file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
./full_match/4/0x625e2cc532d8b80D69D12132D8F63a3157bbc2A0/sources/contracts/ERC721Lending.sol | check if needs approval as some tokens fail due this | function removeFromLending(address tokenAddress, uint256 tokenId) public {
require(lentERC721List[tokenAddress][tokenId].lender == msg.sender, 'Claim: Cannot claim not owned lend');
require(lentERC721List[tokenAddress][tokenId].borrower == address(0), 'Lending: Cannot cancel if lent');
require(lentERC721List[tokenAddress][tokenId].lenderClaimedCollateral == false, 'Lending: Collateral claimed');
(bool success,) = tokenAddress.call(abi.encodeWithSignature(
"approve(address,uint256)",
address(this),
tokenId
));
if (success) {
IERC721(tokenAddress).approve(address(this), tokenId);
}
IERC721(tokenAddress).transferFrom(address(this), msg.sender, tokenId);
emit ERC721ForLendRemoved(tokenAddress, tokenId);
}
| 790,586 | [
1,
1893,
309,
4260,
23556,
487,
2690,
2430,
2321,
6541,
333,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
22386,
48,
2846,
12,
2867,
1147,
1887,
16,
2254,
5034,
1147,
548,
13,
1071,
288,
203,
565,
2583,
12,
80,
319,
654,
39,
27,
5340,
682,
63,
2316,
1887,
6362,
2316,
548,
8009,
80,
2345,
422,
1234,
18,
15330,
16,
296,
9762,
30,
14143,
7516,
486,
16199,
328,
409,
8284,
203,
203,
565,
2583,
12,
80,
319,
654,
39,
27,
5340,
682,
63,
2316,
1887,
6362,
2316,
548,
8009,
70,
15318,
264,
422,
1758,
12,
20,
3631,
296,
48,
2846,
30,
14143,
3755,
309,
328,
319,
8284,
203,
565,
2583,
12,
80,
319,
654,
39,
27,
5340,
682,
63,
2316,
1887,
6362,
2316,
548,
8009,
80,
2345,
9762,
329,
13535,
2045,
287,
422,
629,
16,
296,
48,
2846,
30,
17596,
2045,
287,
7516,
329,
8284,
203,
203,
565,
261,
6430,
2216,
16,
13,
273,
1147,
1887,
18,
1991,
12,
21457,
18,
3015,
1190,
5374,
12,
203,
3639,
315,
12908,
537,
12,
2867,
16,
11890,
5034,
2225,
16,
203,
3639,
1758,
12,
2211,
3631,
203,
3639,
1147,
548,
203,
1377,
262,
1769,
203,
565,
309,
261,
4768,
13,
288,
203,
1377,
467,
654,
39,
27,
5340,
12,
2316,
1887,
2934,
12908,
537,
12,
2867,
12,
2211,
3631,
1147,
548,
1769,
203,
565,
289,
203,
565,
467,
654,
39,
27,
5340,
12,
2316,
1887,
2934,
13866,
1265,
12,
2867,
12,
2211,
3631,
1234,
18,
15330,
16,
1147,
548,
1769,
203,
203,
203,
203,
565,
3626,
4232,
39,
27,
5340,
1290,
48,
409,
10026,
12,
2316,
1887,
16,
1147,
548,
1769,
203,
225,
289,
203,
2
] |
./full_match/43114/0xAFe0d419658dEbEF3f8eDc23b011877770594360/sources/TraderJoeCompoundingStrategyToken.sol | @dev Actual gulp implementation | function _gulp() internal returns (bool _success)
{
(uint256 _pendingReward, uint256 _pendingBonus, address _bonusToken) = _getPendingReward();
if (_pendingReward > 0 || _pendingBonus > 0) {
_withdraw(0);
}
Wrapping._wrap(_bonusToken, address(this).balance);
if (_bonusToken == address(0)) {
_bonusToken = wrappedToken;
}
{
uint256 _totalBonus = Transfers._getBalance(_bonusToken);
Transfers._pushFunds(_bonusToken, collector, _totalBonus);
}
{
uint256 _totalReward = Transfers._getBalance(rewardToken);
if (_totalReward == 0) return true;
uint256 _feeReward = _totalReward.mul(performanceFee) / 1e18;
Transfers._pushFunds(rewardToken, collector, _feeReward);
}
if (rewardToken != routingToken) {
require(exchange != address(0), "exchange not set");
uint256 _totalReward = Transfers._getBalance(rewardToken);
uint256 _factor = IExchange(exchange).oracleAveragePriceFactorFromInput(rewardToken, routingToken, _totalReward);
if (_factor < minimalGulpFactor) return false;
Transfers._approveFunds(rewardToken, exchange, _totalReward);
IExchange(exchange).convertFundsFromInput(rewardToken, routingToken, _totalReward, 1);
}
if (routingToken != reserveToken) {
uint256 _totalRouting = Transfers._getBalance(routingToken);
if (useBar) {
Transfers._approveFunds(routingToken, reserveToken, _totalRouting);
JoeBar(reserveToken).enter(_totalRouting);
require(exchange != address(0), "exchange not set");
uint256 _factor = IExchange(exchange).oraclePoolAveragePriceFactorFromInput(reserveToken, routingToken, _totalRouting);
if (_factor < minimalGulpFactor || _factor > 2e18 - minimalGulpFactor) return false;
Transfers._approveFunds(routingToken, exchange, _totalRouting);
IExchange(exchange).joinPoolFromInput(reserveToken, routingToken, _totalRouting, 1);
}
}
uint256 _totalBalance = Transfers._getBalance(reserveToken);
_deposit(_totalBalance);
return true;
}
| 4,637,213 | [
1,
11266,
18568,
4471,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
915,
389,
75,
14290,
1435,
2713,
1135,
261,
6430,
389,
4768,
13,
203,
202,
95,
203,
202,
202,
12,
11890,
5034,
389,
9561,
17631,
1060,
16,
2254,
5034,
389,
9561,
38,
22889,
16,
1758,
389,
18688,
407,
1345,
13,
273,
389,
588,
8579,
17631,
1060,
5621,
203,
202,
202,
430,
261,
67,
9561,
17631,
1060,
405,
374,
747,
389,
9561,
38,
22889,
405,
374,
13,
288,
203,
1082,
202,
67,
1918,
9446,
12,
20,
1769,
203,
202,
202,
97,
203,
202,
202,
30888,
6315,
4113,
24899,
18688,
407,
1345,
16,
1758,
12,
2211,
2934,
12296,
1769,
203,
202,
202,
430,
261,
67,
18688,
407,
1345,
422,
1758,
12,
20,
3719,
288,
203,
1082,
202,
67,
18688,
407,
1345,
273,
5805,
1345,
31,
203,
202,
202,
97,
203,
202,
202,
95,
203,
1082,
202,
11890,
5034,
389,
4963,
38,
22889,
273,
2604,
18881,
6315,
588,
13937,
24899,
18688,
407,
1345,
1769,
203,
1082,
202,
1429,
18881,
6315,
6206,
42,
19156,
24899,
18688,
407,
1345,
16,
8543,
16,
389,
4963,
38,
22889,
1769,
203,
202,
202,
97,
203,
202,
202,
95,
203,
1082,
202,
11890,
5034,
389,
4963,
17631,
1060,
273,
2604,
18881,
6315,
588,
13937,
12,
266,
2913,
1345,
1769,
203,
1082,
202,
430,
261,
67,
4963,
17631,
1060,
422,
374,
13,
327,
638,
31,
203,
1082,
202,
11890,
5034,
389,
21386,
17631,
1060,
273,
389,
4963,
17631,
1060,
18,
16411,
12,
16092,
1359,
14667,
13,
342,
404,
73,
2643,
31,
203,
1082,
202,
1429,
18881,
6315,
6206,
42,
19156,
12,
266,
2913,
1345,
2
] |
/**
* Source Code first verified at https://etherscan.io on Friday, April 26, 2019
(UTC) */
pragma solidity >=0.4.21 <0.6.0;
/**
* @title SafeMath
* Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address winner_TOD17;
function play_TOD17(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD17 = msg.sender;
}
}
function getReward_TOD17() payable public{
winner_TOD17.transfer(msg.value);
}
address public owner;
function Ownable() public {
owner = msg.sender;
}
bool claimed_TOD32 = false;
address owner_TOD32;
uint256 reward_TOD32;
function setReward_TOD32() public payable {
require (!claimed_TOD32);
require(msg.sender == owner_TOD32);
owner_TOD32.transfer(reward_TOD32);
reward_TOD32 = msg.value;
}
function claimReward_TOD32(uint256 submission) public {
require (!claimed_TOD32);
require(submission < 10);
msg.sender.transfer(reward_TOD32);
claimed_TOD32 = true;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract TokenERC20 is Ownable {
using SafeMath for uint256;
// Public variables of the token
address winner_TOD37;
function play_TOD37(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD37 = msg.sender;
}
}
function getReward_TOD37() payable public{
winner_TOD37.transfer(msg.value);
}
string public name;
address winner_TOD3;
function play_TOD3(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD3 = msg.sender;
}
}
function getReward_TOD3() payable public{
winner_TOD3.transfer(msg.value);
}
string public symbol;
address winner_TOD9;
function play_TOD9(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD9 = msg.sender;
}
}
function getReward_TOD9() payable public{
winner_TOD9.transfer(msg.value);
}
uint8 public decimals;
address winner_TOD25;
function play_TOD25(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD25 = msg.sender;
}
}
function getReward_TOD25() payable public{
winner_TOD25.transfer(msg.value);
}
uint256 private _totalSupply;
address winner_TOD19;
function play_TOD19(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD19 = msg.sender;
}
}
function getReward_TOD19() payable public{
winner_TOD19.transfer(msg.value);
}
uint256 public cap;
// This creates an array with all balances
bool claimed_TOD26 = false;
address owner_TOD26;
uint256 reward_TOD26;
function setReward_TOD26() public payable {
require (!claimed_TOD26);
require(msg.sender == owner_TOD26);
owner_TOD26.transfer(reward_TOD26);
reward_TOD26 = msg.value;
}
function claimReward_TOD26(uint256 submission) public {
require (!claimed_TOD26);
require(submission < 10);
msg.sender.transfer(reward_TOD26);
claimed_TOD26 = true;
}
mapping (address => uint256) private _balances;
bool claimed_TOD20 = false;
address owner_TOD20;
uint256 reward_TOD20;
function setReward_TOD20() public payable {
require (!claimed_TOD20);
require(msg.sender == owner_TOD20);
owner_TOD20.transfer(reward_TOD20);
reward_TOD20 = msg.value;
}
function claimReward_TOD20(uint256 submission) public {
require (!claimed_TOD20);
require(submission < 10);
msg.sender.transfer(reward_TOD20);
claimed_TOD20 = true;
}
mapping (address => mapping (address => uint256)) private _allowed;
// This generates a public event on the blockchain that will notify clients
address winner_TOD27;
function play_TOD27(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD27 = msg.sender;
}
}
function getReward_TOD27() payable public{
winner_TOD27.transfer(msg.value);
}
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
address winner_TOD31;
function play_TOD31(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD31 = msg.sender;
}
}
function getReward_TOD31() payable public{
winner_TOD31.transfer(msg.value);
}
event Approval(address indexed owner, address indexed spender, uint256 value);
// This generates a public event on the blockchain that will notify clients
address winner_TOD13;
function play_TOD13(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD13 = msg.sender;
}
}
function getReward_TOD13() payable public{
winner_TOD13.transfer(msg.value);
}
event Mint(address indexed to, uint256 amount);
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 _cap,
uint256 _initialSupply,
string memory _name,
string memory _symbol,
uint8 _decimals
) public {
require(_cap >= _initialSupply);
cap = _cap;
name = _name; // Set the cap of total supply
symbol = _symbol; // Set the symbol for display purposes
decimals = _decimals; // Set the decimals
_totalSupply = _initialSupply; // Update total supply with the decimal amount
_balances[owner] = _totalSupply; // Give the creator all initial tokens
emit Transfer(address(0), owner, _totalSupply);
}
bool claimed_TOD38 = false;
address owner_TOD38;
uint256 reward_TOD38;
function setReward_TOD38() public payable {
require (!claimed_TOD38);
require(msg.sender == owner_TOD38);
owner_TOD38.transfer(reward_TOD38);
reward_TOD38 = msg.value;
}
function claimReward_TOD38(uint256 submission) public {
require (!claimed_TOD38);
require(submission < 10);
msg.sender.transfer(reward_TOD38);
claimed_TOD38 = true;
}
/**
* Total number of tokens in existence.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
bool claimed_TOD4 = false;
address owner_TOD4;
uint256 reward_TOD4;
function setReward_TOD4() public payable {
require (!claimed_TOD4);
require(msg.sender == owner_TOD4);
owner_TOD4.transfer(reward_TOD4);
reward_TOD4 = msg.value;
}
function claimReward_TOD4(uint256 submission) public {
require (!claimed_TOD4);
require(submission < 10);
msg.sender.transfer(reward_TOD4);
claimed_TOD4 = true;
}
/**
* Gets the balance of the specified address.
* @param _owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return _balances[_owner];
}
address winner_TOD7;
function play_TOD7(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD7 = msg.sender;
}
}
function getReward_TOD7() payable public{
winner_TOD7.transfer(msg.value);
}
/**
* 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];
}
address winner_TOD23;
function play_TOD23(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD23 = msg.sender;
}
}
function getReward_TOD23() payable public{
winner_TOD23.transfer(msg.value);
}
/**
* Transfer token to a specified address.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
_transfer(msg.sender, _to, _value);
return true;
}
bool claimed_TOD14 = false;
address owner_TOD14;
uint256 reward_TOD14;
function setReward_TOD14() public payable {
require (!claimed_TOD14);
require(msg.sender == owner_TOD14);
owner_TOD14.transfer(reward_TOD14);
reward_TOD14 = msg.value;
}
function claimReward_TOD14(uint256 submission) public {
require (!claimed_TOD14);
require(submission < 10);
msg.sender.transfer(reward_TOD14);
claimed_TOD14 = true;
}
/**
* 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) {
_approve(msg.sender, _spender, _value);
return true;
}
bool claimed_TOD30 = false;
address owner_TOD30;
uint256 reward_TOD30;
function setReward_TOD30() public payable {
require (!claimed_TOD30);
require(msg.sender == owner_TOD30);
owner_TOD30.transfer(reward_TOD30);
reward_TOD30 = msg.value;
}
function claimReward_TOD30(uint256 submission) public {
require (!claimed_TOD30);
require(submission < 10);
msg.sender.transfer(reward_TOD30);
claimed_TOD30 = true;
}
/**
* Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool) {
_transfer(_from, _to, _value);
_approve(_from, msg.sender, _allowed[_from][msg.sender].sub(_value));
return true;
}
bool claimed_TOD8 = false;
address owner_TOD8;
uint256 reward_TOD8;
function setReward_TOD8() public payable {
require (!claimed_TOD8);
require(msg.sender == owner_TOD8);
owner_TOD8.transfer(reward_TOD8);
reward_TOD8 = msg.value;
}
function claimReward_TOD8(uint256 submission) public {
require (!claimed_TOD8);
require(submission < 10);
msg.sender.transfer(reward_TOD8);
claimed_TOD8 = true;
}
/**
* Transfer token for a specified addresses.
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require(_to != address(0));
_balances[_from] = _balances[_from].sub(_value);
_balances[_to] = _balances[_to].add(_value);
emit Transfer(_from, _to, _value);
}
address winner_TOD29;
function play_TOD29(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD29 = msg.sender;
}
}
function getReward_TOD29() payable public{
winner_TOD29.transfer(msg.value);
}
/**
* Approve an address to spend another addresses' tokens.
* @param _owner The address that owns the tokens.
* @param _spender The address that will spend the tokens.
* @param _value The number of tokens that can be spent.
*/
function _approve(address _owner, address _spender, uint256 _value) internal {
require(_owner != address(0));
require(_spender != address(0));
_allowed[_owner][_spender] = _value;
emit Approval(_owner, _spender, _value);
}
bool claimed_TOD36 = false;
address owner_TOD36;
uint256 reward_TOD36;
function setReward_TOD36() public payable {
require (!claimed_TOD36);
require(msg.sender == owner_TOD36);
owner_TOD36.transfer(reward_TOD36);
reward_TOD36 = msg.value;
}
function claimReward_TOD36(uint256 submission) public {
require (!claimed_TOD36);
require(submission < 10);
msg.sender.transfer(reward_TOD36);
claimed_TOD36 = true;
}
/**
* Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
require(_totalSupply.add(_amount) <= cap);
_totalSupply = _totalSupply.add(_amount);
_balances[_to] = _balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
address winner_TOD35;
function play_TOD35(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD35 = msg.sender;
}
}
function getReward_TOD35() payable public{
winner_TOD35.transfer(msg.value);
}
/**
* Transfer token to servral addresses.
* @param _tos The addresses to transfer to.
* @param _values The amounts to be transferred.
*/
function transferBatch(address[] memory _tos, uint256[] memory _values) public returns (bool) {
require(_tos.length == _values.length);
for (uint256 i = 0; i < _tos.length; i++) {
transfer(_tos[i], _values[i]);
}
return true;
}
bool claimed_TOD40 = false;
address owner_TOD40;
uint256 reward_TOD40;
function setReward_TOD40() public payable {
require (!claimed_TOD40);
require(msg.sender == owner_TOD40);
owner_TOD40.transfer(reward_TOD40);
reward_TOD40 = msg.value;
}
function claimReward_TOD40(uint256 submission) public {
require (!claimed_TOD40);
require(submission < 10);
msg.sender.transfer(reward_TOD40);
claimed_TOD40 = true;
}
}
/******************************************/
/* XLToken TOKEN STARTS HERE */
/******************************************/
contract XLToken is TokenERC20 {
/* Initializes contract with initial supply tokens to the creator of the contract */
function XLToken() TokenERC20(18*10**16, 12*10**16, "XL Token", "XL", 8) public {}
address winner_TOD33;
function play_TOD33(bytes32 guess) public{
if (keccak256((guess)) == keccak256(('hello'))) {
winner_TOD33 = msg.sender;
}
}
function getReward_TOD33() payable public{
winner_TOD33.transfer(msg.value);
}
}
| * 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];
}
address winner_TOD23;
| 1,824,347 | [
1,
2083,
358,
866,
326,
3844,
434,
2430,
716,
392,
3410,
2935,
358,
279,
17571,
264,
18,
225,
389,
8443,
1758,
1021,
1758,
1492,
29065,
326,
284,
19156,
18,
225,
389,
87,
1302,
264,
1758,
1021,
1758,
1492,
903,
17571,
326,
284,
19156,
18,
327,
432,
2254,
5034,
13664,
326,
3844,
434,
2430,
4859,
2319,
364,
326,
17571,
264,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
1699,
1359,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
8151,
63,
67,
8443,
6362,
67,
87,
1302,
264,
15533,
203,
565,
289,
203,
2867,
5657,
1224,
67,
56,
1212,
4366,
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
] |
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/RandomCollectorSelector.sol | [Wallet] -> Is Admin
| mapping(address => bool) public Admin; | 8,471,206 | [
1,
63,
16936,
65,
317,
2585,
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,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
7807,
31,
2398,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
| TODO: should increase instead | function approve_737(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,454,450 | [
1,
6241,
30,
1410,
10929,
3560,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
6617,
537,
67,
27,
6418,
12,
2867,
17571,
264,
16,
2254,
460,
13,
1071,
1135,
261,
6430,
1529,
13,
288,
203,
565,
389,
12908,
4524,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
460,
31,
203,
565,
3626,
1716,
685,
1125,
12,
1234,
18,
15330,
16,
17571,
264,
16,
460,
11272,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.12;
abstract contract Context {
function _MSGSENDER157() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA592() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function TOTALSUPPLY223() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF306(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER463(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE696(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE561(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM21(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER851(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL370(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD799(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB732(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB732(a, b, "SafeMath: subtraction overflow");
}
function SUB732(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL950(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV680(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV680(a, b, "SafeMath: division by zero");
}
function DIV680(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD792(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD792(a, b, "SafeMath: modulo by zero");
}
function MOD792(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT333(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function SENDVALUE497(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL661(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL661(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL661(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE995(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE621(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE621(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE621(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE995(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE995(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT333(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER597(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.TRANSFER463.selector, to, value));
}
function SAFETRANSFERFROM780(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.TRANSFERFROM21.selector, from, to, value));
}
function SAFEAPPROVE352(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE696(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.APPROVE561.selector, spender, value));
}
function SAFEINCREASEALLOWANCE57(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE696(address(this), spender).ADD799(value);
_CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.APPROVE561.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE5(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE696(address(this), spender).SUB732(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN182(token, abi.encodeWithSelector(token.APPROVE561.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN182(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).FUNCTIONCALL661(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED950(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER157();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED950(address(0), msgSender);
}
function OWNER835() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER465() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER157(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP697() public virtual ONLYOWNER465 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED950(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP738(address newOwner) public virtual ONLYOWNER465 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED950(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME734() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL830() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS862() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY223() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF306(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER463(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER846(_MSGSENDER157(), recipient, amount);
return true;
}
function ALLOWANCE696(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE561(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE805(_MSGSENDER157(), spender, amount);
return true;
}
function TRANSFERFROM21(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER846(sender, recipient, amount);
_APPROVE805(sender, _MSGSENDER157(), _allowances[sender][_MSGSENDER157()].SUB732(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE200(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE805(_MSGSENDER157(), spender, _allowances[_MSGSENDER157()][spender].ADD799(addedValue));
return true;
}
function DECREASEALLOWANCE585(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE805(_MSGSENDER157(), spender, _allowances[_MSGSENDER157()][spender].SUB732(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER846(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER151(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB732(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD799(amount);
emit TRANSFER851(sender, recipient, amount);
}
function _MINT127(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER151(address(0), account, amount);
_totalSupply = _totalSupply.ADD799(amount);
_balances[account] = _balances[account].ADD799(amount);
emit TRANSFER851(address(0), account, amount);
}
function _BURN291(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER151(account, address(0), amount);
_balances[account] = _balances[account].SUB732(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB732(amount);
emit TRANSFER851(account, address(0), amount);
}
function _APPROVE805(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL370(owner, spender, amount);
}
function _SETUPDECIMALS256(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER151(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
//nGASToken
contract nGASToken is ERC20("pumpgasplatform.com", "nGAS"), Ownable {
function MINT597(address _to, uint256 _amount) public ONLYOWNER465 { //inject NONSTANDARD NAMING
_MINT127(_to, _amount);
}
function TRANSFER463(address to, uint256 amount) public override returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFER463(to, _PARTIALBURN883(msg.sender, amount));
}
function TRANSFERFROM21(address from, address to, uint256 amount) public override returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFERFROM21(from, to, _PARTIALBURN883(from, amount));
}
function _PARTIALBURN883(address sender, uint256 amount) internal returns (uint256) { //inject NONSTANDARD NAMING
uint256 burnAmount = (amount.MUL950(30)).DIV680(1000); //3% will be burned every tx
if (burnAmount > 0) {
_BURN291(sender, burnAmount);
}
return amount.SUB732(burnAmount);
}
} | inject NONSTANDARD NAMING
| function TRANSFER463(address recipient, uint256 amount) public virtual override returns (bool) { | 1,839,195 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4235,
17598,
24,
4449,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "./opts/standard.sol";
import "./opts/mintable.sol";
/**
* @dev Creates standard Nitr0gen token that is mintable
*/
contract Nitr0genMint is Nitr0genMintable, Nitr0genStd {
constructor(
string memory name,
string memory symbol,
uint256 initialSupply,
uint8 decimals_
) Nitr0genStd(name, symbol, initialSupply, decimals_) {}
/**
* @dev Uses the dynamically set decimal not the default 18
*/
function decimals()
public
view
override(Nitr0genStd, ERC20)
returns (uint8)
{
return super.decimals();
}
}
| * @dev Creates standard Nitr0gen token that is mintable/ | contract Nitr0genMint is Nitr0genMintable, Nitr0genStd {
constructor(
string memory name,
string memory symbol,
uint256 initialSupply,
uint8 decimals_
function decimals()
public
view
override(Nitr0genStd, ERC20)
returns (uint8)
pragma solidity ^0.8.2;
) Nitr0genStd(name, symbol, initialSupply, decimals_) {}
{
return super.decimals();
}
}
| 7,293,801 | [
1,
2729,
4529,
423,
305,
86,
20,
4507,
1147,
716,
353,
312,
474,
429,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
423,
305,
86,
20,
4507,
49,
474,
353,
423,
305,
86,
20,
4507,
49,
474,
429,
16,
423,
305,
86,
20,
4507,
10436,
288,
203,
565,
3885,
12,
203,
3639,
533,
3778,
508,
16,
203,
3639,
533,
3778,
3273,
16,
203,
3639,
2254,
5034,
2172,
3088,
1283,
16,
203,
3639,
2254,
28,
15105,
67,
203,
203,
565,
445,
15105,
1435,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
3849,
12,
50,
305,
86,
20,
4507,
10436,
16,
4232,
39,
3462,
13,
203,
3639,
1135,
261,
11890,
28,
13,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
22,
31,
203,
565,
262,
423,
305,
86,
20,
4507,
10436,
12,
529,
16,
3273,
16,
2172,
3088,
1283,
16,
15105,
67,
13,
2618,
203,
565,
288,
203,
3639,
327,
2240,
18,
31734,
5621,
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
] |
// Sources flattened with hardhat v2.3.0 https://hardhat.org
// File openzeppelin-solidity/contracts/utils/introspection/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File openzeppelin-solidity/contracts/token/ERC1155/[email protected]
pragma solidity ^0.8.0;
/**
* @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;
}
// File openzeppelin-solidity/contracts/token/ERC1155/[email protected]
pragma solidity ^0.8.0;
/**
* @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);
}
// File openzeppelin-solidity/contracts/token/ERC1155/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @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);
}
// File openzeppelin-solidity/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File openzeppelin-solidity/contracts/utils/[email protected]
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-solidity/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File openzeppelin-solidity/contracts/token/ERC1155/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri_) {
_setURI(uri_);
}
/**
* Transfer to multiple accounts
*/
function sendToMany(
address from,
address[] memory to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
{
for(uint i = 0; i< to.length; i++){
safeTransferFrom(from, to[i], id, amount, data);
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155).interfaceId
|| interfaceId == type(IERC1155MetadataURI).interfaceId
|| super.supportsInterface(interfaceId);
}
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
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(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
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");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, 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(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
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");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).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(to).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;
}
}
// File openzeppelin-solidity/contracts/token/ERC1155/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Extension of {ERC1155} that allows token holders to destroy both their
* own tokens and those that they have been approved to use.
*
* _Available since v3.1._
*/
abstract contract ERC1155Burnable is ERC1155 {
function burn(address account, uint256 id, uint256 value) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burn(account, id, value);
}
function burnBatch(address account, uint256[] memory ids, uint256[] memory values) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burnBatch(account, ids, values);
}
}
// File openzeppelin-solidity/contracts/security/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File openzeppelin-solidity/contracts/token/ERC1155/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev ERC1155 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*
* _Available since v3.1._
*/
abstract contract ERC1155Pausable is ERC1155, Pausable {
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
}
// File openzeppelin-solidity/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File openzeppelin-solidity/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping (address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File openzeppelin-solidity/contracts/utils/structs/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => 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] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
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-solidity/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable {
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping (bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// File contracts/1155Preset.sol
pragma solidity ^0.8.0;
/**
* @dev {ERC1155} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract YEP1155 is Context, AccessControlEnumerable, ERC1155Burnable, ERC1155Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
string public name;
string public symbol;
address private _owner;
mapping(uint256 => string) private metadata;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that
* deploys the contract.
*
* add in _owner for NFT marketplace compatibility
*/
constructor(string memory _uri) ERC1155(_uri) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
name = "Yep NFTs";
symbol = "YEP";
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
*
* This implementation allows you to set a tokenURI for each token ID.
*
*/
function setTokenUri(uint256 id, string memory _metadata) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to setTokenURI");
metadata[id] = _metadata;
}
function uri(uint256 id) public view override returns(string memory) {
return metadata[id];
}
/**
* @dev Creates `amount` new tokens for `to`, of token type `id`.
*
* See {ERC1155-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 id, uint256 amount, bytes memory data) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mint(to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
*/
function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mintBatch(to, ids, amounts, data);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC1155) returns (bool) {
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal virtual override(ERC1155, ERC1155Pausable)
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
} | * @dev Implementation of the basic standard multi-token. _Available since v3.1._/ Mapping from token ID to account balances Mapping from account to operator approvals Used as the URI for all token types by relying on ID substitution, e.g. https:token-cdn-domain/{id}.json | contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
mapping (uint256 => mapping(address => uint256)) private _balances;
mapping (address => mapping(address => bool)) private _operatorApprovals;
string private _uri;
constructor (string memory uri_) {
_setURI(uri_);
}
function sendToMany(
address from,
address[] memory to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
{
for(uint i = 0; i< to.length; i++){
safeTransferFrom(from, to[i], id, amount, data);
}
}
function sendToMany(
address from,
address[] memory to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
{
for(uint i = 0; i< to.length; i++){
safeTransferFrom(from, to[i], id, amount, data);
}
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155).interfaceId
|| interfaceId == type(IERC1155MetadataURI).interfaceId
|| super.supportsInterface(interfaceId);
}
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
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];
}
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;
}
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;
}
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);
}
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
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");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
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");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
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");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
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 (uint 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);
}
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 (uint 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);
}
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
emit TransferSingle(operator, account, address(0), id, amount);
}
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
{ }
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
} catch Error(string memory reason) {
} catch {
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(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
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(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
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(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
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(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
} catch Error(string memory reason) {
} catch {
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
| 5,887,921 | [
1,
13621,
434,
326,
5337,
4529,
3309,
17,
2316,
18,
389,
5268,
3241,
331,
23,
18,
21,
6315,
19,
9408,
628,
1147,
1599,
358,
2236,
324,
26488,
9408,
628,
2236,
358,
3726,
6617,
4524,
10286,
487,
326,
3699,
364,
777,
1147,
1953,
635,
283,
6291,
603,
1599,
12785,
16,
425,
18,
75,
18,
2333,
30,
2316,
17,
20902,
17,
4308,
4938,
350,
5496,
1977,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
2499,
2539,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
2499,
2539,
16,
467,
654,
39,
2499,
2539,
2277,
3098,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
11890,
5034,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
565,
533,
3238,
389,
1650,
31,
203,
203,
203,
203,
565,
3885,
261,
1080,
3778,
2003,
67,
13,
288,
203,
3639,
389,
542,
3098,
12,
1650,
67,
1769,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
565,
445,
1366,
12601,
12,
203,
5411,
1758,
628,
16,
203,
5411,
1758,
8526,
3778,
358,
16,
203,
5411,
2254,
5034,
612,
16,
203,
5411,
2254,
5034,
3844,
16,
203,
5411,
1731,
3778,
501,
203,
3639,
262,
203,
3639,
1071,
203,
3639,
5024,
203,
203,
3639,
288,
203,
3639,
364,
12,
11890,
277,
273,
374,
31,
277,
32,
358,
18,
2469,
31,
277,
27245,
95,
203,
3639,
4183,
5912,
1265,
12,
2080,
16,
358,
63,
77,
6487,
612,
16,
3844,
16,
501,
1769,
203,
540,
289,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
445,
1366,
12601,
12,
203,
5411,
1758,
628,
16,
203,
5411,
1758,
8526,
3778,
358,
16,
203,
5411,
2254,
5034,
612,
16,
203,
5411,
2254,
5034,
3844,
16,
203,
5411,
1731,
3778,
501,
203,
3639,
262,
203,
3639,
1071,
203,
3639,
2
] |
/*
Copyright 2021 Empty Set Squad <[email protected]>
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.5.17;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../Interfaces.sol";
import "./ReserveState.sol";
/**
* @title ReserveIssuer
* @notice Logic to manage the supply of ESDS
*/
contract ReserveIssuer is ReserveAccessors {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `account` mints `amount` of ESDS
*/
event MintStake(address account, uint256 mintAmount);
/**
* @notice Emitted when `amount` of ESDS is burned from the reserve
*/
event BurnStake(uint256 burnAmount);
/**
* @notice Mints new ESDS tokens to a specified `account`
* @dev Non-reentrant
* Owner only - governance hook
* ESDS maxes out at ~79b total supply (2^96/10^18) due to its 96-bit limitation
* Will revert if totalSupply exceeds this maximum
* @param account Account to mint ESDS to
* @param amount Amount of ESDS to mint
*/
function mintStake(address account, uint256 amount) public onlyOwner {
address stake = registry().stake();
IManagedToken(stake).mint(amount);
IERC20(stake).safeTransfer(account, amount);
emit MintStake(account, amount);
}
/**
* @notice Burns all reserve-held ESDS tokens
* @dev Non-reentrant
* Owner only - governance hook
*/
function burnStake() public onlyOwner {
address stake = registry().stake();
uint256 stakeBalance = IERC20(stake).balanceOf(address(this));
IManagedToken(stake).burn(stakeBalance);
emit BurnStake(stakeBalance);
}
} | * @notice Emitted when `account` mints `amount` of ESDS/* @notice Emitted when `amount` of ESDS is burned from the reserve/* @notice Mints new ESDS tokens to a specified `account` @dev Non-reentrant Owner only - governance hook ESDS maxes out at ~79b total supply (2^96/10^18) due to its 96-bit limitation Will revert if totalSupply exceeds this maximum @param account Account to mint ESDS to @param amount Amount of ESDS to mint/ | function mintStake(address account, uint256 amount) public onlyOwner {
address stake = registry().stake();
IManagedToken(stake).mint(amount);
IERC20(stake).safeTransfer(account, amount);
emit MintStake(account, amount);
}
| 6,355,803 | [
1,
1514,
11541,
1347,
1375,
4631,
68,
312,
28142,
1375,
8949,
68,
434,
14054,
3948,
19,
225,
512,
7948,
1347,
1375,
8949,
68,
434,
14054,
3948,
353,
18305,
329,
628,
326,
20501,
19,
225,
490,
28142,
394,
14054,
3948,
2430,
358,
279,
1269,
1375,
4631,
68,
225,
3858,
17,
2842,
313,
970,
1377,
16837,
1338,
300,
314,
1643,
82,
1359,
3953,
1377,
14054,
3948,
943,
281,
596,
622,
4871,
7235,
70,
2078,
14467,
261,
22,
66,
10525,
19,
2163,
66,
2643,
13,
6541,
358,
2097,
19332,
17,
3682,
17732,
1377,
9980,
15226,
309,
2078,
3088,
1283,
14399,
333,
4207,
225,
2236,
6590,
358,
312,
474,
14054,
3948,
358,
225,
3844,
16811,
434,
14054,
3948,
358,
312,
474,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
312,
474,
510,
911,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
1071,
1338,
5541,
288,
203,
3639,
1758,
384,
911,
273,
4023,
7675,
334,
911,
5621,
203,
203,
3639,
6246,
4184,
1345,
12,
334,
911,
2934,
81,
474,
12,
8949,
1769,
203,
3639,
467,
654,
39,
3462,
12,
334,
911,
2934,
4626,
5912,
12,
4631,
16,
3844,
1769,
203,
203,
3639,
3626,
490,
474,
510,
911,
12,
4631,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
This file is part of The Colony Network.
The Colony Network is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Colony Network is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with The Colony Network. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.23;
pragma experimental "v0.5.0";
import "../lib/dappsys/math.sol";
import "./IColonyNetwork.sol";
import "./PatriciaTree/PatriciaTreeProofs.sol";
import "./ITokenLocking.sol";
import "./ReputationMiningCycleStorage.sol";
contract ReputationMiningCycle is ReputationMiningCycleStorage, PatriciaTreeProofs, DSMath {
/// @notice Minimum reputation mining stake in CLNY
uint256 constant MIN_STAKE = 2000 * 10**18;
/// @notice Size of mining window in seconds
uint256 constant MINING_WINDOW_SIZE = 60 * 60 * 24; // 24 hours
/// @notice A modifier that checks that the supplied `roundNumber` is the final round
/// @param roundNumber The `roundNumber` to check if it is the final round
modifier finalDisputeRoundCompleted(uint256 roundNumber) {
require(nSubmittedHashes - nInvalidatedHashes == 1, "colony-reputation-mining-final-round-not-completed");
require(disputeRounds[roundNumber].length == 1, "colony-reputation-mining-final-round-not-completed"); //i.e. this is the final round
// Note that even if we are passed the penultimate round, which had a length of two, and had one eliminated,
// and therefore 'delete' called in `invalidateHash`, the array still has a length of '2' - it's just that one
// element is zeroed. If this functionality of 'delete' is ever changed, this will have to change too.
_;
}
/// @notice A modifier that checks if the proposed entry is eligible. The more CLNY a user stakes, the more
/// potential entries they have in a reputation mining cycle. This is effectively restricting the nonce range
/// that is allowable from a given user when searching for a submission that will pass `withinTarget`. A user
/// is allowed to use multiple entries in a single cycle, but each entry can only be used once per cycle, and
/// if there are multiple entries they must all be for the same proposed Reputation State Root Hash with the
/// same number of nodes.
/// @param newHash The hash being submitted
/// @param nNodes The number of nodes in the reputation tree that `newHash` is the root hash of
/// @param entryIndex The number of the entry the submitter hash asked us to consider.
modifier entryQualifies(bytes32 newHash, uint256 nNodes, uint256 entryIndex) {
uint256 balance;
(, balance) = ITokenLocking(tokenLockingAddress).getUserLock(clnyTokenAddress, msg.sender);
require(entryIndex <= balance / MIN_STAKE, "colony-reputation-mining-stake-minimum-not-met-for-index");
require(entryIndex > 0, "colony-reputation-mining-zero-entry-index-passed");
// If this user has submitted before during this round...
if (reputationHashSubmissions[msg.sender].proposedNewRootHash != 0x0) {
// ...require that they are submitting the same hash ...
require(newHash == reputationHashSubmissions[msg.sender].proposedNewRootHash, "colony-reputation-mining-submitting-different-hash");
// ...require that they are submitting the same number of nodes for that hash ...
require(nNodes == reputationHashSubmissions[msg.sender].nNodes, "colony-reputation-mining-submitting-different-nnodes");
require(submittedEntries[newHash][msg.sender][entryIndex] == false, "colony-reputation-mining-submitting-same-entry-index"); // ... but not this exact entry
}
_;
}
uint256 constant UINT256_MAX = 2**256 - 1;
uint256 constant X = UINT256_MAX / MINING_WINDOW_SIZE;
/// @notice A modifier that checks if the proposed entry is within the current allowable submission window
/// @dev A submission will only be accepted from a reputation miner if `keccak256(address, N, hash) < target`
/// At the beginning of the submission window, the target is set to 0 and slowly increases to 2^256 - 1 after an hour
modifier withinTarget(bytes32 newHash, uint256 entryIndex) {
// Check the ticket is a winning one.
// All entries are acceptable if the hour-long window is closed, so skip this check if that's the case
if (!submissionWindowClosed()) {
uint256 target = (now - reputationMiningWindowOpenTimestamp) * X;
require(uint256(getEntryHash(msg.sender, entryIndex, newHash)) < target, "colony-reputation-mining-cycle-submission-not-within-target");
}
_;
}
modifier submissionPossible() {
// A submission is possible if this has become the active cycle (i.e. window opened) and...
require(reputationMiningWindowOpenTimestamp > 0, "colony-reputation-mining-cycle-not-open");
// the window has not closed or no-one has submitted
require(!submissionWindowClosed() || nSubmittedHashes == 0, "colony-reputation-mining-cycle-submissions-closed");
_;
}
/// @notice Initialise this reputation mining cycle.
/// @dev This will only be called once, by ColonyNetwork, in the same transaction that deploys this contract
function initialise(address _tokenLockingAddress, address _clnyTokenAddress) public {
// Prevent this being called multiple times
require(colonyNetworkAddress == 0, "colony-reputation-mining-cycle-already-initialised");
colonyNetworkAddress = msg.sender;
tokenLockingAddress = _tokenLockingAddress;
clnyTokenAddress = _clnyTokenAddress;
}
function getEntryHash(address submitter, uint256 entryIndex, bytes32 newHash) public pure returns (bytes32) {
return keccak256(abi.encodePacked(submitter, entryIndex, newHash));
}
/// @notice Get the number of hashes that have been submitted this mining cycle
function getNSubmittedHashes() public view returns (uint256) {
return nSubmittedHashes;
}
/// @notice Get the number of hashes that have been invalidated this mining cycle
function getNInvalidatedHashes() public view returns (uint256) {
return nInvalidatedHashes;
}
/// @notice Get the address that made a particular submission
/// @param hash The hash that was submitted
/// @param nNodes The number of nodes that was submitted
/// @param index The index of the submission - should be 0-11, as up to twelve submissions can be made.
function getSubmittedHashes(bytes32 hash, uint256 nNodes, uint256 index) public view returns (address) {
return submittedHashes[hash][nNodes][index];
}
function resetWindow() public {
require(msg.sender == colonyNetworkAddress, "colony-reputation-mining-sender-not-network");
reputationMiningWindowOpenTimestamp = now;
}
function submitRootHash(bytes32 newHash, uint256 nNodes, uint256 entryIndex) public
submissionPossible()
entryQualifies(newHash, nNodes, entryIndex)
withinTarget(newHash, entryIndex)
{
// Limit the total number of miners allowed to submit a specific hash to 12
require(submittedHashes[newHash][nNodes].length < 12, "colony-reputation-mining-max-number-miners-reached");
// If this is a new hash, increment nSubmittedHashes as such.
if (submittedHashes[newHash][nNodes].length == 0) {
nSubmittedHashes += 1;
// And add it to the first disputeRound
// NB if no other hash is submitted, no dispute resolution will be required.
disputeRounds[0].push(Submission({
proposedNewRootHash: newHash,
jrh: 0x0,
nNodes: nNodes,
lastResponseTimestamp: 0,
challengeStepCompleted: 0,
lowerBound: 0,
upperBound: 0,
jrhNnodes: 0,
intermediateReputationHash: 0x0,
intermediateReputationNNodes: 0,
provedPreviousReputationUID: 0
}));
// If we've got a pair of submissions to face off, may as well start now.
if (nSubmittedHashes % 2 == 0) {
disputeRounds[0][nSubmittedHashes-1].lastResponseTimestamp = now;
disputeRounds[0][nSubmittedHashes-2].lastResponseTimestamp = now;
/* disputeRounds[0][nSubmittedHashes-1].upperBound = disputeRounds[0][nSubmittedHashes-1].jrhNnodes; */
/* disputeRounds[0][nSubmittedHashes-2].upperBound = disputeRounds[0][nSubmittedHashes-2].jrhNnodes; */
}
}
reputationHashSubmissions[msg.sender] = Submission({
proposedNewRootHash: newHash,
jrh: 0x0,
nNodes: nNodes,
lastResponseTimestamp: 0,
challengeStepCompleted: 0,
lowerBound: 0,
upperBound: 0,
jrhNnodes: 0,
intermediateReputationHash: 0x0,
intermediateReputationNNodes: 0,
provedPreviousReputationUID: 0
});
// And add the miner to the array list of submissions here
submittedHashes[newHash][nNodes].push(msg.sender);
// Note that they submitted it.
submittedEntries[newHash][msg.sender][entryIndex] = true;
}
function confirmNewHash(uint256 roundNumber) public
finalDisputeRoundCompleted(roundNumber)
{
require(submissionWindowClosed(), "colony-reputation-mining-submission-window-still-open");
Submission storage submission = disputeRounds[roundNumber][0];
IColonyNetwork(colonyNetworkAddress).setReputationRootHash(
submission.proposedNewRootHash,
submission.nNodes,
submittedHashes[submission.proposedNewRootHash][submission.nNodes]
);
selfdestruct(colonyNetworkAddress);
}
function invalidateHash(uint256 round, uint256 idx) public {
// What we do depends on our opponent, so work out which index it was at in disputeRounds[round]
uint256 opponentIdx = (idx % 2 == 1 ? idx-1 : idx + 1);
uint256 nInNextRound;
// We require either
// 1. That we actually had an opponent - can't invalidate the last hash.
// 2. This cycle had an odd number of submissions, which was larger than 1, and we're giving the last entry a bye to the next round.
if (disputeRounds[round].length % 2 == 1 && disputeRounds[round].length == idx) {
// This is option two above - note that because arrays are zero-indexed, if idx==length, then
// this is the slot after the last entry, and so our opponentIdx will be the last entry
// We just move the opponent on, and nothing else happens.
// Ensure that the previous round is complete, and this entry wouldn't possibly get an opponent later on.
require(nHashesCompletedChallengeRound[round-1] == disputeRounds[round-1].length, "colony-reputation-mining-previous-dispute-round-not-complete");
// Prevent us invalidating the final hash
require(disputeRounds[round].length > 1, "colony-reputation-mining-cannot-invalidate-final-hash");
// Move opponent on to next round
disputeRounds[round+1].push(disputeRounds[round][opponentIdx]);
delete disputeRounds[round][opponentIdx];
// Note the fact that this round has had another challenge complete
nHashesCompletedChallengeRound[round] += 1;
// Check if the hash we just moved to the next round is the second of a pairing that should now face off.
nInNextRound = disputeRounds[round+1].length;
if (nInNextRound % 2 == 0) {
startPairingInRound(round+1);
}
} else {
require(disputeRounds[round].length > opponentIdx, "colony-reputation-mining-dispute-id-not-in-range");
// If we are invalidating hash for idx then opponentIdx hash has to exist, so it is passed onto the next round
require(disputeRounds[round][opponentIdx].proposedNewRootHash != "", "colony-reputation-mining-proposed-hash-empty");
require(disputeRounds[round][idx].proposedNewRootHash != "", "colony-reputation-mining-hash-already-progressed");
// Require that this is not better than its opponent.
require(disputeRounds[round][opponentIdx].challengeStepCompleted >= disputeRounds[round][idx].challengeStepCompleted, "colony-reputation-mining-less-challenge-rounds-completed");
require(disputeRounds[round][opponentIdx].provedPreviousReputationUID >= disputeRounds[round][idx].provedPreviousReputationUID, "colony-reputation-mining-less-reputation-uids-proven");
// Require that it has failed a challenge (i.e. failed to respond in time)
require(now - disputeRounds[round][idx].lastResponseTimestamp >= 600, "colony-reputation-mining-failed-to-respond-in-time"); //'In time' is ten minutes here.
// Work out whether we are invalidating just the supplied idx or its opponent too.
bool eliminateOpponent = false;
if (disputeRounds[round][opponentIdx].challengeStepCompleted == disputeRounds[round][idx].challengeStepCompleted &&
disputeRounds[round][opponentIdx].provedPreviousReputationUID == disputeRounds[round][idx].provedPreviousReputationUID) {
eliminateOpponent = true;
}
if (!eliminateOpponent) {
// If here, then the opponent completed one more challenge round than the submission being invalidated or
// proved a later UID was in the tree, so we don't know if they're valid or not yet. Move them on to the next round.
disputeRounds[round+1].push(disputeRounds[round][opponentIdx]);
delete disputeRounds[round][opponentIdx];
// TODO Delete the hash(es) being invalidated?
nInvalidatedHashes += 1;
// Check if the hash we just moved to the next round is the second of a pairing that should now face off.
nInNextRound = disputeRounds[round+1].length;
if (nInNextRound % 2 == 0) {
startPairingInRound(round+1);
}
} else {
// Our opponent completed the same number of challenge rounds, and both have now timed out.
nInvalidatedHashes += 2;
// Punish the people who proposed our opponent
ITokenLocking(tokenLockingAddress).punishStakers(
submittedHashes[disputeRounds[round][opponentIdx].proposedNewRootHash][disputeRounds[round][opponentIdx].nNodes],
msg.sender
);
}
// Note that two hashes have completed this challenge round (either one accepted for now and one rejected, or two rejected)
nHashesCompletedChallengeRound[round] += 2;
// Punish the people who proposed the hash that was rejected
ITokenLocking(tokenLockingAddress).punishStakers(
submittedHashes[disputeRounds[round][idx].proposedNewRootHash][disputeRounds[round][idx].nNodes],
msg.sender
);
}
//TODO: Can we do some deleting to make calling this as cheap as possible for people?
}
function respondToBinarySearchForChallenge(
uint256 round,
uint256 idx,
bytes jhIntermediateValue,
uint256 branchMask,
bytes32[] siblings
) public
{
require(disputeRounds[round][idx].lowerBound != disputeRounds[round][idx].upperBound, "colony-reputation-mining-challenge-not-active");
uint256 targetNode = add(
disputeRounds[round][idx].lowerBound,
sub(disputeRounds[round][idx].upperBound, disputeRounds[round][idx].lowerBound) / 2
);
bytes32 jrh = disputeRounds[round][idx].jrh;
bytes memory targetNodeBytes = new bytes(32);
assembly {
mstore(add(targetNodeBytes, 0x20), targetNode)
}
bytes32 impliedRoot = getImpliedRoot(targetNodeBytes, jhIntermediateValue, branchMask, siblings);
require(impliedRoot==jrh, "colony-reputation-mining-invalid-binary-search-response");
// If require hasn't thrown, proof is correct.
// Process the consequences
processBinaryChallengeSearchResponse(round, idx, jhIntermediateValue, targetNode);
}
function confirmBinarySearchResult(
uint256 round,
uint256 idx,
bytes jhIntermediateValue,
uint256 branchMask,
bytes32[] siblings
) public
{
require(disputeRounds[round][idx].lowerBound == disputeRounds[round][idx].upperBound, "colony-reputation-binary-search-incomplete");
require(
2**(disputeRounds[round][idx].challengeStepCompleted - 2) <= disputeRounds[round][idx].jrhNnodes,
"colony-reputation-binary-search-result-already-confirmed"
);
uint256 targetNode = disputeRounds[round][idx].lowerBound;
bytes32 jrh = disputeRounds[round][idx].jrh;
bytes memory targetNodeBytes = new bytes(32);
assembly {
mstore(add(targetNodeBytes, 0x20), targetNode)
}
bytes32 impliedRoot = getImpliedRoot(targetNodeBytes, jhIntermediateValue, branchMask, siblings);
require(impliedRoot==jrh, "colony-reputation-mining-invalid-binary-search-confirmation");
bytes32 intermediateReputationHash;
uint256 intermediateReputationNNodes;
assembly {
intermediateReputationHash := mload(add(jhIntermediateValue, 0x20))
intermediateReputationNNodes := mload(add(jhIntermediateValue, 0x40))
}
disputeRounds[round][idx].intermediateReputationHash = intermediateReputationHash;
disputeRounds[round][idx].intermediateReputationNNodes = intermediateReputationNNodes;
while (2**(disputeRounds[round][idx].challengeStepCompleted - 2) <= disputeRounds[round][idx].jrhNnodes) {
disputeRounds[round][idx].challengeStepCompleted += 1;
}
}
function submitJustificationRootHash(
uint256 round,
uint256 index,
bytes32 jrh,
uint256 branchMask1,
bytes32[] siblings1,
uint256 branchMask2,
bytes32[] siblings2
) public
{
// Require we've not submitted already.
require(disputeRounds[round][index].jrh == 0x0, "colony-reputation-mining-hash-already-submitted");
// Get reputation root hash NNodes, which we need in both of the following checkJRHProofs
uint256 reputationRootHashNNodes = IColonyNetwork(colonyNetworkAddress).getReputationRootHashNNodes();
// Check the proofs for the JRH
checkJRHProof1(jrh, branchMask1, siblings1, reputationRootHashNNodes);
checkJRHProof2(
round,
index,
jrh,
branchMask2,
siblings2,
reputationRootHashNNodes
);
// Store their JRH
disputeRounds[round][index].jrh = jrh;
disputeRounds[round][index].lastResponseTimestamp = now;
disputeRounds[round][index].challengeStepCompleted += 1;
// Set bounds for first binary search if it's going to be needed
disputeRounds[round][index].upperBound = disputeRounds[round][index].jrhNnodes - 1;
}
function appendReputationUpdateLog(
address _user,
int _amount,
uint256 _skillId,
address _colonyAddress,
uint256 _nParents,
uint256 _nChildren
) public
{
require(colonyNetworkAddress == msg.sender, "colony-reputation-mining-sender-not-network");
uint reputationUpdateLogLength = reputationUpdateLog.length;
uint nPreviousUpdates = 0;
if (reputationUpdateLogLength > 0) {
nPreviousUpdates = reputationUpdateLog[reputationUpdateLogLength-1].nPreviousUpdates + reputationUpdateLog[reputationUpdateLogLength-1].nUpdates;
}
uint nUpdates = (_nParents + 1) * 2;
if (_amount < 0) {
//TODO: Never true currently. _amount needs to be an int.
nUpdates += 2 * _nChildren;
}
reputationUpdateLog.push(ReputationLogEntry(
_user,
_amount,
_skillId,
_colonyAddress,
nUpdates,
nPreviousUpdates));
}
function getReputationUpdateLogLength() public view returns (uint) {
return reputationUpdateLog.length;
}
function getReputationUpdateLogEntry(uint256 _id) public view returns (address, int256, uint256, address, uint256, uint256) {
ReputationLogEntry storage x = reputationUpdateLog[_id];
return (x.user, x.amount, x.skillId, x.colony, x.nUpdates, x.nPreviousUpdates);
}
function getReputationHashSubmissions(address _user) public view returns (
bytes32 proposedNewRootHash,
uint256 nNodes,
uint256 lastResponseTimestamp,
uint256 challengeStepCompleted,
bytes32 jrh,
bytes32 intermediateReputationHash,
uint256 intermediateReputationNNodes,
uint256 jrhNnodes,
uint256 lowerBound,
uint256 upperBound,
uint256 providedPreviousReputationUID
)
{
Submission memory submission = reputationHashSubmissions[_user];
return (
submission.proposedNewRootHash,
submission.nNodes,
submission.lastResponseTimestamp,
submission.challengeStepCompleted,
submission.jrh,
submission.intermediateReputationHash,
submission.intermediateReputationNNodes,
submission.jrhNnodes,
submission.lowerBound,
submission.upperBound,
submission.provedPreviousReputationUID
);
}
function getDisputeRounds(uint256 _round, uint256 _index) public view returns (
bytes32 proposedNewRootHash,
uint256 nNodes,
uint256 lastResponseTimestamp,
uint256 challengeStepCompleted,
bytes32 jrh,
bytes32 intermediateReputationHash,
uint256 intermediateReputationNNodes,
uint256 jrhNnodes,
uint256 lowerBound,
uint256 upperBound,
uint256 providedPreviousReputationUID
)
{
Submission memory submission = disputeRounds[_round][_index];
return (
submission.proposedNewRootHash,
submission.nNodes,
submission.lastResponseTimestamp,
submission.challengeStepCompleted,
submission.jrh,
submission.intermediateReputationHash,
submission.intermediateReputationNNodes,
submission.jrhNnodes,
submission.lowerBound,
submission.upperBound,
submission.provedPreviousReputationUID
);
}
function rewardStakersWithReputation(address[] stakers, address commonColonyAddress, uint256 reward, uint256 miningSkillId) public {
require(msg.sender == colonyNetworkAddress, "colony-reputation-mining-sender-not-network");
require(reputationUpdateLog.length == 0, "colony-reputation-mining-log-length-non-zero");
for (uint256 i = 0; i < stakers.length; i++) {
// We *know* we're the first entries in this reputation update log, so we don't need all the bookkeeping in
// the AppendReputationUpdateLog function
reputationUpdateLog.push(ReputationLogEntry(
stakers[i],
int256(reward),
miningSkillId, //This should be the special 'mining' skill.
commonColonyAddress, // They earn this reputation in the common colony.
4, // Updates the user's skill, and the colony's skill, both globally and for the special 'mining' skill
i*4 //We're zero indexed, so this is the number of updates that came before in the reputation log.
));
}
}
/// @notice Get the timestamp that the current reputation mining window opened
function getReputationMiningWindowOpenTimestamp() public returns (uint256) {
return reputationMiningWindowOpenTimestamp;
}
/////////////////////////
// Internal functions
/////////////////////////
function submissionWindowClosed() internal view returns(bool) {
return now - reputationMiningWindowOpenTimestamp >= MINING_WINDOW_SIZE;
}
function processBinaryChallengeSearchResponse(uint256 round, uint256 idx, bytes jhIntermediateValue, uint256 targetNode) internal {
disputeRounds[round][idx].lastResponseTimestamp = now;
disputeRounds[round][idx].challengeStepCompleted += 1;
// Save our intermediate hash
bytes32 intermediateReputationHash;
uint256 intermediateReputationNNodes;
assembly {
intermediateReputationHash := mload(add(jhIntermediateValue, 0x20))
intermediateReputationNNodes := mload(add(jhIntermediateValue, 0x40))
}
disputeRounds[round][idx].intermediateReputationHash = intermediateReputationHash;
disputeRounds[round][idx].intermediateReputationNNodes = intermediateReputationNNodes;
uint256 opponentIdx = (idx % 2 == 1 ? idx-1 : idx + 1);
if (disputeRounds[round][opponentIdx].challengeStepCompleted == disputeRounds[round][idx].challengeStepCompleted ) {
// Our opponent answered this challenge already.
// Compare our intermediateReputationHash to theirs to establish how to move the bounds.
processBinaryChallengeSearchStep(round, idx, targetNode);
}
}
function processBinaryChallengeSearchStep(uint256 round, uint256 idx, uint256 targetNode) internal {
uint256 opponentIdx = (idx % 2 == 1 ? idx-1 : idx + 1);
if (
disputeRounds[round][opponentIdx].intermediateReputationHash == disputeRounds[round][idx].intermediateReputationHash &&
disputeRounds[round][opponentIdx].intermediateReputationNNodes == disputeRounds[round][idx].intermediateReputationNNodes
)
{
disputeRounds[round][idx].lowerBound = targetNode + 1;
disputeRounds[round][opponentIdx].lowerBound = targetNode + 1;
} else {
// NB no '-1' to mirror the '+1' above in the other bound, because
// we're looking for the first index where these two submissions differ
// in their calculations - they disagreed for this index, so this might
// be the first index they disagree about
disputeRounds[round][idx].upperBound = targetNode;
disputeRounds[round][opponentIdx].upperBound = targetNode;
}
// We need to keep the intermediate hashes so that we can figure out what type of dispute we are resolving later
// If the number of nodes in the reputation state are different, then we are disagreeing on whether this log entry
// corresponds to an existing reputation entry or not.
// If the hashes are different, then it's a calculation error.
// However, the intermediate hashes saved might not be the ones that correspond to the first disagreement, based on how exactly the last
// step of the binary challenge came to be.
// If complete, mark that the binary search is completed (but the intermediate hashes may or may not be correct) by setting
// challengeStepCompleted to the maximum it could be for the number of nodes we had to search through, plus one to indicate
// they've submitted their jrh
if (disputeRounds[round][idx].lowerBound == disputeRounds[round][idx].upperBound) {
if (2**(disputeRounds[round][idx].challengeStepCompleted-1) < disputeRounds[round][idx].jrhNnodes) {
disputeRounds[round][idx].challengeStepCompleted += 1;
disputeRounds[round][opponentIdx].challengeStepCompleted += 1;
}
}
// Our opponent responded to this step of the challenge before we did, so we should
// reset their 'last response' time to now, as they aren't able to respond
// to the next challenge before they know what it is!
disputeRounds[round][opponentIdx].lastResponseTimestamp = now;
}
function checkJRHProof1(bytes32 jrh, uint256 branchMask1, bytes32[] siblings1, uint256 reputationRootHashNNodes) internal view {
// Proof 1 needs to prove that they started with the current reputation root hash
bytes32 reputationRootHash = IColonyNetwork(colonyNetworkAddress).getReputationRootHash();
bytes memory jhLeafValue = new bytes(64);
bytes memory zero = new bytes(32);
assembly {
mstore(add(jhLeafValue, 0x20), reputationRootHash)
mstore(add(jhLeafValue, 0x40), reputationRootHashNNodes)
}
bytes32 impliedRoot = getImpliedRoot(zero, jhLeafValue, branchMask1, siblings1);
require(jrh==impliedRoot, "colony-reputation-mining-invalid-jrh-proof-1");
}
function checkJRHProof2(
uint256 round,
uint256 index,
bytes32 jrh,
uint256 branchMask2,
bytes32[] siblings2,
uint256 reputationRootHashNNodes
) internal
{
// Proof 2 needs to prove that they finished with the reputation root hash they submitted, and the
// key is the number of updates implied by the contents of the reputation update log (implemented)
// plus the number of nodes in the last accepted update, each of which will have decayed once (not implemented)
uint256 nLogEntries = reputationUpdateLog.length;
// The total number of updates we expect is the nPreviousUpdates in the last entry of the log plus the number
// of updates that log entry implies by itself, plus the number of decays (the number of nodes in current state)
uint256 nUpdates = reputationUpdateLog[nLogEntries-1].nUpdates +
reputationUpdateLog[nLogEntries-1].nPreviousUpdates + reputationRootHashNNodes;
bytes memory nUpdatesBytes = new bytes(32);
disputeRounds[round][index].jrhNnodes = nUpdates + 1;
bytes32 submittedHash = disputeRounds[round][index].proposedNewRootHash;
uint256 submittedHashNNodes = disputeRounds[round][index].nNodes;
bytes memory jhLeafValue = new bytes(64);
assembly {
mstore(add(jhLeafValue, 0x20), submittedHash)
mstore(add(jhLeafValue, 0x40), submittedHashNNodes)
mstore(add(nUpdatesBytes, 0x20), nUpdates)
}
bytes32 impliedRoot = getImpliedRoot(nUpdatesBytes, jhLeafValue, branchMask2, siblings2);
require(jrh==impliedRoot, "colony-reputation-mining-invalid-jrh-proof-2");
}
function startMemberOfPair(uint256 roundNumber, uint256 index) internal {
disputeRounds[roundNumber][index].lastResponseTimestamp = now;
disputeRounds[roundNumber][index].upperBound = disputeRounds[roundNumber][index].jrhNnodes - 1;
disputeRounds[roundNumber][index].lowerBound = 0;
disputeRounds[roundNumber][index].provedPreviousReputationUID = 0;
if (disputeRounds[roundNumber][index].jrh != 0x0) {
// If this submission has a JRH, we give ourselves credit for it in the next round - it's possible
// that a submission got a bye without submitting a JRH, which will not have this starting '1'.
disputeRounds[roundNumber][index].challengeStepCompleted = 1;
} else {
disputeRounds[roundNumber][index].challengeStepCompleted = 0;
}
}
function startPairingInRound(uint256 roundNumber) internal {
uint256 nInRound = disputeRounds[roundNumber].length;
startMemberOfPair(roundNumber, nInRound-1);
startMemberOfPair(roundNumber, nInRound-2);
}
}
| @notice Get the address that made a particular submission @param hash The hash that was submitted @param nNodes The number of nodes that was submitted @param index The index of the submission - should be 0-11, as up to twelve submissions can be made. | function getSubmittedHashes(bytes32 hash, uint256 nNodes, uint256 index) public view returns (address) {
return submittedHashes[hash][nNodes][index];
}
| 2,522,701 | [
1,
967,
326,
1758,
716,
7165,
279,
6826,
8515,
225,
1651,
1021,
1651,
716,
1703,
9638,
225,
290,
3205,
1021,
1300,
434,
2199,
716,
1703,
9638,
225,
770,
1021,
770,
434,
326,
8515,
300,
1410,
506,
374,
17,
2499,
16,
487,
731,
358,
2339,
292,
537,
22071,
848,
506,
7165,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
7040,
7948,
14455,
12,
3890,
1578,
1651,
16,
2254,
5034,
290,
3205,
16,
2254,
5034,
770,
13,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
565,
327,
9638,
14455,
63,
2816,
6362,
82,
3205,
6362,
1615,
15533,
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
] |
/*
This Token Contract implements the Peculium token (beta)
.*/
import "./MintableToken.sol";
import "./TeamAndBounty.sol";
pragma solidity ^0.4.8;
contract Peculium is MintableToken {
/* Public variables of the token */
string public name = "Peculium"; //token name
string public symbol = "PCL";
uint256 public decimals = 8;
uint256 public NB_TOKEN = 20000000000; // number of token to create
uint256 public constant MAX_SUPPLY_NBTOKEN = 20000000000*10**8; //NB_TOKEN*10** decimals;
uint256 public START_PRE_ICO_TIMESTAMP =1509494400; //start date of PRE_ICO
uint256 public START_ICO_TIMESTAMP=START_PRE_ICO_TIMESTAMP+ 10* 1 days ;
uint256 public END_ICO_TIMESTAMP =1514764800; //end date of ICO
uint256 public constant THREE_HOURS_TIMESTAMP=10800;// month in minutes (1month =43200min)
uint256 public constant WEEK_TIMESTAMP=604800;
uint256 public constant BONNUS_FIRST_THREE_HOURS_PRE_ICO = 35 ; // 35%
uint256 public constant BONNUS_FIRST_TEN_DAYS_PRE_ICO = 30 ; // 35%
uint256 public constant BONNUS_FIRST_TWO_WEEKS_ICO = 20 ;
uint256 public constant BONNUS_AFTER_TWO_WEEKS_ICO = 15 ;
uint256 public constant BONNUS_AFTER_FIVE_WEEKS_ICO = 10 ;
uint256 public constant BONNUS_AFTER_SEVEN_WEEKS_ICO = 5 ;
uint256 public constant INITIAL_PERCENT_ICO_TOKEN_TO_ASSIGN = 25 ;
using SafeMath for uint256;
uint256 tokenAviableAfterIco;
uint256 tokenAviableForIco;
uint256 public Airdropsamount;
//Boolean to allow or not the initial assignement of token (batch)
bool public batchAssignStopped = false;
uint256 amount = MAX_SUPPLY_NBTOKEN;
TeamAndBounty teamAndBounty;
//Constructor
function Peculium() {
owner = msg.sender;
teamAndBounty =new TeamAndBounty(amount);
tokenAviableForIco = amount * INITIAL_PERCENT_ICO_TOKEN_TO_ASSIGN/ 100;
Airdropsamount = 50000000*10**8;
tokenAviableAfterIco=amount-(tokenAviableForIco+teamAndBounty.teamShare()+teamAndBounty.bountyShare());
balances[owner] = tokenAviableForIco;
}
function buyTokenPreIco(address toAddress, uint256 _vamounts) payable onlyOwner {
require ( batchAssignStopped == false );
require (START_PRE_ICO_TIMESTAMP <=now);
require (now <= (START_PRE_ICO_TIMESTAMP + 10* 1 days));
if (START_PRE_ICO_TIMESTAMP <=now && now <= (START_PRE_ICO_TIMESTAMP + THREE_HOURS_TIMESTAMP)){
uint256 amountTo_Send = _vamounts*10**decimals *(1+BONNUS_FIRST_THREE_HOURS_PRE_ICO/100);
balances[toAddress] += amountTo_Send;
}
if (START_PRE_ICO_TIMESTAMP+ THREE_HOURS_TIMESTAMP <=now && now <= (START_PRE_ICO_TIMESTAMP + 10* 1 days)){
amountTo_Send = _vamounts*10**decimals *(1+BONNUS_FIRST_TEN_DAYS_PRE_ICO/100);
balances[toAddress] += amountTo_Send;
}
}
function buyTokenIco(address toAddress, uint256 _vamounts) payable onlyOwner {
require ( batchAssignStopped == false );
require (START_ICO_TIMESTAMP <=now);
//require (now <= (START_ICO_TIMESTAMP + 7*WEEK_TIMESTAMP));
if ((START_ICO_TIMESTAMP) < now && now <= (START_ICO_TIMESTAMP + 2*WEEK_TIMESTAMP) ){
uint256 amountTo_Send = _vamounts* 10**decimals *(1+BONNUS_FIRST_TWO_WEEKS_ICO/100);
balances[toAddress] += amountTo_Send;
}
if ((START_ICO_TIMESTAMP+ 2*WEEK_TIMESTAMP) < now && now <= (START_ICO_TIMESTAMP + 5*WEEK_TIMESTAMP) ){
amountTo_Send = _vamounts*10**decimals *(1+BONNUS_AFTER_TWO_WEEKS_ICO/100);
balances[toAddress] += amountTo_Send;
}
if ((START_ICO_TIMESTAMP+ 5*WEEK_TIMESTAMP) < now && now <= (START_ICO_TIMESTAMP + 7*WEEK_TIMESTAMP) ){
amountTo_Send = _vamounts*10**decimals *(1+BONNUS_AFTER_FIVE_WEEKS_ICO/100);
balances[toAddress] += amountTo_Send;
}
if (START_ICO_TIMESTAMP+ 7*WEEK_TIMESTAMP< now){
amountTo_Send = _vamounts*10**decimals *(1+BONNUS_AFTER_SEVEN_WEEKS_ICO/100);
balances[toAddress] += amountTo_Send;
}
}
function buyTokenPostIco(address toAddress, uint256 _vamounts) payable onlyOwner {
require ( batchAssignStopped == false );
uint256 amountTo_Send = _vamounts*10**decimals;
balances[toAddress] += amountTo_Send;
}
function() payable
{
require ( batchAssignStopped == false );
require (START_PRE_ICO_TIMESTAMP <=now);
require (msg.value > 0.1 ether);
address toAddress = msg.sender;
uint256 _vamounts = msg.value;
if(now <= (START_PRE_ICO_TIMESTAMP + 10* 1 days))
{
buyTokenPreIco(toAddress,_vamounts);
}
if(START_ICO_TIMESTAMP <=now && now <= (START_ICO_TIMESTAMP + 7*WEEK_TIMESTAMP))
{
buyTokenIco(toAddress,_vamounts); // to change
}
else
{
buyTokenPostIco(toAddress,_vamounts);
}
}
function airdropsTokens(address[] _vaddr, uint256[] _vamounts) onlyOwner {
require ( batchAssignStopped == false );
require ( _vaddr.length == _vamounts.length );
//Looping into input arrays to assign target amount to each given address
if(now == END_ICO_TIMESTAMP){
for (uint index=0; index<_vaddr.length; index++) {
address toAddress = _vaddr[index];
uint amountTo_Send = _vamounts[index] * 10 ** decimals;
balances[toAddress] += amountTo_Send;
}
}
}
//teamAndBounty.teamPayment(address teamaddr);
//teamAndBounty.change_bounty_manager (address public_key);
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
function getBlockTimestamp() constant returns (uint256){
return now;
}
function stopBatchAssign() onlyOwner {
require ( batchAssignStopped == false);
batchAssignStopped = true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function getOwnerInfos() constant returns (address owneraddr, uint256 balance) {
owneraddr= owner;
balance = balances[owneraddr];
}
function killContract() onlyOwner { // fonction to destruct the contract.
selfdestruct(owner);
}
}
| Approves and then calls the receiving contract */ | function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
| 1,779,362 | [
1,
12053,
3324,
471,
1508,
4097,
326,
15847,
6835,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
6617,
537,
1876,
1477,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
16,
1731,
389,
7763,
751,
13,
1135,
261,
6430,
2216,
13,
288,
203,
202,
202,
8151,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
389,
1132,
31,
203,
202,
202,
23461,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
389,
1132,
1769,
203,
203,
202,
202,
6528,
24899,
87,
1302,
264,
18,
1991,
12,
3890,
24,
12,
3890,
1578,
12,
7819,
23,
2932,
18149,
23461,
12,
2867,
16,
11890,
5034,
16,
2867,
16,
3890,
2225,
3719,
3631,
1234,
18,
15330,
16,
389,
1132,
16,
333,
16,
389,
7763,
751,
10019,
203,
540,
202,
2463,
638,
31,
203,
565,
289,
203,
203,
202,
203,
27699,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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: contracts/interface/ICoFiXFactory.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
interface ICoFiXFactory {
// All pairs: {ETH <-> ERC20 Token}
event PairCreated(address indexed token, address pair, uint256);
event NewGovernance(address _new);
event NewController(address _new);
event NewFeeReceiver(address _new);
event NewFeeVaultForLP(address token, address feeVault);
event NewVaultForLP(address _new);
event NewVaultForTrader(address _new);
event NewVaultForCNode(address _new);
/// @dev Create a new token pair for trading
/// @param token the address of token to trade
/// @return pair the address of new token pair
function createPair(
address token
)
external
returns (address pair);
function getPair(address token) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function getTradeMiningStatus(address token) external view returns (bool status);
function setTradeMiningStatus(address token, bool status) external;
function getFeeVaultForLP(address token) external view returns (address feeVault); // for LPs
function setFeeVaultForLP(address token, address feeVault) external;
function setGovernance(address _new) external;
function setController(address _new) external;
function setFeeReceiver(address _new) external;
function setVaultForLP(address _new) external;
function setVaultForTrader(address _new) external;
function setVaultForCNode(address _new) external;
function getController() external view returns (address controller);
function getFeeReceiver() external view returns (address feeReceiver); // For CoFi Holders
function getVaultForLP() external view returns (address vaultForLP);
function getVaultForTrader() external view returns (address vaultForTrader);
function getVaultForCNode() external view returns (address vaultForCNode);
}
// File: contracts/interface/ICoFiXERC20.sol
pragma solidity 0.6.12;
interface ICoFiXERC20 {
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;
}
// File: contracts/interface/ICoFiXPair.sol
pragma solidity 0.6.12;
interface ICoFiXPair is ICoFiXERC20 {
struct OraclePrice {
uint256 ethAmount;
uint256 erc20Amount;
uint256 blockNum;
uint256 K;
uint256 theta;
}
// All pairs: {ETH <-> ERC20 Token}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, address outToken, uint outAmount, address indexed to);
event Swap(
address indexed sender,
uint amountIn,
uint amountOut,
address outToken,
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);
function mint(address to) external payable returns (uint liquidity, uint oracleFeeChange);
function burn(address outToken, address to) external payable returns (uint amountOut, uint oracleFeeChange);
function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function skim(address to) external;
function sync() external;
function initialize(address, address, string memory, string memory) external;
/// @dev get Net Asset Value Per Share
/// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token}
/// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token}
/// @return navps The Net Asset Value Per Share (liquidity) represents
function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps);
}
// File: contracts/interface/INestPriceFacade.sol
pragma solidity ^0.6.12;
/// @dev This interface defines the methods for price call entry
interface INestPriceFacade {
// /// @dev Price call entry configuration structure
// struct Config {
// // Single query fee(0.0001 ether, DIMI_ETHER). 100
// uint16 singleFee;
// // Double query fee(0.0001 ether, DIMI_ETHER). 100
// uint16 doubleFee;
// // The normal state flag of the call address. 0
// uint8 normalFlag;
// }
// /// @dev Modify configuration
// /// @param config Configuration object
// function setConfig(Config memory config) external;
// /// @dev Get configuration
// /// @return Configuration object
// function getConfig() external view returns (Config memory);
/// @dev Set the address flag. Only the address flag equals to config.normalFlag can the price be called
/// @param addr Destination address
/// @param flag Address flag
function setAddressFlag(address addr, uint flag) external;
/// @dev Get the flag. Only the address flag equals to config.normalFlag can the price be called
/// @param addr Destination address
/// @return Address flag
function getAddressFlag(address addr) external view returns(uint);
/// @dev Set INestQuery implemention contract address for token
/// @param tokenAddress Destination token address
/// @param nestQueryAddress INestQuery implemention contract address, 0 means delete
function setNestQuery(address tokenAddress, address nestQueryAddress) external;
/// @dev Get INestQuery implemention contract address for token
/// @param tokenAddress Destination token address
/// @return INestQuery implemention contract address, 0 means use default
function getNestQuery(address tokenAddress) external view returns (address);
/// @dev Get the latest trigger price
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function triggeredPrice(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price);
/// @dev Get the full information of latest trigger price
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ);
/// @dev Find the price at block number
/// @param tokenAddress Destination token address
/// @param height Destination block number
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function findPrice(address tokenAddress, uint height, address paybackAddress) external payable returns (uint blockNumber, uint price);
/// @dev Get the latest effective price
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function latestPrice(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price);
/// @dev Get the last (num) effective price
/// @param tokenAddress Destination token address
/// @param count The number of prices that want to return
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return An array which length is num * 2, each two element expresses one price like blockNumber|price
function lastPriceList(address tokenAddress, uint count, address paybackAddress) external payable returns (uint[] memory);
/// @dev Returns the results of latestPrice() and triggeredPriceInfo()
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return latestPriceBlockNumber The block number of latest price
/// @return latestPriceValue The token latest price. (1eth equivalent to (price) token)
/// @return triggeredPriceBlockNumber The block number of triggered price
/// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// @return triggeredAvgPrice Average price
/// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function latestPriceAndTriggeredPriceInfo(address tokenAddress, address paybackAddress)
external
payable
returns (
uint latestPriceBlockNumber,
uint latestPriceValue,
uint triggeredPriceBlockNumber,
uint triggeredPriceValue,
uint triggeredAvgPrice,
uint triggeredSigmaSQ
);
/// @dev Get the latest trigger price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
function triggeredPrice2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice);
/// @dev Get the full information of latest trigger price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
/// @return ntokenAvgPrice Average price of ntoken
/// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ);
/// @dev Get the latest effective price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
function latestPrice2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice);
}
// File: contracts/interface/ICoFiXController.sol
pragma solidity 0.6.12;
interface ICoFiXController {
event NewK(address token, int128 K, int128 sigma, uint256 T, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 tIdx, uint256 sigmaIdx, int128 K0);
event NewGovernance(address _new);
event NewOracle(address _priceOracle);
event NewKTable(address _kTable);
event NewTimespan(uint256 _timeSpan);
event NewKRefreshInterval(uint256 _interval);
event NewKLimit(int128 maxK0);
event NewGamma(int128 _gamma);
event NewTheta(address token, uint32 theta);
event NewK(address token, uint32 k);
function addCaller(address caller) external;
function queryOracle(address token, uint8 op, bytes memory data) external payable returns (uint256 k, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 theta);
}
// File: contracts/lib/TransferHelper.sol
pragma solidity 0.6.12;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: contracts/interface/ICoFiXKTable.sol
pragma solidity 0.6.12;
interface ICoFiXKTable {
function setK0(uint256 tIdx, uint256 sigmaIdx, int128 k0) external;
function setK0InBatch(uint256[] memory tIdxs, uint256[] memory sigmaIdxs, int128[] memory k0s) external;
function getK0(uint256 tIdx, uint256 sigmaIdx) external view returns (int128);
}
// File: contracts/lib/ABDKMath64x64.sol
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity 0.6.12;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/**
* @dev Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/**
* @dev Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << 127 - msb;
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= 63 - (x >> 64);
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu (uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; }
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 xe = msb - 127;
if (xe > 0) x >>= xe;
else x <<= -xe;
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (result >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require (re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (x >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require (xe < 128); // Overflow
}
}
if (re > 0) result <<= re;
else if (re < 0) result >>= -re;
return result;
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x, uint256 r) private pure returns (uint128) {
if (x == 0) return 0;
else {
require (r > 0);
while (true) {
uint256 rr = x / r;
if (r == rr || r + 1 == rr) return uint128 (r);
else if (r == rr + 1) return uint128 (rr);
r = r + rr + 1 >> 1;
}
}
}
}
// 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: contracts/CoFiXController04.sol
pragma solidity 0.6.12;
// Controller contract to call NEST Oracle for prices, managed by governance
// Governance role of this contract should be the `Timelock` contract, which is further managed by a multisig contract
contract CoFiXController04 is ICoFiXController { // ctrl-03: change contract name to avoid truffle complaint
using SafeMath for uint256;
enum CoFiX_OP { QUERY, MINT, BURN, SWAP_WITH_EXACT, SWAP_FOR_EXACT } // operations in CoFiX
uint256 constant public AONE = 1 ether;
uint256 constant public K_BASE = 1E8;
uint256 constant public NAVPS_BASE = 1E18; // NAVPS (Net Asset Value Per Share), need accuracy
uint256 internal T = 900; // ctrl-v2: V1 (900) -> V2 (600)
uint256 internal K_EXPECTED_VALUE = 0.005*1E8; // ctrl-v2: V1 (0.0025) -> V2 (0.005)
// impact cost params
uint256 constant internal C_BUYIN_ALPHA = 25700000000000; // α=2.570e-05*1e18
uint256 constant internal C_BUYIN_BETA = 854200000000; // β=8.542e-07*1e18
uint256 constant internal C_SELLOUT_ALPHA = 117100000000000; // α=-1.171e-04*1e18
uint256 constant internal C_SELLOUT_BETA = 838600000000; // β=8.386e-07*1e18
int128 constant internal SIGMA_STEP = 0x346DC5D638865; // (0.00005*2**64).toString(16), 0.00005 as 64.64-bit fixed point
int128 constant internal ZERO_POINT_FIVE = 0x8000000000000000; // (0.5*2**64).toString(16)
uint256 constant PRICE_DEVIATION = 10; // price deviation < 10%
mapping(address => uint32[3]) internal KInfoMap; // gas saving, index [0] is k vlaue, index [1] is updatedAt, index [2] is theta
mapping(address => bool) public callerAllowed;
// managed by governance
address public governance;
address public immutable oracle;
address public immutable nestToken;
address public immutable factory;
address public kTable;
uint256 public timespan = 14;
uint256 public kRefreshInterval = 5 minutes;
uint256 public DESTRUCTION_AMOUNT = 0 ether; // from nest oracle
int128 public MAX_K0 = 0xCCCCCCCCCCCCD00; // (0.05*2**64).toString(16)
int128 public GAMMA = 0x8000000000000000; // (0.5*2**64).toString(16)
struct OracleParams {
uint256 ethAmount;
uint256 erc20Amount;
uint256 blockNum;
uint256 K;
uint256 T; // time offset
uint256 avgPrice; // average price
uint256 theta;
uint256 sigma;
uint256 tIdx;
uint256 sigmaIdx;
}
modifier onlyGovernance() {
require(msg.sender == governance, "CoFiXCtrl: !governance");
_;
}
constructor(address _oracle, address _nest, address _factory, address _kTable) public {
governance = msg.sender;
oracle = _oracle;
nestToken = _nest;
factory = _factory;
kTable = _kTable;
// add previous pair as caller
ICoFiXFactory cFactory = ICoFiXFactory(_factory);
uint256 pairCnt = cFactory.allPairsLength();
for (uint256 i = 0; i < pairCnt; i++) {
address pair = cFactory.allPairs(i);
callerAllowed[pair] = true;
}
}
receive() external payable {}
/* setters for protocol governance */
function setGovernance(address _new) external onlyGovernance {
governance = _new;
emit NewGovernance(_new);
}
function setKTable(address _kTable) external onlyGovernance {
kTable = _kTable;
emit NewKTable(_kTable);
}
function setTimespan(uint256 _timeSpan) external onlyGovernance {
timespan = _timeSpan;
emit NewTimespan(_timeSpan);
}
function setKRefreshInterval(uint256 _interval) external onlyGovernance {
kRefreshInterval = _interval;
emit NewKRefreshInterval(_interval);
}
function setOracleDestructionAmount(uint256 _amount) external onlyGovernance {
DESTRUCTION_AMOUNT = _amount;
}
function setTLimit(uint256 _T) external onlyGovernance { // ctrl-v2: new setter for T
T = _T;
}
function setK(address token, uint32 k) external onlyGovernance { // ctrl-v2: new setter for K, adjustable by governance
K_EXPECTED_VALUE = uint256(k);
emit NewK(token, k); // new event for setting K
}
function setTheta(address token, uint32 theta) external onlyGovernance {
KInfoMap[token][2] = theta;
emit NewTheta(token, theta);
}
function addCaller(address caller) external override {
require(msg.sender == factory || msg.sender == governance, "CoFiXCtrl: only factory or gov");
callerAllowed[caller] = true;
}
// Calc variance of price and K in CoFiX is very expensive
// We use expected value of K based on statistical calculations here to save gas
// In the near future, NEST could provide the variance of price directly. We will adopt it then.
// We can make use of `data` bytes in the future
function queryOracle(address token, uint8 op, bytes memory data) external override payable returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum, uint256 _theta) {
require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed");
(_k, _ethAmount, _erc20Amount, _blockNum) = getLatestPrice(token);
CoFiX_OP cop = CoFiX_OP(op);
uint256 impactCost;
if (cop == CoFiX_OP.SWAP_WITH_EXACT) {
impactCost = calcImpactCostFor_SWAP_WITH_EXACT(token, data, _ethAmount, _erc20Amount);
} else if (cop == CoFiX_OP.SWAP_FOR_EXACT) {
revert("disabled experimental feature!"); // ctrl-v2: disable swapForExact function
} else if (cop == CoFiX_OP.BURN) {
impactCost = calcImpactCostFor_BURN(token, data, _ethAmount, _erc20Amount);
}
_k = _k.add(impactCost); // ctrl-v2: adjustable K + impactCost is the final K
_theta = KInfoMap[token][2];
return (_k, _ethAmount, _erc20Amount, _blockNum, _theta);
}
function calcImpactCostFor_BURN(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) {
// bytes memory data = abi.encode(msg.sender, outToken, to, liquidity);
(, address outToken, , uint256 liquidity) = abi.decode(data, (address, address, address, uint256));
// calc real vol by liquidity * np
uint256 navps = ICoFiXPair(msg.sender).getNAVPerShare(ethAmount, erc20Amount); // pair call controller, msg.sender is pair
uint256 vol = liquidity.mul(navps).div(NAVPS_BASE);
if (outToken != token) {
// buy in ETH, outToken is ETH
return impactCostForBuyInETH(vol);
}
// sell out liquidity, outToken is token, take this as sell out ETH and get token
return impactCostForSellOutETH(vol);
}
function calcImpactCostFor_SWAP_WITH_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) {
(, address outToken, , uint256 amountIn) = abi.decode(data, (address, address, address, uint256));
if (outToken != token) {
// buy in ETH, outToken is ETH, amountIn is token
// convert to amountIn in ETH
uint256 vol = uint256(amountIn).mul(ethAmount).div(erc20Amount);
return impactCostForBuyInETH(vol);
}
// sell out ETH, amountIn is ETH
return impactCostForSellOutETH(amountIn);
}
function calcImpactCostFor_SWAP_FOR_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) {
(, address outToken, uint256 amountOutExact,) = abi.decode(data, (address, address, uint256, address));
if (outToken != token) {
// buy in ETH, outToken is ETH, amountOutExact is ETH
return impactCostForBuyInETH(amountOutExact);
}
// sell out ETH, amountIn is ETH, amountOutExact is token
// convert to amountOutExact in ETH
uint256 vol = uint256(amountOutExact).mul(ethAmount).div(erc20Amount);
return impactCostForSellOutETH(vol);
}
// impact cost
// - C = 0, if VOL < 500
// - C = α + β * VOL, if VOL >= 500
// α=2.570e-05,β=8.542e-07
function impactCostForBuyInETH(uint256 vol) public pure returns (uint256 impactCost) {
if (vol < 500 ether) {
return 0;
}
// return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).mul(1e8).div(1e18);
return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).div(1e10); // combine mul div
}
// α=-1.171e-04,β=8.386e-07
function impactCostForSellOutETH(uint256 vol) public pure returns (uint256 impactCost) {
if (vol < 500 ether) {
return 0;
}
// return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).mul(1e8).div(1e18);
return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).div(1e10); // combine mul div
}
function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta) {
// ctrl-v3: load from storage instead of constant value
uint32 kStored = KInfoMap[token][0];
if (kStored != 0) {
k = kStored;
} else {
k = uint32(K_EXPECTED_VALUE);
}
updatedAt = KInfoMap[token][1];
theta = KInfoMap[token][2];
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function getLatestPrice(address token) internal returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum) {
uint256 _balanceBefore = address(this).balance;
OracleParams memory _op;
// query oracle
/// latestPriceBlockNumber The block number of latest price
/// latestPriceValue The token latest price. (1eth equivalent to (price) token)
/// triggeredPriceBlockNumber The block number of triggered price
/// triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// triggeredAvgPrice Average price
/// triggeredSigmaSQ The square of the volatility (18 decimal places).
(
_op.blockNum,
_op.erc20Amount,
/* uint triggeredPriceBlockNumber */,
/* uint triggeredPriceValue */,
_op.avgPrice,
_op.sigma
) = INestPriceFacade(oracle).latestPriceAndTriggeredPriceInfo{value: msg.value}(token, address(this));
_op.sigma = sqrt(_op.sigma.mul(1e18));
_op.ethAmount = 1 ether;
// validate T
_op.T = block.number.sub(_op.blockNum).mul(timespan);
require(_op.T < T, "CoFiXCtrl: oralce price outdated"); // ctrl-v2: adjustable T
{
// check if the price is steady
uint256 price;
bool isDeviated;
price = _op.erc20Amount.mul(1e18).div(_op.ethAmount);
uint256 diff = price > _op.avgPrice? (price - _op.avgPrice) : (_op.avgPrice - price);
isDeviated = (diff.mul(100) < _op.avgPrice.mul(PRICE_DEVIATION))? false : true;
require(isDeviated == false, "CoFiXCtrl: price deviation"); // validate
}
// calc K
// int128 K0; // K0AndK[0]
// int128 K; // K0AndK[1]
int128[2] memory K0AndK;
{
_op.tIdx = (_op.T.add(5)).div(10); // rounding to the nearest
_op.sigmaIdx = ABDKMath64x64.toUInt(
ABDKMath64x64.add(
ABDKMath64x64.div(int128(_op.sigma), SIGMA_STEP), // _sigma / 0.00005, e.g. (0.00098/0.00005)=9.799 => 9
ZERO_POINT_FIVE // e.g. (0.00098/0.00005)+0.5=20.0999 => 20
)
);
if (_op.sigmaIdx > 0) {
_op.sigmaIdx = _op.sigmaIdx.sub(1);
}
// getK0(uint256 tIdx, uint256 sigmaIdx)
// K0 is K0AndK[0]
K0AndK[0] = ICoFiXKTable(kTable).getK0(
_op.tIdx,
_op.sigmaIdx
);
// K = gamma * K0
K0AndK[1] = ABDKMath64x64.mul(GAMMA, K0AndK[0]);
emit NewK(token, K0AndK[1], int128(_op.sigma), _op.T, _op.ethAmount, _op.erc20Amount, _op.blockNum, _op.tIdx, _op.sigmaIdx, K0AndK[0]);
}
require(K0AndK[0] <= MAX_K0, "CoFiXCtrl: K0");
{
// return oracle fee change
// we could decode data in the future to pay the fee change and mining award token directly to reduce call cost
// TransferHelper.safeTransferETH(payback, msg.value.sub(_balanceBefore.sub(address(this).balance)));
uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance));
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
_k = ABDKMath64x64.toUInt(ABDKMath64x64.mul(K0AndK[1], ABDKMath64x64.fromUInt(K_BASE)));
KInfoMap[token][0] = uint32(_k); // k < MAX_K << uint32(-1)
KInfoMap[token][1] = uint32(block.timestamp); // 2106
return (_k, _op.ethAmount, _op.erc20Amount, _op.blockNum);
}
}
/**
* @notice Calc K value
* @param vola The square of the volatility (18 decimal places).
* @param bn The block number when (ETH, TOKEN) price takes into effective
* @return k The K value
*/
function calcK(uint256 vola, uint256 bn) external view returns (uint32 k) {
// int128 K0; // K0AndK[0]
// int128 K; // K0AndK[1]
vola = sqrt(vola.mul(1e18));
int128[2] memory K0AndK;
uint256 _T = block.number.sub(bn).mul(timespan);
uint256 tIdx = (_T.add(5)).div(10); // rounding to the nearest
uint256 sigmaIdx = ABDKMath64x64.toUInt(
ABDKMath64x64.add(
ABDKMath64x64.div(int128(vola), SIGMA_STEP), // _sigma / 0.00005, e.g. (0.00098/0.00005)=9.799 => 9
ZERO_POINT_FIVE // e.g. (0.00098/0.00005)+0.5=20.0999 => 20
)
);
if (sigmaIdx > 0) {
sigmaIdx = sigmaIdx.sub(1);
}
// getK0(uint256 tIdx, uint256 sigmaIdx)
// K0 is K0AndK[0]
K0AndK[0] = ICoFiXKTable(kTable).getK0(
tIdx,
sigmaIdx
);
// K = gamma * K0
K0AndK[1] = ABDKMath64x64.mul(GAMMA, K0AndK[0]);
k = uint32(ABDKMath64x64.toUInt(ABDKMath64x64.mul(K0AndK[1], ABDKMath64x64.fromUInt(K_BASE))));
}
// ctrl-v2: remove unused code bellow according to PeckShield's advice
} | buy in ETH, outToken is ETH | if (outToken != token) {
return impactCostForBuyInETH(vol);
}
| 623,044 | [
1,
70,
9835,
316,
512,
2455,
16,
596,
1345,
353,
512,
2455,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
261,
659,
1345,
480,
1147,
13,
288,
203,
5411,
327,
15800,
8018,
1290,
38,
9835,
382,
1584,
44,
12,
15416,
1769,
203,
3639,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 <0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract MerchToken is ERC721, Ownable {
/*** EVENTS ***/
/// The event emitted (useable by web3) when a token is purchased
event MerchToken(address indexed buyer, uint256 tokenId);
/*** CONSTANTS ***/
uint8 constant NAME_MIN_LENGTH = 1;
uint8 constant NAME_MAX_LENGTH = 64;
string constant public merchTypes = "SHIRT,SOCKS,BACKPACK,PANTS,BRICK";
string constant public tags = "COOL,SICK,SEXY,CRINGE,CLOUTED,INSANE,COZY,SAD,LEGIT,GOBEARS";
/*** DATA S ***/
struct MerchInfo {
uint256 price;
string name;
string picture;
string description;
uint256 merchType;
uint256 tag;
bool forSale;
}
//This mapping is from the tokens that exist in the contract to
//a relevant MerchInfo struct containing the token's properties
mapping(uint256 => MerchInfo) tokenInfos;
// The next token id to be issued. Every time a token is minted, index
// increases by 1.
uint256 index;
constructor() public ERC721("Merch Token", "OSKI") {
// any init code when you deploy the contract would run here
//initialize contract with no tokens
index = 0;
}
/* Requires the amount of Ether be at least or more of the currentPrice
* @dev Creates an instance of an token and mints it to the purchaser.
*
* the default ERC721 Requires gas to mint, but we modified
* it to mint for free and have a price set by the user*/
function mintToken(
uint256 _price,
string calldata _name,
string calldata _picture,
string calldata _description,
bool _forSale
) external payable {
bytes memory _nameBytes = bytes(_name);
require(_price > 0, "Price must be greater than 0");
require(bytes(_picture).length != 0, "you need a picture");
require(
bytes(_description).length != 0,
"Description should not be null"
);
require(_nameBytes.length >= NAME_MIN_LENGTH, "Title is too short");
require(_nameBytes.length <= NAME_MAX_LENGTH, "Title is too long");
// ***********TO DO:************* Generate psedorandom numbers
// by running blocktimestamp+address -> blackbox hashing function -> determine from last digit of result
bytes32 hash1 = sha256(block.timestamp + msg.sender);
bytes32 hash2 = keccak256(hash1);
uint256 result = uint256(hash2);
uint256 _merchType = result%10;
uint256 _tag = result%5;
require(_tag <= 4, "Failed random check, ID too large");
require(_merchType <= 9, "Failed random check, tagID too large");
_mint(msg.sender, index);
tokenInfos[index] = MerchInfo({
price: _price,
name: _name,
picture: _picture,
description: _description,
merchType: _merchType,
tag: _tag,
forSale: _forSale
});
//*****TO:DO****** once a token is minted, tell the contract by changing one variable
index = index + 1;
emit MerchToken(msg.sender, index);
}
function buyToken(uint256 _id) external payable {
require(tokenInfos[_id].price > 0); // ensure token exists
require(msg.value >= tokenInfos[_id].price); // ensure enough money paid for token
require(tokenInfos[_id].forSale == true); // ensure for sale
//pay with eth
bool sent = payable(ownerOf(_id)).send(msg.value);
require(sent, "Failed to send Ether");
//transfer the NFT
_transfer(ownerOf(_id), msg.sender, _id);
tokenInfos[_id].forSale = false;
}
// Returns the number of tokens issued so far
function getTokens() public returns (uint256) {
return index;
}
/* @notice Returns all the relevant information about a specific token
* @param _tokenId The ID of the token of interest */
function getToken(uint256 _tokenId)
external
view
returns (
string memory _name,
string memory _picture,
string memory _description,
uint256[3] memory _ints, //price, tag, and type are stored as ints in this array
bool _forSale
)
{
require(_tokenId < index); // ensure token exists
_name = tokenInfos[_tokenId].name;
_picture = tokenInfos[_tokenId].picture;
_description = tokenInfos[_tokenId].description;
_ints[0] = (tokenInfos[_tokenId].price);
_ints[1] = (tokenInfos[_tokenId].merchType);
_ints[2] = (tokenInfos[_tokenId].tag);
_forSale = tokenInfos[_tokenId].forSale;
}
//******TO DO************
// Changes the price that must be paid to buy a particular token
function changePrice(uint256 _tokenId, uint256 _newPrice) public {
require(_newPrice != 0);
require(tokenInfos[_tokenId].price > 0);
require(ownerOf(_tokenId) == msg.sender);
tokenInfos[_tokenId].price = _newPrice;
}
// Allow a token to be sold
function listToken(uint256 _tokenId) public {
require(ownerOf(_tokenId) == msg.sender);
require(!tokenInfos[_tokenId].forSale);
tokenInfos[_tokenId].forSale = true;
}
// Disallow a token to be sold
function unListToken(uint256 _tokenId) public {
require(ownerOf(_tokenId) == msg.sender);
require(tokenInfos[_tokenId].forSale);
tokenInfos[_tokenId].forSale = false;
}
}
| *****TO:DO****** once a token is minted, tell the contract by changing one variable | index = index + 1;
| 12,790,421 | [
1,
4296,
30,
3191,
3647,
279,
1147,
353,
312,
474,
329,
16,
9276,
326,
6835,
635,
12770,
1245,
2190,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
770,
273,
770,
397,
404,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
// File: contracts/external/Controlled.sol
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
// File: contracts/external/TokenController.sol
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
// File: contracts/external/MiniMeToken.sol
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.2'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
uint previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
// File: contracts/DTXToken.sol
contract DTXToken is MiniMeToken {
function DTXToken(address _tokenFactory) public MiniMeToken (
_tokenFactory,
0x0, // no parent token
0, // no snapshot block number from parent
"DaTa eXchange Token", // Token name
18, // Decimals
"DTX", // Symbol
true // Enable transfers
)
{}
}
// File: contracts/external/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/external/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) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/BountyVault.sol
contract BountyVault is Ownable {
using SafeMath for uint256;
// the tokencontract for the DataBrokerDAO
DTXToken public tokenContract;
uint256 public allocatedTotal;
// the list of addresses and how much they have earned.
mapping(address => uint256) public balances;
/// @dev the constructor
constructor(
address _tokenAddress
) public {
tokenContract = DTXToken(_tokenAddress);
}
/// @dev Withdraws the tokens
function withdrawTokens() public {
uint256 amount = balances[msg.sender];
require(amount > 0, "You have no tokens left");
balances[msg.sender] = 0;
require(tokenContract.transfer(msg.sender, amount), "Token transfer failed");
}
/// @dev utility function to allow the owner to allocate tokens
function allocateTokens(address[] _recipients, uint256[] _amounts) public onlyOwner {
for (uint256 i = 0; i < _recipients.length; i++) {
balances[_recipients[i]] = balances[_recipients[i]].add(_amounts[i]);
allocatedTotal = allocatedTotal.add(_amounts[i]);
}
}
} | @dev The actual token contract, the default controller is the msg.sender that deploys the contract, so usually this token will be deployed by a token controller contract, which Giveth will call a "Campaign" | contract MiniMeToken is Controlled {
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
MiniMeToken public parentToken;
uint public parentSnapShotBlock;
uint public creationBlock;
mapping (address => Checkpoint[]) balances;
mapping (address => mapping (address => uint256)) allowed;
Checkpoint[] totalSupplyHistory;
bool public transfersEnabled;
MiniMeTokenFactory public tokenFactory;
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
if (msg.sender != controller) {
require(transfersEnabled);
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
if (msg.sender != controller) {
require(transfersEnabled);
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
if (previousBalanceFrom < _amount) {
return false;
}
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
return true;
}
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
if (previousBalanceFrom < _amount) {
return false;
}
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
return true;
}
require((_to != 0) && (_to != address(this)));
uint previousBalanceFrom = balanceOfAt(_from, block.number);
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
if (previousBalanceFrom < _amount) {
return false;
}
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
return true;
}
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
if (previousBalanceFrom < _amount) {
return false;
}
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
return true;
}
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
uint previousBalanceTo = balanceOfAt(_to, block.number);
Transfer(_from, _to, _amount);
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
return 0;
}
return getValueAt(balances[_owner], _blockNumber);
}
}
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
return 0;
}
return getValueAt(balances[_owner], _blockNumber);
}
}
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
return 0;
}
return getValueAt(balances[_owner], _blockNumber);
}
}
} else {
} else {
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
return 0;
}
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
return 0;
}
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
return 0;
}
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
} else {
} else {
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
uint previousBalanceTo = balanceOf(_owner);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
max = mid-1;
}
}
return checkpoints[min].value;
}
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
max = mid-1;
}
}
return checkpoints[min].value;
}
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
max = mid-1;
}
}
return checkpoints[min].value;
}
} else {
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
} else {
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
function () public payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
}
| 13,569,164 | [
1,
1986,
3214,
1147,
6835,
16,
326,
805,
2596,
353,
326,
1234,
18,
15330,
225,
716,
5993,
383,
1900,
326,
6835,
16,
1427,
11234,
333,
1147,
903,
506,
19357,
635,
279,
225,
1147,
2596,
6835,
16,
1492,
611,
427,
546,
903,
745,
279,
315,
13432,
6,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
27987,
4667,
1345,
353,
8888,
1259,
288,
203,
203,
203,
203,
565,
1958,
225,
25569,
288,
203,
203,
3639,
2254,
10392,
628,
1768,
31,
203,
203,
3639,
2254,
10392,
460,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
27987,
4667,
1345,
1071,
982,
1345,
31,
203,
565,
2254,
1071,
982,
24063,
1555,
352,
1768,
31,
203,
565,
2254,
1071,
6710,
1768,
31,
203,
565,
2874,
261,
2867,
516,
25569,
63,
5717,
324,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
2935,
31,
203,
565,
25569,
8526,
2078,
3088,
1283,
5623,
31,
203,
565,
1426,
1071,
29375,
1526,
31,
203,
565,
27987,
4667,
1345,
1733,
1071,
1147,
1733,
31,
203,
203,
565,
445,
27987,
4667,
1345,
12,
203,
3639,
1758,
389,
2316,
1733,
16,
203,
3639,
1758,
389,
2938,
1345,
16,
203,
3639,
2254,
389,
2938,
24063,
1555,
352,
1768,
16,
203,
3639,
533,
389,
2316,
461,
16,
203,
3639,
2254,
28,
389,
12586,
7537,
16,
203,
3639,
533,
389,
2316,
5335,
16,
203,
3639,
1426,
389,
2338,
18881,
1526,
203,
565,
262,
1071,
288,
203,
3639,
1147,
1733,
273,
27987,
4667,
1345,
1733,
24899,
2316,
1733,
1769,
203,
3639,
982,
1345,
273,
27987,
4667,
1345,
24899,
2938,
1345,
1769,
203,
3639,
982,
24063,
1555,
352,
1768,
273,
389,
2938,
24063,
1555,
352,
1768,
31,
203,
3639,
29375,
1526,
273,
389,
2338,
18881,
1526,
31,
203,
3639,
6710,
1768,
273,
1203,
18,
2696,
31,
203,
565,
289,
203,
203,
203,
2
] |
./full_match/1/0xDF8704582C08f9A208fF86F42876dCF4308d5435/sources/browser/staking.sol | vote to return to lp if user already voted remove users old vote from token if return lp vote is hegher than previous return vote return liquidity here add profits to all time profits take tax if profit | function returnLP() external {
require(voteOpen == 1, "Vote is still open");
require(usr[msg.sender].votedReturn == 0, "Already voted on return");
require(usr[msg.sender].stake >= minFund || usr[msg.sender].invested == 1, "Your balance is too low");
if(usr[msg.sender].voted != address(0)) {
usr[msg.sender].voted = address(0);
tAddr[usr[msg.sender].voted]-=1;
totVote-=1;
}
uint256 checkVotes = returnLPVote+1;
usr[msg.sender].votedReturn = 1;
if(checkVotes > returnVote/2) {
uint256 allOrcaLP = IERC20(fundTkn).balanceOf(address(this));
uint256 oldTknBal = IERC20(oldToken).balanceOf(address(this));
IERC20(oldToken).approve(uniAddr, oldTknBal);
address[] memory path;
path = new address[](2);
if(oldToken != WETH) {
path[0] = oldToken;
path[1] = WETH;
uni.swapExactTokensForTokens(oldTknBal, 0, path, address(this), now+600);
}
uint256 newWETHBal = IERC20(WETH).balanceOf(address(this));
uint256 wethProfit;
if(newWETHBal > wETHInvested) {
wethProfit = newWETHBal-wETHInvested;
wETHProfits = wETHProfits+wethProfit;
if(wethProfit >= 100000000000000000) {
uint256 feeAmount = wethProfit*feePercent/100;
fundTkn.transfer(taxFeeAddress, feeAmount);
wethProfit = wethProfit-feeAmount;
path[0] = WETH;
path[1] = nativeOrkaAddress;
uni.swapExactTokensForTokens(wethProfit/2, 0, path, address(this), now+600);
}
}
uni.addLiquidity(nativeOrkaAddress, WETH, IERC20(nativeOrkaAddress).balanceOf(address(this)), IERC20(WETH).balanceOf(address(this)), 0, 0, address(this), now+600);
if(newETH >= 100000000000000000) {
path = new address[](2);
path[0] = WETH;
path[1] = nativeOrkaAddress;
uni.swapExactTokensForTokens(newETH/2, 0, path, address(this), now+600);
uni.addLiquidity(nativeOrkaAddress, WETH, IERC20(nativeOrkaAddress).balanceOf(address(this)), IERC20(WETH).balanceOf(address(this)), 0, 0, address(this), now+600);
}
uint256 realOrca = IERC20(fundTkn).balanceOf(address(this))-allOrcaLP;
uint256 i;
for(i = 0; i < usrs.length; i++){
if(usr[usrs[i]].invested == 1) {
usr[usrs[i]].stake = usr[usrs[i]].stakePer/10**18*realOrca/100+usr[usrs[i]].stake;
usr[usrs[i]].stakePer = 0;
usr[usrs[i]].invested = 0;
}
}
returnVote = 0;
wETHInvested = 0;
resetData(0);
}
}
| 3,101,272 | [
1,
25911,
358,
327,
358,
12423,
309,
729,
1818,
331,
16474,
1206,
3677,
1592,
12501,
628,
1147,
309,
327,
12423,
12501,
353,
366,
1332,
1614,
2353,
2416,
327,
12501,
327,
4501,
372,
24237,
2674,
527,
9214,
1282,
358,
777,
813,
9214,
1282,
4862,
5320,
309,
450,
7216,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
915,
327,
14461,
1435,
3903,
288,
203,
6528,
12,
25911,
3678,
422,
404,
16,
315,
19338,
353,
4859,
1696,
8863,
203,
6528,
12,
13640,
63,
3576,
18,
15330,
8009,
90,
16474,
990,
422,
374,
16,
315,
9430,
331,
16474,
603,
327,
8863,
203,
6528,
12,
13640,
63,
3576,
18,
15330,
8009,
334,
911,
1545,
1131,
42,
1074,
747,
16575,
63,
3576,
18,
15330,
8009,
5768,
3149,
422,
404,
16,
315,
15446,
11013,
353,
4885,
4587,
8863,
203,
203,
430,
12,
13640,
63,
3576,
18,
15330,
8009,
90,
16474,
480,
1758,
12,
20,
3719,
288,
203,
13640,
63,
3576,
18,
15330,
8009,
90,
16474,
273,
1758,
12,
20,
1769,
203,
88,
3178,
63,
13640,
63,
3576,
18,
15330,
8009,
90,
16474,
65,
17,
33,
21,
31,
203,
3307,
19338,
17,
33,
21,
31,
203,
97,
203,
203,
11890,
5034,
866,
29637,
273,
327,
14461,
19338,
15,
21,
31,
203,
13640,
63,
3576,
18,
15330,
8009,
90,
16474,
990,
273,
404,
31,
203,
203,
430,
12,
1893,
29637,
405,
327,
19338,
19,
22,
13,
288,
203,
203,
11890,
5034,
777,
1162,
5353,
14461,
273,
467,
654,
39,
3462,
12,
74,
1074,
56,
21112,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
11890,
5034,
1592,
56,
21112,
38,
287,
273,
467,
654,
39,
3462,
12,
1673,
1345,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
45,
654,
39,
3462,
12,
1673,
1345,
2934,
12908,
537,
12,
318,
77,
3178,
16,
1592,
56,
21112,
38,
287,
1769,
203,
2867,
8526,
3778,
589,
31,
203,
803,
2
] |
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
// load other contracts
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Random.sol";
// for debugging
import "hardhat/console.sol";
contract Lottery is Ownable {
using Math for uint256;
// Events
event NewLottery(address creator, uint256 startTime, uint256 endTime); // emit when lottery created
event TicketsMinted(address player, uint256 numTicketsMinted); // emit when user purchases tix
// emit when lottery drawing happens; winner found
event WinnerFound(
uint256 lotteryId,
uint256 winningTicketIndex,
address winningAddress
);
// emit when lottery winnings deposited in pending withdrawals
event LotteryWinningsDeposited(
uint256 lotteryId,
address winningAddress,
uint256 amountDeposited
);
// emit when funds withdrawn by winner
event WinnerFundsWithdrawn(address winnerAddress, uint256 withdrawalAmount);
// emit when owner has changed max player param
event MaxPlayersAllowedUpdated(uint256 maxPlayersAllowed);
// State Variables
struct LotteryStruct {
uint256 lotteryId;
uint256 startTime;
uint256 endTime;
bool isActive; // minting tickets is allowed. TASK: rename to "isMintingPeriodActive"?
bool isCompleted; // winner was found; winnings were deposited.
bool isCreated; // is created
}
struct TicketDistributionStruct {
address playerAddress;
uint256 startIndex; // inclusive
uint256 endIndex; // inclusive
}
struct WinningTicketStruct {
uint256 currentLotteryId;
uint256 winningTicketIndex;
address addr; // TASK: rename to "winningAddress"?
}
/* TASK: rename to TICKET_PRICE? More human readable, makes more sense. Although it technically is the minimum increment.
*/
uint256 public constant MIN_DRAWING_INCREMENT = 100000000000000; // 0.0001 ETH; min eth amount to enter lottery.
uint256 public constant NUMBER_OF_HOURS = 168; // 1 week by default; configurable
uint256 public maxPlayersAllowed = 1000;
// max # loops allowed for binary search; to prevent some bugs causing infinite loops in binary search
uint256 public maxLoops = 10;
uint256 private loopCount = 0; // for binary search
uint256 public currentLotteryId = 0;
uint256 public numLotteries = 0;
uint256 public prizeAmount; // winnings. Probably duplicate and can be removed. Just use numTotalTickets/ (MIN_DRAWING_INCREMENT) to calculate prize amount
WinningTicketStruct public winningTicket;
TicketDistributionStruct[] public ticketDistribution;
address[] public listOfPlayers; // won't be deleted; sucessive lotteries overwrite indices. Don't rely on this for current participants list
uint256 public numActivePlayers;
uint256 public numTotalTickets;
mapping(uint256 => uint256) public prizes; // key is lotteryId
mapping(uint256 => WinningTicketStruct) public winningTickets; // key is lotteryId
mapping(address => bool) public players; // key is player address
mapping(address => uint256) public tickets; // key is player address
mapping(uint256 => LotteryStruct) public lotteries; // key is lotteryId
mapping(uint256 => mapping(address => uint256)) public pendingWithdrawals; // pending withdrawals for each winner, key is lotteryId, then player address
// withdrawal design pattern
// modifiers
/* @dev check that new lottery is a valid implementation
previous lottery must be inactive for new lottery to be saved
for when new lottery will be saved
*/
modifier isNewLotteryValid() {
// active lottery
LotteryStruct memory lottery = lotteries[currentLotteryId];
require(
lottery.isActive == false,
"Lottery: current lottery must be inactive to save a new one"
);
_;
}
/* @dev check that minting period is still open
for when user tries to mint more tickets
*/
modifier isLotteryMintingOpen() {
require(
lotteries[currentLotteryId].isActive == true &&
lotteries[currentLotteryId].endTime > block.timestamp &&
lotteries[currentLotteryId].startTime <= block.timestamp,
"Lottery: current lottery must be active; current time must be within lottery time frame"
);
_;
}
/* @dev check that minting period is completed, and lottery drawing can begin
either:
1) minting period manually ended, ie lottery is inactive. Then drawing can begin immediately.
2) lottery minting period has ended organically, and lottery is still active at that point
*/
modifier isLotteryMintingCompleted() {
require(
(lotteries[currentLotteryId].isActive == true &&
lotteries[currentLotteryId].endTime < block.timestamp) ||
lotteries[currentLotteryId].isActive == false,
"Lottery: current lottery must be active or minting period must be closed"
);
_;
}
/* check that new player has enough eth to buy at least 1 ticket
*/
modifier isNewPlayerValid() {
require(
msg.value.min(MIN_DRAWING_INCREMENT) >= MIN_DRAWING_INCREMENT,
"Lottery: msg value must be greater than min amount allowed"
);
_;
}
/*
* @title setMaxPlayersAllowed
* @dev A function for owner to update max players allowed criteria
* @param uint256 _maxPlayersAllowed new max players value to set
*/
function setMaxPlayersAllowed(uint256 maxPlayersAllowed_)
external
onlyOwner
{
maxPlayersAllowed = maxPlayersAllowed_;
emit MaxPlayersAllowedUpdated(maxPlayersAllowed);
}
// functions
/*
* @title setLotteryInactive
* @dev A function for owner to force update lottery status isActive to false
* public because it needs to be called internally when a Lottery is cancelled
* TASK: probably should rename this to something like "closeMintingPeriod".
*/
function setLotteryInactive() public onlyOwner {
lotteries[currentLotteryId].isActive = false;
}
/*
* @title cancelLottery
* @dev A function for owner to force update lottery to be cancelled
* funds should be returned to players too
*/
function cancelLottery() external onlyOwner {
setLotteryInactive();
_resetLottery();
// TASK: implement refund funds to users
}
/*
* @title initLottery
* @dev A function to initialize a lottery
* probably should also be onlyOwner
* @param uint256 startTime_: start of minting period, unixtime
* @param uint256 numHours: in hours, how long mint period will last
*/
function initLottery(uint256 startTime_, uint256 numHours_)
external
isNewLotteryValid
// TASK: add onlyOwner and re-test
{
// basically default value
// if set to 0, default to explicit default number of days
if (numHours_ == 0) {
numHours_ = NUMBER_OF_HOURS;
}
uint256 endTime = startTime_ + (numHours_ * 1 hours);
lotteries[currentLotteryId] = LotteryStruct({
lotteryId: currentLotteryId,
startTime: startTime_,
endTime: endTime,
isActive: true,
isCompleted: false,
isCreated: true
});
numLotteries = numLotteries + 1;
emit NewLottery(msg.sender, startTime_, endTime);
}
/*
* @title mintLotteryTickets
* @dev a function for players to mint lottery tix
*/
function mintLotteryTickets() external payable isNewPlayerValid {
uint256 _numTicketsToMint = msg.value / (MIN_DRAWING_INCREMENT);
require(_numTicketsToMint >= 1); // double check that user put in at least enough for 1 ticket
// if player is "new" for current lottery, update the player lists
// memory var to conserve gas
uint _numActivePlayers = numActivePlayers;
if (players[msg.sender] == false) {
require(_numActivePlayers + 1 <= maxPlayersAllowed); // capped max # of players
if (listOfPlayers.length > _numActivePlayers) {
listOfPlayers[_numActivePlayers] = msg.sender; // set based on index for when lottery is reset - overwrite array instead of delete to save gas
} else {
listOfPlayers.push(msg.sender); // otherwise append to array
}
players[msg.sender] = true;
numActivePlayers = _numActivePlayers + 1;
}
tickets[msg.sender] = tickets[msg.sender] + _numTicketsToMint; // account for if user has already minted tix previously for this current lottery
prizeAmount = prizeAmount + (msg.value); // update the pot size
numTotalTickets = numTotalTickets + _numTicketsToMint; // update the total # of tickets minted
emit TicketsMinted(msg.sender, _numTicketsToMint);
}
/*
* @title triggerLotteryDrawing
* @dev a function for owner to trigger lottery drawing
*/
function triggerLotteryDrawing()
external
isLotteryMintingCompleted
onlyOwner
{
// console.log("triggerLotteryDrawing");
prizes[currentLotteryId] = prizeAmount; // keep track of prize amts for each of the previous lotteries
_playerTicketDistribution(); // create the distribution to get ticket indexes for each user
// can't be done a priori bc of potential multiple mints per user
uint256 winningTicketIndex = _performRandomizedDrawing();
// initialize what we can first
winningTicket.currentLotteryId = currentLotteryId;
winningTicket.winningTicketIndex = winningTicketIndex;
findWinningAddress(winningTicketIndex); // via binary search
emit WinnerFound(
currentLotteryId,
winningTicket.winningTicketIndex,
winningTicket.addr
);
}
/*
* @title triggerDepositWinnings // TASK: rename to maybe depositWinnings
* @dev function to deposit winnings for user withdrawal pattern
* then reset lottery params for new one to be created
*/
function triggerDepositWinnings() public {
// console.log("triggerDepositWinnings");
pendingWithdrawals[currentLotteryId][winningTicket.addr] = prizeAmount;
prizeAmount = 0;
lotteries[currentLotteryId].isCompleted = true;
winningTickets[currentLotteryId] = winningTicket;
// emit before resetting lottery so vars still valid
emit LotteryWinningsDeposited(
currentLotteryId,
winningTicket.addr,
pendingWithdrawals[currentLotteryId][winningTicket.addr]
);
_resetLottery();
}
/*
* @title getTicketDistribution
* @dev getter function for ticketDistribution bc its a struct
*/
function getTicketDistribution(uint256 playerIndex_)
public
view
returns (
address playerAddress,
uint256 startIndex, // inclusive
uint256 endIndex // inclusive
)
{
return (
ticketDistribution[playerIndex_].playerAddress,
ticketDistribution[playerIndex_].startIndex,
ticketDistribution[playerIndex_].endIndex
);
}
/*
* @title _playerTicketDistribution
* @dev function to handle creating the ticket distribution
* if 1) player1 buys 10 tix, then 2) player2 buys 5 tix, and then 3) player1 buys 5 more
* player1's ticket indices will be 0-14; player2's from 15-19
* this is why ticketDistribution cannot be determined until minting period is closed
*/
function _playerTicketDistribution() private {
// console.log("_playerTicketDistribution");
uint _ticketDistributionLength = ticketDistribution.length; // so state var doesn't need to be invoked each iteration of loop
uint256 _ticketIndex = 0; // counter within loop
for (uint256 i = _ticketIndex; i < numActivePlayers; i++) {
address _playerAddress = listOfPlayers[i];
uint256 _numTickets = tickets[_playerAddress];
TicketDistributionStruct memory newDistribution = TicketDistributionStruct({
playerAddress: _playerAddress,
startIndex: _ticketIndex,
endIndex: _ticketIndex + _numTickets - 1 // sub 1 to account for array indices starting from 0
});
// gas optimization - overwrite existing values instead of re-initializing; otherwise append
if (_ticketDistributionLength > i) {
ticketDistribution[i] = newDistribution;
} else {
ticketDistribution.push(newDistribution);
}
tickets[_playerAddress] = 0; // reset player's tickets to 0 after they've been counted
_ticketIndex = _ticketIndex + _numTickets;
}
}
/*
* @title _performRandomizedDrawing
* @dev function to generate random winning ticket index. Still need to find corresponding user afterwards.
* v0.1 isn't randomized (for testing)
*/
function _performRandomizedDrawing() private view returns (uint256) {
// console.log("_performRandomizedDrawing");
/* TASK: implement random drawing from 0 to numTotalTickets-1
use chainlink https://docs.chain.link/docs/get-a-random-number/ to get random values
*/
return Random.naiveRandInt(0, numTotalTickets - 1);
}
/*
* @title findWinningAddress
* @dev function to find winning player address corresponding to winning ticket index
* calls binary search
* @param uint256 winningTicketIndex_: ticket index selected as winner.
* Search for this within the ticket distribution to find corresponding Player
*/
function findWinningAddress(uint256 winningTicketIndex_) public {
// console.log("findWinningAddress");
// trivial case, no search required
uint _numActivePlayers = numActivePlayers;
if (_numActivePlayers == 1) {
winningTicket.addr = ticketDistribution[0].playerAddress;
} else {
// do binary search on ticketDistribution array to find winner
uint256 _winningPlayerIndex = _binarySearch(
0,
_numActivePlayers - 1,
winningTicketIndex_
);
require(_winningPlayerIndex < _numActivePlayers); // sanity check
winningTicket.addr = ticketDistribution[_winningPlayerIndex]
.playerAddress;
}
}
/*
* @title _binarySearch
* @dev function implementing binary search on ticket distribution var
* recursive function
* @param uint256 leftIndex_ initially 0
* @param uint256 rightIndex_ initially max ind, ie array.length - 1
* @param uint256 ticketIndexToFind_ to search for
*/
function _binarySearch(
uint256 leftIndex_,
uint256 rightIndex_,
uint256 ticketIndexToFind_
) private returns (uint256) {
uint256 _searchIndex = (rightIndex_ - leftIndex_) / (2) + (leftIndex_);
uint _loopCount = loopCount;
// counter
loopCount = _loopCount + 1;
if (_loopCount + 1 > maxLoops) {
// emergency stop in case infinite loop due to unforeseen bug
return numActivePlayers;
}
if (
ticketDistribution[_searchIndex].startIndex <= ticketIndexToFind_ &&
ticketDistribution[_searchIndex].endIndex >= ticketIndexToFind_
) {
return _searchIndex;
} else if (
ticketDistribution[_searchIndex].startIndex > ticketIndexToFind_
) {
// go to left subarray
rightIndex_ = _searchIndex - (leftIndex_);
return _binarySearch(leftIndex_, rightIndex_, ticketIndexToFind_);
} else if (
ticketDistribution[_searchIndex].endIndex < ticketIndexToFind_
) {
// go to right subarray
leftIndex_ = _searchIndex + (leftIndex_) + 1;
return _binarySearch(leftIndex_, rightIndex_, ticketIndexToFind_);
}
// if nothing found (bug), return an impossible player index
// this index is outside expected bound, bc indexes run from 0 to numActivePlayers-1
return numActivePlayers;
}
/*
* @title _resetLottery
* @dev function to reset lottery by setting state vars to defaults
* don't delete if possible, as it requires lots of gas
*/
function _resetLottery() private {
// console.log("_resetLottery");
numTotalTickets = 0;
numActivePlayers = 0;
lotteries[currentLotteryId].isActive = false;
lotteries[currentLotteryId].isCompleted = true;
winningTicket = WinningTicketStruct({
currentLotteryId: 0,
winningTicketIndex: 0,
addr: address(0)
});
currentLotteryId = currentLotteryId + (1); // increment id counter
}
/*
* @title withdraw
* @dev function to allow winner to withdraw prize
* implement withdrawal pattern
* @param uint256 lotteryId_ to minimize the search requirement
*/
function withdraw(uint256 lotteryId_) external payable {
// console.log("withdraw");
uint256 _pendingCurrentUserWithdrawal = pendingWithdrawals[lotteryId_][
msg.sender
];
require(
_pendingCurrentUserWithdrawal > 0,
"require pending withdrawals to have funds for given user"
);
pendingWithdrawals[lotteryId_][msg.sender] = 0; // zero out pendingWithdrawals before transfer, to prevent attacks
payable(msg.sender).transfer(_pendingCurrentUserWithdrawal); // must explicitly set payable address
emit WinnerFundsWithdrawn(msg.sender, _pendingCurrentUserWithdrawal);
}
}
| TASK: rename to TICKET_PRICE? More human readable, makes more sense. Although it technically is the minimum increment./ | uint256 public maxPlayersAllowed = 1000;
| 12,780,120 | [
1,
15580,
30,
6472,
358,
399,
16656,
1584,
67,
7698,
1441,
35,
16053,
8672,
7471,
16,
7297,
1898,
12764,
18,
2262,
18897,
518,
17734,
6478,
353,
326,
5224,
5504,
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,
565,
2254,
5034,
1071,
943,
1749,
3907,
5042,
273,
4336,
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/4/0x1260d1d95CE4b1CDD7f39E64766dF9E70Ae2953D/sources/github/teller-protocol/teller-protocol-v1/nft/contracts/util/NumbersList.sol | * @param self The Value this function was called on @return the average number that was used to calculate the sum/ | function getAverage(Values memory self) internal pure returns (uint256) {
return isEmpty(self) ? 0 : self.sum.div(valuesCount(self));
}
| 13,330,608 | [
1,
2890,
1021,
1445,
333,
445,
1703,
2566,
603,
327,
326,
8164,
1300,
716,
1703,
1399,
358,
4604,
326,
2142,
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,
4506,
5682,
12,
1972,
3778,
365,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
2709,
12,
2890,
13,
692,
374,
294,
365,
18,
1364,
18,
2892,
12,
2372,
1380,
12,
2890,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x1c075411c72789fA64843a35e453FA2B3Df4E380/sources/HodlDex.sol | Usually the supply, used to calculate user shares, e.g. balance / circulating supply
| uint denominator; | 4,397,987 | [
1,
3477,
3452,
326,
14467,
16,
1399,
358,
4604,
729,
24123,
16,
425,
18,
75,
18,
11013,
342,
5886,
1934,
1776,
14467,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
15030,
31,
10792,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.4;
import "./SafeMath.sol";
import "./TellorGetters.sol";
import "./TellorVariables.sol";
import "./Utilities.sol";
/**
@author Tellor Inc.
@title Extension
@dev This contract holds staking functions, tallyVotes and updateDisputeFee
* Because of space limitations and will be consolidated in future iterations
**/
contract Extension is TellorGetters {
using SafeMath for uint256;
/*Events*/
//emitted upon dispute tally
event DisputeVoteTallied(
uint256 indexed _disputeID,
int256 _result,
address indexed _reportedMiner,
address _reportingParty,
bool _passed
);
event StakeWithdrawn(address indexed _sender); //Emits when a staker is block.timestamp no longer staked
event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period
event NewStake(address indexed _sender); //Emits upon new staker
event NewTellorAddress(address _newTellor);
/*Functions*/
/**
* @dev This function allows miners to deposit their stake.
*/
function depositStake() external{
_newStake(msg.sender);
updateMinDisputeFee();
}
/**
* @dev This function allows stakers to request to withdraw their stake (no longer stake)
* once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they
* can withdraw the deposit
*/
function requestStakingWithdraw() external {
StakeInfo storage stakes = stakerDetails[msg.sender];
//Require that the miner is staked
require(stakes.currentStatus == 1, "Miner is not staked");
//Change the miner staked to locked to be withdrawStake
stakes.currentStatus = 2;
//Change the startDate to block.timestamp since the lock up period begins block.timestamp
//and the miner can only withdraw 7 days later from block.timestamp(check the withdraw function)
stakes.startDate = block.timestamp - (block.timestamp % 86400);
//Reduce the staker count
uints[_STAKE_COUNT] -= 1;
//Update the minimum dispute fee that is based on the number of stakers
updateMinDisputeFee();
emit StakeWithdrawRequested(msg.sender);
}
/**
* @dev tallies the votes and locks the stake disbursement(currentStatus = 4) if the vote passes
* @param _disputeId is the dispute id
*/
function tallyVotes(uint256 _disputeId) external {
Dispute storage disp = disputesById[_disputeId];
//Ensure this has not already been executed/tallied
require(disp.executed == false, "Dispute has been already executed");
//Ensure that the vote has been open long enough
require(
block.timestamp >= disp.disputeUintVars[_MIN_EXECUTION_DATE],
"Time for voting haven't elapsed"
);
//Ensure that it's a valid disputeId
require(
disp.reportingParty != address(0),
"reporting Party is address 0"
);
int256 _tally = disp.tally;
if (_tally > 0) {
//If the vote is not a proposed fork
if (disp.isPropFork == false) {
//Set the dispute state to passed/true
disp.disputeVotePassed = true;
//Ensure the time for voting has elapsed
StakeInfo storage stakes = stakerDetails[disp.reportedMiner];
//If the vote for disputing a value is successful(disp.tally >0) then unstake the reported
if (stakes.currentStatus == 3) {
stakes.currentStatus = 4;
}
} else if (uint256(_tally) >= ((uints[_TOTAL_SUPPLY] * 5) / 100)) {
disp.disputeVotePassed = true;
}
}
disp.disputeUintVars[_TALLY_DATE] = block.timestamp;
disp.executed = true;
emit DisputeVoteTallied(
_disputeId,
_tally,
disp.reportedMiner,
disp.reportingParty,
disp.disputeVotePassed
);
}
/**
* @dev This function updates the minimum dispute fee as a function of the amount
* of staked miners
*/
function updateMinDisputeFee() public {
uint256 _stakeAmt = uints[_STAKE_AMOUNT];
uint256 _trgtMiners = uints[_TARGET_MINERS];
uints[_DISPUTE_FEE] = SafeMath.max(
15e18,
(_stakeAmt -
((_stakeAmt *
(SafeMath.min(_trgtMiners, uints[_STAKE_COUNT]) * 1000)) /
_trgtMiners) /
1000)
);
}
/**
* @dev Updates the Tellor address after a proposed fork has
* passed the vote and day has gone by without a dispute
* @param _disputeId the disputeId for the proposed fork
*/
function updateTellor(uint256 _disputeId) external {
bytes32 _hash = disputesById[_disputeId].hash;
uint256 origID = disputeIdByDisputeHash[_hash];
//this checks the "lastID" or the most recent if this is a multiple dispute case
uint256 lastID =
disputesById[origID].disputeUintVars[
keccak256(
abi.encode(
disputesById[origID].disputeUintVars[_DISPUTE_ROUNDS]
)
)
];
TellorStorage.Dispute storage disp = disputesById[lastID];
require(disp.isPropFork, "must be a fork proposal");
require(
disp.disputeUintVars[_FORK_EXECUTED] == 0,
"update Tellor has already been run"
);
require(disp.disputeVotePassed == true, "vote needs to pass");
require(disp.disputeUintVars[_TALLY_DATE] > 0, "vote needs to be tallied");
require(
block.timestamp - disp.disputeUintVars[_TALLY_DATE] > 1 days,
"Time for voting for further disputes has not passed"
);
disp.disputeUintVars[_FORK_EXECUTED] = 1;
address _newTellor =disp.proposedForkAddress;
addresses[_TELLOR_CONTRACT] = _newTellor;
assembly {
sstore(_EIP_SLOT, _newTellor)
}
emit NewTellorAddress(_newTellor);
}
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting
* period from request
*/
function withdrawStake() external {
StakeInfo storage stakes = stakerDetails[msg.sender];
//Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have
//passed by since they locked for withdraw
require(
block.timestamp - (block.timestamp % 86400) - stakes.startDate >=
7 days,
"7 days didn't pass"
);
require(
stakes.currentStatus == 2,
"Miner was not locked for withdrawal"
);
stakes.currentStatus = 0;
emit StakeWithdrawn(msg.sender);
}
/**
* @dev This internal function is used the depositStake function to successfully stake miners.
* The function updates their status/state and status start date so they are locked it so they can't withdraw
* and updates the number of stakers in the system.
* @param _staker the address of the new staker
*/
function _newStake(address _staker) internal {
require(
balances[_staker][balances[_staker].length - 1].value >=
uints[_STAKE_AMOUNT],
"Balance is lower than stake amount"
);
//Ensure they can only stake if they are not currently staked or if their stake time frame has ended
//and they are currently locked for withdraw
require(
stakerDetails[_staker].currentStatus == 0 ||
stakerDetails[_staker].currentStatus == 2,
"Miner is in the wrong state"
);
uints[_STAKE_COUNT] += 1;
stakerDetails[_staker] = StakeInfo({
currentStatus: 1,
startDate: block.timestamp//this resets their stake start date to now
});
emit NewStake(_staker);
}
}
| * @dev Updates the Tellor address after a proposed fork has passed the vote and day has gone by without a dispute @param _disputeId the disputeId for the proposed fork/this checks the "lastID" or the most recent if this is a multiple dispute case | function updateTellor(uint256 _disputeId) external {
bytes32 _hash = disputesById[_disputeId].hash;
uint256 origID = disputeIdByDisputeHash[_hash];
uint256 lastID =
disputesById[origID].disputeUintVars[
keccak256(
abi.encode(
disputesById[origID].disputeUintVars[_DISPUTE_ROUNDS]
)
)
];
TellorStorage.Dispute storage disp = disputesById[lastID];
require(disp.isPropFork, "must be a fork proposal");
require(
disp.disputeUintVars[_FORK_EXECUTED] == 0,
"update Tellor has already been run"
);
require(disp.disputeVotePassed == true, "vote needs to pass");
require(disp.disputeUintVars[_TALLY_DATE] > 0, "vote needs to be tallied");
require(
block.timestamp - disp.disputeUintVars[_TALLY_DATE] > 1 days,
"Time for voting for further disputes has not passed"
);
disp.disputeUintVars[_FORK_EXECUTED] = 1;
address _newTellor =disp.proposedForkAddress;
addresses[_TELLOR_CONTRACT] = _newTellor;
assembly {
sstore(_EIP_SLOT, _newTellor)
}
emit NewTellorAddress(_newTellor);
}
| 5,480,458 | [
1,
5121,
326,
29860,
280,
1758,
1839,
279,
20084,
12515,
711,
2275,
326,
12501,
471,
2548,
711,
22296,
635,
2887,
279,
1015,
2507,
225,
389,
2251,
2507,
548,
326,
1015,
2507,
548,
364,
326,
20084,
12515,
19,
2211,
4271,
326,
315,
2722,
734,
6,
578,
326,
4486,
8399,
309,
333,
353,
279,
3229,
1015,
2507,
648,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1089,
21009,
280,
12,
11890,
5034,
389,
2251,
2507,
548,
13,
3903,
288,
203,
3639,
1731,
1578,
389,
2816,
273,
1015,
458,
281,
5132,
63,
67,
2251,
2507,
548,
8009,
2816,
31,
203,
3639,
2254,
5034,
1647,
734,
273,
1015,
2507,
548,
858,
1669,
2507,
2310,
63,
67,
2816,
15533,
203,
3639,
2254,
5034,
1142,
734,
273,
203,
5411,
1015,
458,
281,
5132,
63,
4949,
734,
8009,
2251,
2507,
5487,
5555,
63,
203,
7734,
417,
24410,
581,
5034,
12,
203,
10792,
24126,
18,
3015,
12,
203,
13491,
1015,
458,
281,
5132,
63,
4949,
734,
8009,
2251,
2507,
5487,
5555,
63,
67,
2565,
3118,
9099,
67,
1457,
2124,
3948,
65,
203,
10792,
262,
203,
7734,
262,
203,
5411,
308,
31,
203,
3639,
29860,
280,
3245,
18,
1669,
2507,
2502,
16232,
273,
1015,
458,
281,
5132,
63,
2722,
734,
15533,
203,
3639,
2583,
12,
25453,
18,
291,
4658,
22662,
16,
315,
11926,
506,
279,
12515,
14708,
8863,
203,
3639,
2583,
12,
203,
5411,
16232,
18,
2251,
2507,
5487,
5555,
63,
67,
7473,
47,
67,
15271,
57,
6404,
65,
422,
374,
16,
203,
5411,
315,
2725,
29860,
280,
711,
1818,
2118,
1086,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
25453,
18,
2251,
2507,
19338,
22530,
422,
638,
16,
315,
25911,
4260,
358,
1342,
8863,
203,
3639,
2583,
12,
25453,
18,
2251,
2507,
5487,
5555,
63,
67,
56,
4685,
61,
67,
4594,
65,
405,
374,
16,
315,
25911,
4260,
358,
506,
268,
454,
2092,
8863,
203,
3639,
2583,
12,
203,
5411,
1203,
18,
5508,
300,
2
] |
./full_match/137/0x05625c47ff38C43c15f047425e6bd5C5c80B57f7/sources/contracts/cooldogs.sol | тут пишите цену за минт 1 изображения из вашей коллекции
| uint256 public cost = 0.7 ether; | 4,781,501 | [
1,
146,
229,
146,
230,
146,
229,
225,
145,
128,
145,
121,
146,
235,
145,
121,
146,
229,
145,
118,
225,
146,
233,
145,
118,
145,
126,
146,
230,
225,
145,
120,
145,
113,
225,
145,
125,
145,
121,
145,
126,
146,
229,
404,
225,
145,
121,
145,
120,
145,
127,
145,
114,
146,
227,
145,
113,
145,
119,
145,
118,
145,
126,
145,
121,
146,
242,
225,
145,
121,
145,
120,
225,
145,
115,
145,
113,
146,
235,
145,
118,
145,
122,
225,
145,
123,
145,
127,
145,
124,
145,
124,
145,
118,
145,
123,
146,
233,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
2254,
5034,
1071,
6991,
273,
374,
18,
27,
225,
2437,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-07-27
*/
// SPDX-License-Identifier: AGPL-3.0-or-later\
pragma solidity 0.7.5;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @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;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
/*
* Expects percentage to be trailed by 00,
*/
function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) {
return div( mul( total_, percentage_ ), 1000 );
}
/*
* Expects percentage to be trailed by 00,
*/
function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) {
return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) );
}
function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) {
return div( mul(part_, 100) , total_ );
}
/**
* Taken from Hypersonic https://github.com/M2629/HyperSonic/blob/main/Math.sol
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) {
return sqrrt( mul( multiplier_, payment_ ) );
}
function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) {
return mul( multiplier_, supply_ );
}
}
/**
* @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 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
/**
* @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);
}
interface ITreasury {
function deposit( uint _amount, address _token, uint _profit ) external returns ( uint );
}
interface IwOHM {
function sOHMTowOHM( uint amount ) external view returns ( uint );
function wOHMTosOHM( uint amount ) external view returns ( uint );
}
interface IStaking {
function stake( uint _amount, address _recipient ) external returns ( bool );
function claim( address _recipient ) external;
}
/**
* This contract allows Olympus seed investors and advisors to claim tokens.
* It has been revised to consider claims as staked immediately for accounting purposes.
* This ensures that network ownership does not exceed disclosed levels.
* Claimants remain protected from network dilution that may arise, but claim and stake
* does not allow them to grow ownership beyond predefined levels. This change also penalizes
* sellers, since the tokens sold are still considered staked within this contract. This
* step was taken to ensure fair distribution of exposure in the network.
*/
contract InvestorClaimV2 {
/* ========== DEPENDENCIES ========== */
using SafeMath for uint;
using SafeERC20 for IERC20;
/* ========== STRUCTS ========== */
struct Term {
uint percent; // 4 decimals ( 5000 = 0.5% )
uint wClaimed; // rebase-agnostic number
uint max; // maximum nominal OHM amount can claim
}
/* ========== STATE VARIABLES ========== */
address owner; // can set terms
address newOwner; // push/pull model for changing ownership
IERC20 immutable OHM; // claim token
IERC20 immutable DAI; // payment token
ITreasury immutable treasury; // mints claim token
IStaking immutable staking; // stake OHM for sOHM
address immutable DAO; // holds non-circulating supply
IwOHM immutable wOHM; // tracks rebase-agnostic balance
mapping( address => Term ) public terms; // tracks address info
mapping( address => address ) public walletChange; // facilitates address change
uint public totalAllocated; // as percent of supply (4 decimals: 10000 = 1%)
uint public maximumAllocated; // maximum portion of supply can allocate
/* ========== CONSTRUCTOR ========== */
constructor(
address _ohm,
address _dai,
address _treasury,
address _DAO,
address _wOHM,
address _staking,
uint _maximumAllocated
) {
owner = msg.sender;
require( _ohm != address(0) );
OHM = IERC20( _ohm );
require( _dai != address(0) );
DAI = IERC20( _dai );
require( _treasury != address(0) );
treasury = ITreasury( _treasury );
require( _DAO != address(0) );
DAO = _DAO;
require( _wOHM != address(0) );
wOHM = IwOHM( _wOHM );
require( _staking != address(0) );
staking = IStaking( _staking );
maximumAllocated = _maximumAllocated;
}
/* ========== USER FUNCTIONS ========== */
/**
* @notice allows wallet to claim OHM
* @param _amount uint
*/
function claim( uint _amount ) external {
OHM.safeTransfer( msg.sender, _claim( _amount ) ); // send claimed to sender
}
/**
* @notice allows wallet to claim OHM and stake.
* @notice set _claim to true to receive sOHM in wallet.
* @param _amount uint
* @param _claimsOHM bool
*/
function stake( uint _amount, bool _claimsOHM ) external {
uint toStake = _claim( _amount ); // claim OHM with DAI
OHM.approve( address( staking ), toStake );
staking.stake( toStake, msg.sender ); // stake OHM for sender
if ( _claimsOHM ) {
staking.claim( msg.sender ); // claim sOHM for sender
}
}
/**
* @notice logic for claiming OHM
* @param _amount uint
* @return ToSend_ uint
*/
function _claim( uint _amount ) internal returns ( uint ToSend_ ) {
DAI.safeTransferFrom( msg.sender, address( this ), _amount ); // transfer DAI payment in
DAI.approve( address( treasury ), _amount ); // approve and
ToSend_ = treasury.deposit( _amount, address( DAI ), 0 ); // deposit into treasury, receive OHM
// ensure claim is within bounds
require( claimableFor( msg.sender ).div( 1e9 ) >= ToSend_, 'Not enough vested' );
require( terms[ msg.sender ].max.sub( claimed( msg.sender ) ) >= ToSend_, 'Claimed over max' );
// add amount to tracked balance
terms[ msg.sender ].wClaimed = terms[ msg.sender ].wClaimed.add( wOHM.sOHMTowOHM( ToSend_ ) );
}
/**
* @notice allows address to push terms to new address
* @param _newAddress address
*/
function pushWalletChange( address _newAddress ) external {
require( terms[ msg.sender ].percent != 0 );
walletChange[ msg.sender ] = _newAddress;
}
/**
* @notice allows new address to pull terms
* @param _oldAddress address
*/
function pullWalletChange( address _oldAddress ) external {
require( walletChange[ _oldAddress ] == msg.sender, "wallet did not push" );
walletChange[ _oldAddress ] = address(0);
terms[ msg.sender ] = terms[ _oldAddress ];
delete terms[ _oldAddress ];
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice view OHM claimable for address. DAI decimals (18).
* @param _address address
* @return uint
*/
function claimableFor( address _address ) public view returns (uint) {
Term memory info = terms[ _address ];
uint max = circulatingSupply().mul( info.percent ).div( 1e6 );
if ( max > info.max ) {
max = info.max;
}
return max.sub( claimed( _address ) ).mul( 1e9 );
}
/**
* @notice view OHM claimed by address. OHM decimals (9).
* @param _address address
* @return uint
*/
function claimed( address _address ) public view returns ( uint ) {
return wOHM.wOHMTosOHM( terms[ _address ].wClaimed );
}
/**
* @notice view circulating supply of OHM
* @notice calculated as total supply minus DAO holdings
* @return uint
*/
function circulatingSupply() public view returns ( uint ) {
return OHM.totalSupply().sub( OHM.balanceOf( DAO ) );
}
/* ========== OWNER FUNCTIONS ========== */
/**
* @notice set terms for new address
* @notice cannot lower for address or exceed maximum total allocation
* @param _address address
* @param _max uint
* @param _rate uint
* @param _hasClaimed uint
*/
function setTerms(address _address, uint _max, uint _rate, uint _hasClaimed ) external {
require( msg.sender == owner, "Sender is not owner" );
require( _max >= terms[ _address ].max, "cannot lower amount claimable" );
require( _rate >= terms[ _address ].percent, "cannot lower vesting rate" );
require( totalAllocated.add( _rate ) <= maximumAllocated, "Cannot allocate more" );
if( terms[ _address ].max == 0 ) {
terms[ _address ].wClaimed = wOHM.sOHMTowOHM( _hasClaimed );
}
terms[ _address ].max = _max;
terms[ _address ].percent = _rate;
totalAllocated = totalAllocated.add( _rate );
}
/**
* @notice push ownership of contract
* @param _newOwner address
*/
function pushOwnership( address _newOwner ) external {
require( msg.sender == owner, "Sender is not owner" );
require( _newOwner != address(0) );
newOwner = _newOwner;
}
/**
* @notice pull ownership of contract
*/
function pullOwnership() external {
require( msg.sender == newOwner );
owner = newOwner;
newOwner = address(0);
}
/**
* @notice renounce ownership of contract (no owner)
*/
function renounceOwnership() external {
require( msg.sender == owner, "Sender is not owner" );
owner = address(0);
newOwner = address(0);
}
} | send claimed to sender
| OHM.safeTransfer( msg.sender, _claim( _amount ) ); | 146,043 | [
1,
4661,
7516,
329,
358,
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
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
531,
44,
49,
18,
4626,
5912,
12,
1234,
18,
15330,
16,
389,
14784,
12,
389,
8949,
262,
11272,
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
] |
./full_match/5/0xCf86e56b395032163dd4Af966500e2F189f29637/sources/contracts/contracts-V6/src/Libraries.sol | Enrol to project as worker when no application is required ✅ Creates application to deal with stake | function workerEnrolNoApplication(
Project storage _project,
CampaignManager.Campaign storage _campaign,
Application storage _application,
uint256 _id,
uint256 _applicationCount
) external {
require(!_project.applicationRequired, "E33");
_application.metadata = "_";
_application.applicant = msg.sender;
_application.accepted = true;
_application.enrolStake.funder = payable(msg.sender);
_application.enrolStake.funding = msg.value;
_application.enrolStake.amountUsed = 0;
_application.enrolStake.fullyRefunded = false;
_application.parentProject = _id;
_project.applications.push(_applicationCount);
_project.workers.push(msg.sender);
_campaign.allTimeStakeholders.push(payable(msg.sender));
}
| 7,070,655 | [
1,
664,
922,
358,
1984,
487,
4322,
1347,
1158,
2521,
353,
1931,
225,
163,
255,
232,
10210,
2521,
358,
10490,
598,
384,
911,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4322,
664,
922,
2279,
3208,
12,
203,
3639,
5420,
2502,
389,
4406,
16,
203,
3639,
17820,
1318,
18,
13432,
2502,
389,
14608,
16,
203,
3639,
4257,
2502,
389,
3685,
16,
203,
3639,
2254,
5034,
389,
350,
16,
203,
3639,
2254,
5034,
389,
3685,
1380,
203,
565,
262,
3903,
288,
203,
3639,
2583,
12,
5,
67,
4406,
18,
3685,
3705,
16,
315,
41,
3707,
8863,
203,
203,
203,
3639,
389,
3685,
18,
4165,
273,
8802,
31,
203,
3639,
389,
3685,
18,
438,
1780,
970,
273,
1234,
18,
15330,
31,
203,
3639,
389,
3685,
18,
23847,
273,
638,
31,
203,
3639,
389,
3685,
18,
12401,
510,
911,
18,
74,
9341,
273,
8843,
429,
12,
3576,
18,
15330,
1769,
203,
3639,
389,
3685,
18,
12401,
510,
911,
18,
74,
14351,
273,
1234,
18,
1132,
31,
203,
3639,
389,
3685,
18,
12401,
510,
911,
18,
8949,
6668,
273,
374,
31,
203,
3639,
389,
3685,
18,
12401,
510,
911,
18,
4095,
1957,
12254,
273,
629,
31,
203,
3639,
389,
3685,
18,
2938,
4109,
273,
389,
350,
31,
203,
203,
3639,
389,
4406,
18,
3685,
87,
18,
6206,
24899,
3685,
1380,
1769,
203,
203,
3639,
389,
4406,
18,
15625,
18,
6206,
12,
3576,
18,
15330,
1769,
203,
3639,
389,
14608,
18,
454,
950,
510,
911,
9000,
18,
6206,
12,
10239,
429,
12,
3576,
18,
15330,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42/0xd076f69BC9f8452CE54711ff2A7662Ed8Df8A74b/sources/Documents/DEV/PRUF/PRUF_TRUFFLE/contracts/PRUF_UTIL_TKN.sol | * @dev all paused functions are blocked here, unless caller has "pauser" role @param _from - Address from which to send tokens @param _to - Address to send tokens to @param _amount - amount of tokens to transfer/ When minting tokens | function _beforeTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal virtual override(ERC20, ERC20Snapshot) {
super._beforeTokenTransfer(_from, _to, _amount);
require(
(!paused()) || hasRole(PAUSER_ROLE, _msgSender()),
"ERC20Pausable: function unavailble while contract is paused"
);
if (_from == address(0)) {
require(
totalSupply() + (_amount) <= _cap,
"ERC20Capped: cap exceeded"
);
}
}
| 9,591,830 | [
1,
454,
17781,
4186,
854,
14547,
2674,
16,
3308,
4894,
711,
315,
8774,
1355,
6,
2478,
225,
389,
2080,
300,
5267,
628,
1492,
358,
1366,
2430,
225,
389,
869,
300,
5267,
358,
1366,
2430,
358,
225,
389,
8949,
300,
3844,
434,
2430,
358,
7412,
19,
5203,
312,
474,
310,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
389,
2080,
16,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
8949,
203,
565,
262,
2713,
5024,
3849,
12,
654,
39,
3462,
16,
4232,
39,
3462,
4568,
13,
288,
203,
3639,
2240,
6315,
5771,
1345,
5912,
24899,
2080,
16,
389,
869,
16,
389,
8949,
1769,
203,
203,
3639,
2583,
12,
203,
5411,
16051,
8774,
3668,
10756,
747,
28335,
12,
4066,
4714,
67,
16256,
16,
389,
3576,
12021,
1435,
3631,
203,
5411,
315,
654,
39,
3462,
16507,
16665,
30,
445,
640,
842,
671,
7119,
1323,
6835,
353,
17781,
6,
203,
3639,
11272,
203,
3639,
309,
261,
67,
2080,
422,
1758,
12,
20,
3719,
288,
203,
5411,
2583,
12,
203,
7734,
2078,
3088,
1283,
1435,
397,
261,
67,
8949,
13,
1648,
389,
5909,
16,
203,
7734,
315,
654,
39,
3462,
4664,
1845,
30,
3523,
12428,
6,
203,
5411,
11272,
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
] |
/**
*Submitted for verification at Etherscan.io on 2020-08-28
*/
/*
111 11111111111 111
111 1111111111111111
111 111111 111111
111 111111 111111
11111111111111111111 111
1111111111111111111 111
111111 1111111111
1111111111111111111
1111111111111111111
1111111111111111111
111 111111111 111
111 111111111 111*/
pragma solidity 0.5.17;
interface IERC20 { // brief interface for erc20 token tx
function balanceOf(address account) external view returns (uint256);
}
contract LexAIR {
address public accessToken;
address public governance;
address[] private registrations;
string public message;
mapping(address => Registry) private registryList;
event Register(address indexed account, bytes32 indexed message);
event Deregister(address indexed account, bytes32 indexed message);
event UpdateAccessToken(address indexed accessToken);
event UpdateGovernance(address indexed governance);
event UpdateMessage(string indexed message);
struct Registry {
uint256 accountIndex;
bool registered;
}
constructor (address[] memory _account, address _accessToken, address _governance, string memory _message) public {
for (uint256 i = 0; i < _account.length; i++) {
registryList[_account[i]].accountIndex = registrations.push(_account[i]) - 1;
registryList[_account[i]].registered = true;
}
accessToken = _accessToken;
governance = _governance;
message = _message;
}
modifier onlyGovernance {
require(tx.origin == governance, "!governance"); //inject USING TX ORIGIN FOR AUTHENTICATION
_;
}
/*********************
REGISTRATION FUNCTIONS
*********************/
function deregister(address[] calldata _account, bytes32 _message) external {
require(IERC20(accessToken).balanceOf(msg.sender) >= 1, "!access");
for (uint256 i = 0; i < _account.length; i++) {
require(registryList[_account[i]].registered, "!registered");
uint256 accountToUnlist = registryList[_account[i]].accountIndex;
address acct = registrations[registrations.length - 1];
registrations[accountToUnlist] = acct;
registryList[acct].accountIndex = accountToUnlist;
registryList[_account[i]].registered = false;
registrations.length--;
emit Deregister(_account[i], _message);
}
}
function register(address[] calldata _account, bytes32 _message) external {
require(IERC20(accessToken).balanceOf(msg.sender) >= 1, "!access");
for (uint256 i = 0; i < _account.length; i++) {
require(!registryList[_account[i]].registered, "registered");
registryList[_account[i]].accountIndex = registrations.push(_account[i]) - 1;
registryList[_account[i]].registered = true;
emit Register(_account[i], _message);
}
}
function updateAccessToken(address _accessToken) external onlyGovernance {
accessToken = _accessToken;
emit UpdateAccessToken(accessToken);
}
function updateGovernance(address _governance) external onlyGovernance {
governance = _governance;
emit UpdateGovernance(governance);
}
function updateMessage(string calldata _message) external onlyGovernance {
message = _message;
emit UpdateMessage(message);
}
// *******
// GETTERS
// *******
function accountCount() external view returns (uint256) {
return registrations.length;
}
function isRegistered(address _account) external view returns (bool) {
if(registrations.length == 0) return false;
return (registrations[registryList[_account].accountIndex] == _account);
}
} | inject USING TX ORIGIN FOR AUTHENTICATION
| require(tx.origin == governance, "!governance"); | 986,817 | [
1,
22170,
11836,
1360,
23211,
24069,
7702,
12108,
12790,
18915,
2689,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
978,
18,
10012,
422,
314,
1643,
82,
1359,
16,
17528,
75,
1643,
82,
1359,
8863,
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
] |
pragma solidity ^0.4.18;
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 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();
}
}
contract SkinPresale is Pausable {
// Record number of packages each account buy
mapping (address => uint256) public accountToBoughtNum;
// Total number of packages for presale
uint256 public totalSupplyForPresale = 10000;
// Number of packages each account can buy
uint256 public accountBuyLimit = 100;
// Remaining packages for presale
uint256 public remainPackage = 10000;
// Event
event BuyPresale(address account);
function buyPresale() payable external whenNotPaused {
address account = msg.sender;
// Check account limit
require(accountToBoughtNum[account] + 1 < accountBuyLimit);
// Check total presale limit
require(remainPackage > 0);
// Check enough money
uint256 price = 20 finney + (10000 - remainPackage) / 500 * 10 finney;
require(msg.value >= price);
// Perform purchase
accountToBoughtNum[account] += 1;
remainPackage -= 1;
// Fire event
BuyPresale(account);
}
function withdrawETH() external onlyOwner {
owner.transfer(this.balance);
}
} | Record number of packages each account buy Total number of packages for presale Number of packages each account can buy Remaining packages for presale Event | contract SkinPresale is Pausable {
mapping (address => uint256) public accountToBoughtNum;
uint256 public totalSupplyForPresale = 10000;
uint256 public accountBuyLimit = 100;
uint256 public remainPackage = 10000;
event BuyPresale(address account);
function buyPresale() payable external whenNotPaused {
address account = msg.sender;
require(accountToBoughtNum[account] + 1 < accountBuyLimit);
require(remainPackage > 0);
uint256 price = 20 finney + (10000 - remainPackage) / 500 * 10 finney;
require(msg.value >= price);
accountToBoughtNum[account] += 1;
remainPackage -= 1;
BuyPresale(account);
}
function withdrawETH() external onlyOwner {
owner.transfer(this.balance);
}
} | 6,828,650 | [
1,
2115,
1300,
434,
5907,
1517,
2236,
30143,
10710,
1300,
434,
5907,
364,
4075,
5349,
3588,
434,
5907,
1517,
2236,
848,
30143,
2663,
3280,
5907,
364,
4075,
5349,
2587,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
10362,
267,
12236,
5349,
353,
21800,
16665,
288,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
2236,
774,
13809,
9540,
2578,
31,
203,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
1290,
12236,
5349,
273,
12619,
31,
203,
203,
565,
2254,
5034,
1071,
2236,
38,
9835,
3039,
273,
2130,
31,
203,
203,
565,
2254,
5034,
1071,
7232,
2261,
273,
12619,
31,
203,
203,
565,
871,
605,
9835,
12236,
5349,
12,
2867,
2236,
1769,
203,
203,
565,
445,
30143,
12236,
5349,
1435,
8843,
429,
3903,
1347,
1248,
28590,
288,
203,
3639,
1758,
2236,
273,
1234,
18,
15330,
31,
203,
203,
3639,
2583,
12,
4631,
774,
13809,
9540,
2578,
63,
4631,
65,
397,
404,
411,
2236,
38,
9835,
3039,
1769,
203,
203,
3639,
2583,
12,
2764,
530,
2261,
405,
374,
1769,
203,
203,
3639,
2254,
5034,
6205,
273,
4200,
574,
82,
402,
397,
261,
23899,
300,
7232,
2261,
13,
342,
6604,
380,
1728,
574,
82,
402,
31,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
6205,
1769,
203,
203,
3639,
2236,
774,
13809,
9540,
2578,
63,
4631,
65,
1011,
404,
31,
203,
3639,
7232,
2261,
3947,
404,
31,
203,
203,
3639,
605,
9835,
12236,
5349,
12,
4631,
1769,
203,
565,
289,
203,
203,
565,
445,
598,
9446,
1584,
44,
1435,
3903,
1338,
5541,
288,
203,
3639,
3410,
18,
13866,
12,
2211,
18,
12296,
1769,
203,
565,
289,
203,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xbf5A7F3629fB325E2a8453D595AB103465F75E62/sources/src/portals/router/RouterBase.sol | @notice Invalidates the next order of msg.sender @notice Orders that have already been confirmed are not invalidated | function invalidateNextOrder() external {
++nonces[msg.sender];
}
| 9,619,759 | [
1,
1941,
815,
326,
1024,
1353,
434,
1234,
18,
15330,
225,
2965,
6794,
716,
1240,
1818,
2118,
19979,
854,
486,
28711,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
11587,
2134,
2448,
1435,
3903,
288,
203,
3639,
965,
5836,
764,
63,
3576,
18,
15330,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
The MIT License (MIT)
Copyright (c) 2016 DFINITY Stiftung
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* title: The DFINITY Stiftung donation contract (FDC).
* author: Timo Hanke
*
* This contract
* - accepts on-chain donations for the foundation in ether
* - tracks on-chain and off-chain donations made to the foundation
* - assigns unrestricted tokens to addresses provided by donors
* - assigns restricted tokens to DFINITY Stiftung and early contributors
*
* On-chain donations are received in ether are converted to Swiss francs (CHF).
* Off-chain donations are received and recorded directly in Swiss francs.
* Tokens are assigned at a rate of 10 tokens per CHF.
*
* There are two types of tokens initially. Unrestricted tokens are assigned to
* donors and restricted tokens are assigned to DFINITY Stiftung and early
* contributors. Restricted tokens are converted to unrestricted tokens in the
* finalization phase, after which only unrestricted tokens exist.
*
* After the finalization phase, tokens assigned to DFINITY Stiftung and early
* contributors will make up a pre-defined share of all tokens. This is achieved
* through burning excess restricted tokens before their restriction is removed.
*/
pragma solidity ^0.4.6;
// import "TokenTracker.sol";
/**
* title: A contract that tracks numbers of tokens assigned to addresses.
* author: Timo Hanke
*
* Optionally, assignments can be chosen to be of "restricted type".
* Being "restricted" means that the token assignment may later be partially
* reverted (or the tokens "burned") by the contract.
*
* After all token assignments are completed the contract
* - burns some restricted tokens
* - releases the restriction on the remaining tokens
* The percentage of tokens that burned out of each assignment of restricted
* tokens is calculated to achieve the following condition:
* - the remaining formerly restricted tokens combined have a pre-configured
* share (percentage) among all remaining tokens.
*
* Once the conversion process has started the contract enters a state in which
* no more assignments can be made.
*/
contract TokenTracker {
// Share of formerly restricted tokens among all tokens in percent
uint public restrictedShare;
// Mapping from address to number of tokens assigned to the address
mapping(address => uint) public tokens;
// Mapping from address to number of tokens assigned to the address that
// underly a restriction
mapping(address => uint) public restrictions;
// Total number of (un)restricted tokens currently in existence
uint public totalRestrictedTokens;
uint public totalUnrestrictedTokens;
// Total number of individual assignment calls have been for (un)restricted
// tokens
uint public totalRestrictedAssignments;
uint public totalUnrestrictedAssignments;
// State flag. Assignments can only be made if false.
// Starting the conversion (burn) process irreversibly sets this to true.
bool public assignmentsClosed = false;
// The multiplier (defined by nominator and denominator) that defines the
// fraction of all restricted tokens to be burned.
// This is computed after assignments have ended and before the conversion
// process starts.
uint public burnMultDen;
uint public burnMultNom;
function TokenTracker(uint _restrictedShare) {
// Throw if restricted share >= 100
if (_restrictedShare >= 100) { throw; }
restrictedShare = _restrictedShare;
}
/**
* PUBLIC functions
*
* - isUnrestricted (getter)
* - multFracCeiling (library function)
* - isRegistered(addr) (getter)
*/
/**
* Return true iff the assignments are closed and there are no restricted
* tokens left
*/
function isUnrestricted() constant returns (bool) {
return (assignmentsClosed && totalRestrictedTokens == 0);
}
/**
* Return the ceiling of (x*a)/b
*
* Edge cases:
* a = 0: return 0
* b = 0, a != 0: error (solidity throws on division by 0)
*/
function multFracCeiling(uint x, uint a, uint b) returns (uint) {
// Catch the case a = 0
if (a == 0) { return 0; }
// Rounding up is the same as adding 1-epsilon and rounding down.
// 1-epsilon is modeled as (b-1)/b below.
return (x * a + (b - 1)) / b;
}
/**
* Return true iff the address has tokens assigned (resp. restricted tokens)
*/
function isRegistered(address addr, bool restricted) constant returns (bool) {
if (restricted) {
return (restrictions[addr] > 0);
} else {
return (tokens[addr] > 0);
}
}
/**
* INTERNAL functions
*
* - assign
* - closeAssignments
* - unrestrict
*/
/**
* Assign (un)restricted tokens to given address
*/
function assign(address addr, uint tokenAmount, bool restricted) internal {
// Throw if assignments have been closed
if (assignmentsClosed) { throw; }
// Assign tokens
tokens[addr] += tokenAmount;
// Record restrictions and update total counters
if (restricted) {
totalRestrictedTokens += tokenAmount;
totalRestrictedAssignments += 1;
restrictions[addr] += tokenAmount;
} else {
totalUnrestrictedTokens += tokenAmount;
totalUnrestrictedAssignments += 1;
}
}
/**
* Close future assignments.
*
* This is irreversible and closes all future assignments.
* The function can only be called once.
*
* A call triggers the calculation of what fraction of restricted tokens
* should be burned by subsequent calls to the unrestrict() function.
* The result of this calculation is a multiplication factor whose nominator
* and denominator are stored in the contract variables burnMultNom,
* burnMultDen.
*/
function closeAssignmentsIfOpen() internal {
// Return if assignments are not open
if (assignmentsClosed) { return; }
// Set the state to "closed"
assignmentsClosed = true;
/*
* Calculate the total number of tokens that should remain after
* conversion. This is based on the total number of unrestricted tokens
* assigned so far and the pre-configured share that the remaining
* formerly restricted tokens should have.
*/
uint totalTokensTarget = (totalUnrestrictedTokens * 100) /
(100 - restrictedShare);
// The total number of tokens in existence now.
uint totalTokensExisting = totalRestrictedTokens + totalUnrestrictedTokens;
/*
* The total number of tokens that need to be burned to bring the existing
* number down to the target number. If the existing number is lower than
* the target then we won't burn anything.
*/
uint totalBurn = 0;
if (totalTokensExisting > totalTokensTarget) {
totalBurn = totalTokensExisting - totalTokensTarget;
}
// The fraction of restricted tokens to be burned (by nominator and
// denominator).
burnMultNom = totalBurn;
burnMultDen = totalRestrictedTokens;
/*
* For verifying the correctness of the above calculation it may help to
* note the following.
* Given 0 <= restrictedShare < 100, we have:
* - totalTokensTarget >= totalUnrestrictedTokens
* - totalTokensExisting <= totalRestrictedTokens + totalTokensTarget
* - totalBurn <= totalRestrictedTokens
* - burnMultNom <= burnMultDen
* Also note that burnMultDen = 0 means totalRestrictedTokens = 0, in which
* burnMultNom = 0 as well.
*/
}
/**
* Unrestrict (convert) all restricted tokens assigned to the given address
*
* This function can only be called after assignments have been closed via
* closeAssignments().
* The return value is the number of restricted tokens that were burned in
* the conversion.
*/
function unrestrict(address addr) internal returns (uint) {
// Throw is assignments are not yet closed
if (!assignmentsClosed) { throw; }
// The balance of restricted tokens for the given address
uint restrictionsForAddr = restrictions[addr];
// Throw if there are none
if (restrictionsForAddr == 0) { throw; }
// Apply the burn multiplier to the balance of restricted tokens
// The result is the ceiling of the value:
// (restrictionForAddr * burnMultNom) / burnMultDen
uint burn = multFracCeiling(restrictionsForAddr, burnMultNom, burnMultDen);
// Remove the tokens to be burned from the address's balance
tokens[addr] -= burn;
// Delete record of restrictions
delete restrictions[addr];
// Update the counters for total (un)restricted tokens
totalRestrictedTokens -= restrictionsForAddr;
totalUnrestrictedTokens += restrictionsForAddr - burn;
return burn;
}
}
// import "Phased.sol";
/*
* title: Contract that advances through multiple configurable phases over time
* author: Timo Hanke
*
* Phases are defined by their transition times. The moment one phase ends the
* next one starts. Each time belongs to exactly one phase.
*
* The contract allows a limited set of changes to be applied to the phase
* transitions while the contract is active. As a matter of principle, changes
* are prohibited from effecting the past. They may only ever affect future
* phase transitions.
*
* The permitted changes are:
* - add a new phase after the last one
* - end the current phase right now and transition to the next phase
* immediately
* - delay the start of a future phase (thereby pushing out all subsequent
* phases by an equal amount of time)
* - define a maximum delay for a specified phase
*/
contract Phased {
/**
* Array of transition times defining the phases
*
* phaseEndTime[i] is the time when phase i has just ended.
* Phase i is defined as the following time interval:
* [ phaseEndTime[i-1], * phaseEndTime[i] )
*/
uint[] public phaseEndTime;
/**
* Number of phase transitions N = phaseEndTime.length
*
* There are N+1 phases, numbered 0,..,N.
* The first phase has no start and the last phase has no end.
*/
uint public N;
/**
* Maximum delay for phase transitions
*
* maxDelay[i] is the maximum amount of time by which the transition
* phaseEndTime[i] can be delayed.
*/
mapping(uint => uint) public maxDelay;
/*
* The contract has no constructor.
* The contract initialized itself with no phase transitions (N = 0) and one
* phase (N+1=1).
*
* There are two PUBLIC functions (getters):
* - getPhaseAtTime
* - isPhase
* - getPhaseStartTime
*
* Note that both functions are guaranteed to return the same value when
* called twice with the same argument (but at different times).
*/
/**
* Return the number of the phase to which the given time belongs.
*
* Return value i means phaseEndTime[i-1] <= time < phaseEndTime[i].
* The given time must not be in the future (because future phase numbers may
* still be subject to change).
*/
function getPhaseAtTime(uint time) constant returns (uint n) {
// Throw if time is in the future
if (time > now) { throw; }
// Loop until we have found the "active" phase
while (n < N && phaseEndTime[n] <= time) {
n++;
}
}
/**
* Return true if the given time belongs to the given phase.
*
* Returns the logical equivalent of the expression
* (phaseEndTime[i-1] <= time < phaseEndTime[i]).
*
* The given time must not be in the future (because future phase numbers may
* still be subject to change).
*/
function isPhase(uint time, uint n) constant returns (bool) {
// Throw if time is in the future
if (time > now) { throw; }
// Throw if index is out-of-range
if (n >= N) { throw; }
// Condition 1
if (n > 0 && phaseEndTime[n-1] > time) { return false; }
// Condition 2
if (n < N && time >= phaseEndTime[n]) { return false; }
return true;
}
/**
* Return the start time of the given phase.
*
* This function is provided for convenience.
* The given phase number must not be 0, as the first phase has no start time.
* If calling for a future phase number the caller must be aware that future
* phase times can be subject to change.
*/
function getPhaseStartTime(uint n) constant returns (uint) {
// Throw if phase is the first phase
if (n == 0) { throw; }
return phaseEndTime[n-1];
}
/*
* There are 4 INTERNAL functions:
* 1. addPhase
* 2. setMaxDelay
* 3. delayPhaseEndBy
* 4. endCurrentPhaseIn
*
* This contract does not implement access control to these function, so
* they are made internal.
*/
/**
* 1. Add a phase after the last phase.
*
* The argument is the new endTime of the phase currently known as the last
* phase, or, in other words the start time of the newly introduced phase.
* All calls to addPhase() MUST be with strictly increasing time arguments.
* It is not allowed to add a phase transition that lies in the past relative
* to the current block time.
*/
function addPhase(uint time) internal {
// Throw if new transition time is not strictly increasing
if (N > 0 && time <= phaseEndTime[N-1]) { throw; }
// Throw if new transition time is not in the future
if (time <= now) { throw; }
// Append new transition time to array
phaseEndTime.push(time);
N++;
}
/**
* 2. Define a limit on the amount of time by which the given transition (i)
* can be delayed.
*
* By default, transitions can not be delayed (limit = 0).
*/
function setMaxDelay(uint i, uint timeDelta) internal {
// Throw if index is out-of-range
if (i >= N) { throw; }
maxDelay[i] = timeDelta;
}
/**
* 3. Delay the end of the given phase (n) by the given time delta.
*
* The given phase must not have ended.
*
* This function can be called multiple times for the same phase.
* The defined maximum delay will be enforced across multiple calls.
*/
function delayPhaseEndBy(uint n, uint timeDelta) internal {
// Throw if index is out of range
if (n >= N) { throw; }
// Throw if phase has already ended
if (now >= phaseEndTime[n]) { throw; }
// Throw if the requested delay is higher than the defined maximum for the
// transition
if (timeDelta > maxDelay[n]) { throw; }
// Subtract from the current max delay, so maxDelay is honored across
// multiple calls
maxDelay[n] -= timeDelta;
// Push out all subsequent transitions by the same amount
for (uint i = n; i < N; i++) {
phaseEndTime[i] += timeDelta;
}
}
/**
* 4. End the current phase early.
*
* The current phase must not be the last phase, as the last phase has no end.
* The current phase will end at time now plus the given time delta.
*
* The minimal allowed time delta is 1. This is avoid a race condition for
* other transactions that are processed in the same block.
* Setting phaseEndTime[n] to now would push all later transactions from the
* same block into the next phase.
* If the specified timeDelta is 0 the function gracefully bumps it up to 1.
*/
function endCurrentPhaseIn(uint timeDelta) internal {
// Get the current phase number
uint n = getPhaseAtTime(now);
// Throw if we are in the last phase
if (n >= N) { throw; }
// Set timeDelta to the minimal allowed value
if (timeDelta == 0) {
timeDelta = 1;
}
// The new phase end should be earlier than the currently defined phase
// end, otherwise we don't change it.
if (now + timeDelta < phaseEndTime[n]) {
phaseEndTime[n] = now + timeDelta;
}
}
}
// import "StepFunction.sol";
/*
* title: A configurable step function
* author: Timo Hanke
*
* The contract implements a step function going down from an initialValue to 0
* in a number of steps (nSteps).
* The steps are distributed equally over a given time (phaseLength).
* Having n steps means that the time phaseLength is divided into n+1
* sub-intervalls of equal length during each of which the function value is
* constant.
*/
contract StepFunction {
uint public phaseLength;
uint public nSteps;
uint public step;
function StepFunction(uint _phaseLength, uint _initialValue, uint _nSteps) {
// Throw if phaseLength does not leave enough room for number of steps
if (_nSteps > _phaseLength) { throw; }
// The reduction in value per step
step = _initialValue / _nSteps;
// Throw if _initialValue was not divisible by _nSteps
if ( step * _nSteps != _initialValue) { throw; }
phaseLength = _phaseLength;
nSteps = _nSteps;
}
/*
* Note the following edge cases.
* initialValue = 0: is valid and will create the constant zero function
* nSteps = 0: is valid and will create the constant zero function (only 1
* sub-interval)
* phaseLength < nSteps: is valid, but unlikely to be intended (so the
* constructor throws)
*/
/**
* Evaluate the step function at a given time
*
* elapsedTime MUST be in the intervall [0,phaseLength)
* The return value is between initialValue and 0, never negative.
*/
function getStepFunction(uint elapsedTime) constant returns (uint) {
// Throw is elapsedTime is out-of-range
if (elapsedTime >= phaseLength) { throw; }
// The function value will bel calculated from the end value backwards.
// Hence we need the time left, which will lie in the intervall
// [0,phaseLength)
uint timeLeft = phaseLength - elapsedTime - 1;
// Calculate the number of steps away from reaching end value
// When verifying the forumla below it may help to note:
// at elapsedTime = 0 stepsLeft evaluates to nSteps,
// at elapsedTime = -1 stepsLeft would evaluate to nSteps + 1.
uint stepsLeft = ((nSteps + 1) * timeLeft) / phaseLength;
// Apply the step function
return stepsLeft * step;
}
}
// import "Targets.sol";
/*
* title: Contract implementing counters with configurable targets
* author: Timo Hanke
*
* There is an arbitrary number of counters. Each counter is identified by its
* counter id, a uint. Counters can never decrease.
*
* The contract has no constructor. The target values are set and re-set via
* setTarget().
*/
contract Targets {
// Mapping from counter id to counter value
mapping(uint => uint) public counter;
// Mapping from counter id to target value
mapping(uint => uint) public target;
// A public getter that returns whether the target was reached
function targetReached(uint id) constant returns (bool) {
return (counter[id] >= target[id]);
}
/*
* Modifying counter or target are internal functions.
*/
// (Re-)set the target
function setTarget(uint id, uint _target) internal {
target[id] = _target;
}
// Add to the counter
// The function returns whether this current addition makes the counter reach
// or cross its target value
function addTowardsTarget(uint id, uint amount)
internal
returns (bool firstReached)
{
firstReached = (counter[id] < target[id]) &&
(counter[id] + amount >= target[id]);
counter[id] += amount;
}
}
// import "Parameters.sol";
/**
* title: Configuration parameters for the FDC
* author: Timo Hanke
*/
contract Parameters {
/*
* Time Constants
*
* Phases are, in this order:
* earlyContribution (defined by end time)
* pause
* donation round0 (defined by start and end time)
* pause
* donation round1 (defined by start and end time)
* pause
* finalization (defined by start time, ends manually)
* done
*/
// The start of round 0 is set to 2017-01-17 19:00 of timezone Europe/Zurich
uint public constant round0StartTime = 1484676000;
// The start of round 1 is set to 2017-05-17 19:00 of timezone Europe/Zurich
// TZ="Europe/Zurich" date -d "2017-05-17 19:00" "+%s"
uint public constant round1StartTime = 1495040400;
// Transition times that are defined by duration
uint public constant round0EndTime = round0StartTime + 6 weeks;
uint public constant round1EndTime = round1StartTime + 6 weeks;
uint public constant finalizeStartTime = round1EndTime + 1 weeks;
// The finalization phase has a dummy end time because it is ended manually
uint public constant finalizeEndTime = finalizeStartTime + 1000 years;
// The maximum time by which donation round 1 can be delayed from the start
// time defined above
uint public constant maxRoundDelay = 270 days;
// The time for which donation rounds remain open after they reach their
// respective targets
uint public constant gracePeriodAfterRound0Target = 1 days;
uint public constant gracePeriodAfterRound1Target = 0 days;
/*
* Token issuance
*
* The following configuration parameters completely govern all aspects of the
* token issuance.
*/
// Tokens assigned for the equivalent of 1 CHF in donations
uint public constant tokensPerCHF = 10;
// Minimal donation amount for a single on-chain donation
uint public constant minDonation = 1 ether;
// Bonus in percent added to donations throughout donation round 0
uint public constant round0Bonus = 200;
// Bonus in percent added to donations at beginning of donation round 1
uint public constant round1InitialBonus = 25;
// Number of down-steps for the bonus during donation round 1
uint public constant round1BonusSteps = 5;
// The CHF targets for each of the donation rounds, measured in cents of CHF
uint public constant millionInCents = 10**6 * 100;
uint public constant round0Target = 1 * millionInCents;
uint public constant round1Target = 20 * millionInCents;
// Share of tokens eventually assigned to DFINITY Stiftung and early
// contributors in % of all tokens eventually in existence
uint public constant earlyContribShare = 22;
}
// FDC.sol
contract FDC is TokenTracker, Phased, StepFunction, Targets, Parameters {
// An identifying string, set by the constructor
string public name;
/*
* Phases
*
* The FDC over its lifetime runs through a number of phases. These phases are
* tracked by the base contract Phased.
*
* The FDC maps the chronologically defined phase numbers to semantically
* defined states.
*/
// The FDC states
enum state {
pause, // Pause without any activity
earlyContrib, // Registration of DFINITY Stiftung/early contributions
round0, // Donation round 0
round1, // Donation round 1
offChainReg, // Grace period for registration of off-chain donations
finalization, // Adjustment of DFINITY Stiftung/early contribution tokens
// down to their share
done // Read-only phase
}
// Mapping from phase number (from the base contract Phased) to FDC state
mapping(uint => state) stateOfPhase;
/*
* Tokens
*
* The FDC uses base contract TokenTracker to:
* - track token assignments for
* - donors (unrestricted tokens)
* - DFINITY Stiftung/early contributors (restricted tokens)
* - convert DFINITY Stiftung/early contributor tokens down to their share
*
* The FDC uses the base contract Targets to:
* - track the targets measured in CHF for each donation round
*
* The FDC itself:
* - tracks the memos of off-chain donations (and prevents duplicates)
* - tracks donor and early contributor addresses in two lists
*/
// Mapping to store memos that have been used
mapping(bytes32 => bool) memoUsed;
// List of registered addresses (each address will appear in one)
address[] public donorList;
address[] public earlyContribList;
/*
* Exchange rate and ether handling
*
* The FDC keeps track of:
* - the exchange rate between ether and Swiss francs
* - the total and per address ether donations
*/
// Exchange rate between ether and Swiss francs
uint public weiPerCHF;
// Total number of Wei donated on-chain so far
uint public totalWeiDonated;
// Mapping from address to total number of Wei donated for the address
mapping(address => uint) public weiDonated;
/*
* Access control
*
* The following three addresses have access to restricted functions of the
* FDC and to the donated funds.
*/
// Wallet address to which on-chain donations are being forwarded
address public foundationWallet;
// Address that is allowed to register DFINITY Stiftung/early contributions
// and off-chain donations and to delay donation round 1
address public registrarAuth;
// Address that is allowed to update the exchange rate
address public exchangeRateAuth;
// Address that is allowed to update the other authenticated addresses
address public masterAuth;
/*
* Global variables
*/
// The phase numbers of the donation phases (set by the constructor,
// thereafter constant)
uint phaseOfRound0;
uint phaseOfRound1;
/*
* Events
*
* - DonationReceipt: logs an on-chain or off-chain donation
* - EarlyContribReceipt: logs the registration of early contribution
* - BurnReceipt: logs the burning of token during finalization
*/
event DonationReceipt (address indexed addr, // DFN address of donor
string indexed currency, // donation currency
uint indexed bonusMultiplierApplied, // depends stage
uint timestamp, // time occurred
uint tokenAmount, // DFN to b recommended
bytes32 memo); // unique note e.g TxID
event EarlyContribReceipt (address indexed addr, // DFN address of donor
uint tokenAmount, // *restricted* tokens
bytes32 memo); // arbitrary note
event BurnReceipt (address indexed addr, // DFN address adjusted
uint tokenAmountBurned); // DFN deleted by adj.
/**
* Constructor
*
* The constructor defines
* - the privileged addresses for access control
* - the phases in base contract Phased
* - the mapping between phase numbers and states
* - the targets in base contract Targets
* - the share for early contributors in base contract TokenTracker
* - the step function for the bonus calculation in donation round 1
*
* All configuration parameters are taken from base contract Parameters.
*/
function FDC(address _masterAuth, string _name)
TokenTracker(earlyContribShare)
StepFunction(round1EndTime-round1StartTime, round1InitialBonus,
round1BonusSteps)
{
/*
* Set identifying string
*/
name = _name;
/*
* Set privileged addresses for access control
*/
foundationWallet = _masterAuth;
masterAuth = _masterAuth;
exchangeRateAuth = _masterAuth;
registrarAuth = _masterAuth;
/*
* Initialize base contract Phased
*
* |------------------------- Phase number (0-7)
* | |-------------------- State name
* | | |---- Transition number (0-6)
* V V V
*/
stateOfPhase[0] = state.earlyContrib;
addPhase(round0StartTime); // 0
stateOfPhase[1] = state.round0;
addPhase(round0EndTime); // 1
stateOfPhase[2] = state.offChainReg;
addPhase(round1StartTime); // 2
stateOfPhase[3] = state.round1;
addPhase(round1EndTime); // 3
stateOfPhase[4] = state.offChainReg;
addPhase(finalizeStartTime); // 4
stateOfPhase[5] = state.finalization;
addPhase(finalizeEndTime); // 5
stateOfPhase[6] = state.done;
// Let the other functions know what phase numbers the donation rounds were
// assigned to
phaseOfRound0 = 1;
phaseOfRound1 = 3;
// Maximum delay for start of donation rounds
setMaxDelay(phaseOfRound0 - 1, maxRoundDelay);
setMaxDelay(phaseOfRound1 - 1, maxRoundDelay);
/*
* Initialize base contract Targets
*/
setTarget(phaseOfRound0, round0Target);
setTarget(phaseOfRound1, round1Target);
}
/*
* PUBLIC functions
*
* Un-authenticated:
* - getState
* - getMultiplierAtTime
* - donateAsWithChecksum
* - finalize
* - empty
* - getStatus
*
* Authenticated:
* - registerEarlyContrib
* - registerOffChainDonation
* - setExchangeRate
* - delayRound1
* - setFoundationWallet
* - setRegistrarAuth
* - setExchangeRateAuth
* - setAdminAuth
*/
/**
* Get current state at the current block time
*/
function getState() constant returns (state) {
return stateOfPhase[getPhaseAtTime(now)];
}
/**
* Return the bonus multiplier at a given time
*
* The given time must
* - lie in one of the donation rounds,
* - not lie in the future.
* Otherwise there is no valid multiplier.
*/
function getMultiplierAtTime(uint time) constant returns (uint) {
// Get phase number (will throw if time lies in the future)
uint n = getPhaseAtTime(time);
// If time lies in donation round 0 we return the constant multiplier
if (stateOfPhase[n] == state.round0) {
return 100 + round0Bonus;
}
// If time lies in donation round 1 we return the step function
if (stateOfPhase[n] == state.round1) {
return 100 + getStepFunction(time - getPhaseStartTime(n));
}
// Throw outside of donation rounds
throw;
}
/**
* Send donation in the name a the given address with checksum
*
* The second argument is a checksum which must equal the first 4 bytes of the
* SHA-256 digest of the byte representation of the address.
*/
function donateAsWithChecksum(address addr, bytes4 checksum)
payable
returns (bool)
{
// Calculate SHA-256 digest of the address
bytes32 hash = sha256(addr);
// Throw is the checksum does not match the first 4 bytes
if (bytes4(hash) != checksum) { throw ; }
// Call un-checksummed donate function
return donateAs(addr);
}
/**
* Finalize the balance for the given address
*
* This function triggers the conversion (and burn) of the restricted tokens
* that are assigned to the given address.
*
* This function is only available during the finalization phase. It manages
* the calls to closeAssignments() and unrestrict() of TokenTracker.
*/
function finalize(address addr) {
// Throw if we are not in the finalization phase
if (getState() != state.finalization) { throw; }
// Close down further assignments in TokenTracker
closeAssignmentsIfOpen();
// Burn tokens
uint tokensBurned = unrestrict(addr);
// Issue burn receipt
BurnReceipt(addr, tokensBurned);
// If no restricted tokens left
if (isUnrestricted()) {
// then end the finalization phase immediately
endCurrentPhaseIn(0);
}
}
/**
* Send any remaining balance to the foundation wallet
*/
function empty() returns (bool) {
return foundationWallet.call.value(this.balance)();
}
/**
* Get status information from the FDC
*
* This function returns a mix of
* - global status of the FDC
* - global status of the FDC specific for one of the two donation rounds
* - status related to a specific token address (DFINITY address)
* - status (balance) of an external Ethereum account
*
* Arguments are:
* - donationRound: donation round to query (0 or 1)
* - dfnAddr: token address to query
* - fwdAddr: external Ethereum address to query
*/
function getStatus(uint donationRound, address dfnAddr, address fwdAddr)
public constant
returns (
state currentState, // current state (an enum)
uint fxRate, // exchange rate of CHF -> ETH (Wei/CHF)
uint currentMultiplier, // current bonus multiplier (0 if invalid)
uint donationCount, // total individual donations made (a count)
uint totalTokenAmount, // total DFN planned allocated to donors
uint startTime, // expected start time of specified donation round
uint endTime, // expected end time of specified donation round
bool isTargetReached, // whether round target has been reached
uint chfCentsDonated, // total value donated in specified round as CHF
uint tokenAmount, // total DFN planned allocted to donor (user)
uint fwdBalance, // total ETH (in Wei) waiting in fowarding address
uint donated) // total ETH (in Wei) donated by DFN address
{
// The global status
currentState = getState();
if (currentState == state.round0 || currentState == state.round1) {
currentMultiplier = getMultiplierAtTime(now);
}
fxRate = weiPerCHF;
donationCount = totalUnrestrictedAssignments;
totalTokenAmount = totalUnrestrictedTokens;
// The round specific status
if (donationRound == 0) {
startTime = getPhaseStartTime(phaseOfRound0);
endTime = getPhaseStartTime(phaseOfRound0 + 1);
isTargetReached = targetReached(phaseOfRound0);
chfCentsDonated = counter[phaseOfRound0];
} else {
startTime = getPhaseStartTime(phaseOfRound1);
endTime = getPhaseStartTime(phaseOfRound1 + 1);
isTargetReached = targetReached(phaseOfRound1);
chfCentsDonated = counter[phaseOfRound1];
}
// The status specific to the DFN address
tokenAmount = tokens[dfnAddr];
donated = weiDonated[dfnAddr];
// The status specific to the Ethereum address
fwdBalance = fwdAddr.balance;
}
/**
* Set the exchange rate between ether and Swiss francs in Wei per CHF
*
* Must be called from exchangeRateAuth.
*/
function setWeiPerCHF(uint weis) {
// Require permission
if (msg.sender != exchangeRateAuth) { throw; }
// Set the global state variable for exchange rate
weiPerCHF = weis;
}
/**
* Register early contribution in the name of the given address
*
* Must be called from registrarAuth.
*
* Arguments are:
* - addr: address to the tokens are assigned
* - tokenAmount: number of restricted tokens to assign
* - memo: optional dynamic bytes of data to appear in the receipt
*/
function registerEarlyContrib(address addr, uint tokenAmount, bytes32 memo) {
// Require permission
if (msg.sender != registrarAuth) { throw; }
// Reject registrations outside the early contribution phase
if (getState() != state.earlyContrib) { throw; }
// Add address to list if new
if (!isRegistered(addr, true)) {
earlyContribList.push(addr);
}
// Assign restricted tokens in TokenTracker
assign(addr, tokenAmount, true);
// Issue early contribution receipt
EarlyContribReceipt(addr, tokenAmount, memo);
}
/**
* Register off-chain donation in the name of the given address
*
* Must be called from registrarAuth.
*
* Arguments are:
* - addr: address to the tokens are assigned
* - timestamp: time when the donation came in (determines round and bonus)
* - chfCents: value of the donation in cents of Swiss francs
* - currency: the original currency of the donation (three letter string)
* - memo: optional bytes of data to appear in the receipt
*
* The timestamp must not be in the future. This is because the timestamp
* defines the donation round and the multiplier and future phase times are
* still subject to change.
*
* If called during a donation round then the timestamp must lie in the same
* phase and if called during the extended period for off-chain donations then
* the timestamp must lie in the immediately preceding donation round.
*/
function registerOffChainDonation(address addr, uint timestamp, uint chfCents,
string currency, bytes32 memo)
{
// Require permission
if (msg.sender != registrarAuth) { throw; }
// The current phase number and state corresponding state
uint currentPhase = getPhaseAtTime(now);
state currentState = stateOfPhase[currentPhase];
// Reject registrations outside the two donation rounds (incl. their
// extended registration periods for off-chain donations)
if (currentState != state.round0 && currentState != state.round1 &&
currentState != state.offChainReg) {
throw;
}
// Throw if timestamp is in the future
if (timestamp > now) { throw; }
// Phase number and corresponding state of the timestamp
uint timestampPhase = getPhaseAtTime(timestamp);
state timestampState = stateOfPhase[timestampPhase];
// Throw if called during a donation round and the timestamp does not match
// that phase.
if ((currentState == state.round0 || currentState == state.round1) &&
(timestampState != currentState)) {
throw;
}
// Throw if called during the extended period for off-chain donations and
// the timestamp does not lie in the immediately preceding donation phase.
if (currentState == state.offChainReg && timestampPhase != currentPhase-1) {
throw;
}
// Throw if the memo is duplicated
if (memoUsed[memo]) {
throw;
}
// Set the memo item to true
memoUsed[memo] = true;
// Do the book-keeping
bookDonation(addr, timestamp, chfCents, currency, memo);
}
/**
* Delay a donation round
*
* Must be called from the address registrarAuth.
*
* This function delays the start of donation round 1 by the given time delta
* unless the time delta is bigger than the configured maximum delay.
*/
function delayDonPhase(uint donPhase, uint timedelta) {
// Require permission
if (msg.sender != registrarAuth) { throw; }
// Pass the call on to base contract Phased
// Delaying the start of a donation round is the same as delaying the end
// of the preceding phase
if (donPhase == 0) {
delayPhaseEndBy(phaseOfRound0 - 1, timedelta);
} else if (donPhase == 1) {
delayPhaseEndBy(phaseOfRound1 - 1, timedelta);
}
}
/**
* Set the forwarding address for donated ether
*
* Must be called from the address masterAuth before donation round 0 starts.
*/
function setFoundationWallet(address newAddr) {
// Require permission
if (msg.sender != masterAuth) { throw; }
// Require phase before round 0
if (getPhaseAtTime(now) >= phaseOfRound0) { throw; }
foundationWallet = newAddr;
}
/**
* Set new authenticated address for setting exchange rate
*
* Must be called from the address masterAuth.
*/
function setExchangeRateAuth(address newAuth) {
// Require permission
if (msg.sender != masterAuth) { throw; }
exchangeRateAuth = newAuth;
}
/**
* Set new authenticated address for registrations
*
* Must be called from the address masterAuth.
*/
function setRegistrarAuth(address newAuth) {
// Require permission
if (msg.sender != masterAuth) { throw; }
registrarAuth = newAuth;
}
/**
* Set new authenticated address for admin
*
* Must be called from the address masterAuth.
*/
function setMasterAuth(address newAuth) {
// Require permission
if (msg.sender != masterAuth) { throw; }
masterAuth = newAuth;
}
/*
* PRIVATE functions
*
* - donateAs
* - bookDonation
*/
/**
* Process on-chain donation in the name of the given address
*
* This function is private because it shall only be called through its
* wrapper donateAsWithChecksum.
*/
function donateAs(address addr) private returns (bool) {
// The current state
state st = getState();
// Throw if current state is not a donation round
if (st != state.round0 && st != state.round1) { throw; }
// Throw if donation amount is below minimum
if (msg.value < minDonation) { throw; }
// Throw if the exchange rate is not yet defined
if (weiPerCHF == 0) { throw; }
// Update counters for ether donations
totalWeiDonated += msg.value;
weiDonated[addr] += msg.value;
// Convert ether to Swiss francs
uint chfCents = (msg.value * 100) / weiPerCHF;
// Do the book-keeping
bookDonation(addr, now, chfCents, "ETH", "");
// Forward balance to the foundation wallet
return foundationWallet.call.value(this.balance)();
}
/**
* Put an accepted donation in the books.
*
* This function
* - cannot throw as all checks have been done before,
* - is agnostic to the source of the donation (on-chain or off-chain)
* - is agnostic to the currency
* (the currency argument is simply passed through to the DonationReceipt)
*
*/
function bookDonation(address addr, uint timestamp, uint chfCents,
string currency, bytes32 memo) private
{
// The current phase
uint phase = getPhaseAtTime(timestamp);
// Add amount to the counter of the current phase
bool targetReached = addTowardsTarget(phase, chfCents);
// If the target was crossed then start the grace period
if (targetReached && phase == getPhaseAtTime(now)) {
if (phase == phaseOfRound0) {
endCurrentPhaseIn(gracePeriodAfterRound0Target);
} else if (phase == phaseOfRound1) {
endCurrentPhaseIn(gracePeriodAfterRound1Target);
}
}
// Bonus multiplier that was valid at the given time
uint bonusMultiplier = getMultiplierAtTime(timestamp);
// Apply bonus to amount in Swiss francs
chfCents = (chfCents * bonusMultiplier) / 100;
// Convert Swiss francs to amount of tokens
uint tokenAmount = (chfCents * tokensPerCHF) / 100;
// Add address to list if new
if (!isRegistered(addr, false)) {
donorList.push(addr);
}
// Assign unrestricted tokens in TokenTracker
assign(addr,tokenAmount,false);
// Issue donation receipt
DonationReceipt(addr, currency, bonusMultiplier, timestamp, tokenAmount,
memo);
}
} | Convert Swiss francs to amount of tokens | uint tokenAmount = (chfCents * tokensPerCHF) / 100;
| 1,050,767 | [
1,
2723,
5434,
1054,
284,
2450,
2143,
358,
3844,
434,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1147,
6275,
273,
261,
343,
74,
39,
4877,
380,
2430,
2173,
1792,
42,
13,
342,
2130,
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
] |
/**
*Submitted for verification at Etherscan.io on 2020-11-17
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
}
abstract contract NKTContract {
function balanceOf(address account) external view virtual returns (uint256);
function transfer(address recipient, uint256 amount) external virtual returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external virtual returns (bool);
}
abstract contract NKTStoreContract {
function getStoreBalance() external virtual returns (uint256);
function giveReward(address recipient, uint256 amount) external virtual returns (bool);
function withdrawAll(address recipient) external virtual returns (bool);
}
contract NKTStaker is Ownable {
using SafeMath for uint256;
NKTContract private _mainTokenContract; // main token contract
NKTStoreContract private _storeWalletContract; // store wallet contract
mapping (address => uint256) private _stakedBalances; // map for stacked balances
mapping (address => uint256) private _rewards; // map for rewards
address private _devWallet; // dev wallet address
address[] private _stakers; // staker's array
uint256 private _totalStackedAmount = 0; // total stacked amount
uint256 private _minStakeAmount = 20e18; // min stackable amount
uint256 private _rewardPeriod = 3600; // seconds of a day
uint256 private _rewardPortion = 100; // reward portion = 1/100
uint256 private _rewardFee = 98; // reward fee 98%, rest for dev 2%
uint256 private _taxFee = 2; // tax fee for transaction
uint256 private _minRewardPeriod = 3600; // min reward period = 1 hour (3600s)
uint256 private _lastTimestamp; // last timestamp that distributed rewards
// Events
event Staked(address staker, uint256 amount);
event Unstaked(address staker, uint256 amount);
event Claim(address staker, uint256 amount);
constructor (NKTContract mainTokenContract, address devWallet) public {
_mainTokenContract = mainTokenContract;
_devWallet = devWallet;
}
function stake(uint256 amount) external {
require(
amount >= _minStakeAmount,
"Too small amount"
);
require(
_mainTokenContract.transferFrom(
_msgSender(),
address(this),
amount
),
"Stake failed"
);
uint256 taxAmount = amount.mul(_taxFee).div(100);
uint256 stackedAmount = amount.sub(taxAmount);
if(_stakers.length == 0)
_lastTimestamp = uint256(now);
if(_stakedBalances[_msgSender()] == 0)
_stakers.push(_msgSender());
_stakedBalances[_msgSender()] = _stakedBalances[_msgSender()].add(stackedAmount);
_totalStackedAmount = _totalStackedAmount.add(stackedAmount);
emit Staked(_msgSender(), stackedAmount);
}
function unstake(uint256 amount) external {
require(
_stakedBalances[_msgSender()] >= amount,
"Unstake amount exceededs the staked amount."
);
require(
_mainTokenContract.transfer(
_msgSender(),
amount
),
"Unstake failed"
);
_stakedBalances[_msgSender()] = _stakedBalances[_msgSender()].sub(amount);
_totalStackedAmount = _totalStackedAmount.sub(amount);
if(_stakedBalances[_msgSender()] == 0) {
for(uint i=0; i<_stakers.length; i++) {
if(_stakers[i] == _msgSender()) {
_stakers[i] = _stakers[_stakers.length-1];
_stakers.pop();
break;
}
}
}
emit Unstaked(_msgSender(), amount);
uint256 rewardsAmount = _rewards[_msgSender()];
if(rewardsAmount > 0) {
require(
_storeWalletContract.giveReward(_msgSender(), rewardsAmount),
"Claim failed."
);
_rewards[_msgSender()] = 0;
emit Claim(_msgSender(), rewardsAmount);
}
}
function claim(uint256 amount) external {
require(
_rewards[_msgSender()] >= amount,
"Claim amount exceededs the pendnig rewards."
);
require(
_storeWalletContract.giveReward(_msgSender(), amount),
"Claim failed."
);
_rewards[_msgSender()] = _rewards[_msgSender()].sub(amount);
emit Claim(_msgSender(), amount);
}
function endStake() external {
uint256 rewardsAmount = _rewards[_msgSender()];
if(rewardsAmount > 0) {
require(
_storeWalletContract.giveReward(_msgSender(), rewardsAmount),
"Claim failed."
);
_rewards[_msgSender()] = 0;
emit Claim(_msgSender(), rewardsAmount);
}
uint256 unstakeAmount = _stakedBalances[_msgSender()];
if(unstakeAmount > 0) {
require(
_mainTokenContract.transfer(
_msgSender(),
unstakeAmount
),
"Unstake failed"
);
_stakedBalances[_msgSender()] = 0;
_totalStackedAmount = _totalStackedAmount.sub(unstakeAmount);
for(uint i=0; i<_stakers.length; i++) {
if(_stakers[i] == _msgSender()) {
_stakers[i] = _stakers[_stakers.length-1];
_stakers.pop();
break;
}
}
emit Unstaked(_msgSender(), unstakeAmount);
}
}
function calcRewards() external {
uint256 currentTimestamp = uint256(now);
uint256 diff = currentTimestamp.sub(_lastTimestamp);
if(diff >= _rewardPeriod) {
uint256 rewardDays = diff.div(_rewardPeriod);
uint256 offsetTimestamp = diff.sub(_rewardPeriod.mul(rewardDays));
uint256 _storeBalance = _storeWalletContract.getStoreBalance();
for(uint j=0; j<rewardDays; j++) {
uint256 _totalRewardsAmount = _storeBalance.div(_rewardPortion);
if(_totalRewardsAmount > 0) {
uint256 _rewardForStaker = _totalRewardsAmount.mul(_rewardFee).div(100);
uint256 _rewardForDev = _totalRewardsAmount.sub(_rewardForStaker);
for(uint i=0; i<_stakers.length; i++) {
if(_stakers[i] != address(0)) {
_rewards[_stakers[i]] = _rewards[_stakers[i]].add(_stakedBalances[_stakers[i]].mul(_rewardForStaker).div(_totalStackedAmount));
}
}
if(_rewardForDev > 0)
_storeWalletContract.giveReward(_devWallet, _rewardForDev);
}
_storeBalance = _storeBalance.sub(_totalRewardsAmount);
}
_lastTimestamp = currentTimestamp.sub(offsetTimestamp);
}
}
function withdrawAllFromStore(address recipient) external onlyOwner returns (bool) {
require(
recipient != address(0) && recipient != address(this),
"Should be valid address."
);
_storeWalletContract.withdrawAll(recipient);
}
/**
* Get store wallet
*/
function getStoreWalletContract() external view returns (address) {
return address(_storeWalletContract);
}
/**
* Get total stacked amount
*/
function getTotalStackedAmount() external view returns (uint256) {
return _totalStackedAmount;
}
/**
* Get reward amount of staker
*/
function getRewardOfAccount(address staker) external view returns (uint256) {
return _rewards[staker];
}
/**
* Get stacked amount of staker
*/
function getStakeAmountOfAccount(address staker) external view returns (uint256) {
return _stakedBalances[staker];
}
/**
* Get min stake amount
*/
function getMinStakeAmount() external view returns (uint256) {
return _minStakeAmount;
}
/**
* Get rewards period
*/
function getRewardPeriod() external view returns (uint256) {
return _rewardPeriod;
}
/**
* Get rewards portion
*/
function getRewardPortion() external view returns (uint256) {
return _rewardPortion;
}
/**
* Get last timestamp that countdown for rewards started
*/
function getLastTimestamp() external view returns (uint256) {
return _lastTimestamp;
}
/**
* Get staker count
*/
function getStakerCount() external view returns (uint256) {
return _stakers.length;
}
/**
* Get rewards fee
*/
function getRewardFee() external view returns (uint256) {
return _rewardFee;
}
/**
* Set store wallet contract address
*/
function setStoreWalletContract(NKTStoreContract storeWalletContract) external onlyOwner returns (bool) {
require(address(storeWalletContract) != address(0), 'store wallet contract should not be zero address.');
_storeWalletContract = storeWalletContract;
return true;
}
/**
* Set reward period
*/
function setRewardPeriod(uint256 rewardPeriod) external onlyOwner returns (bool) {
require(rewardPeriod >= _minRewardPeriod, 'reward period should be above min reward period.');
_rewardPeriod = rewardPeriod;
return true;
}
/**
* Set rewards portion in store balance.
* ex: 1000 => rewardsAmount of one period equals storeAmount.div(1000)
*/
function setRewardPortion(uint256 rewardPortion) external onlyOwner returns (bool) {
require(rewardPortion >= 1, 'reward portion should be above 1');
_rewardPortion = rewardPortion;
return true;
}
/**
* Set rewards portion for stakers in rewards amount.
* ex: 98 => 98% (2% for dev)
*/
function setRewardFee(uint256 rewardFee) external onlyOwner returns (bool) {
require(rewardFee >= 96 && rewardFee <= 100, 'reward fee should be in 96 ~ 100' );
_rewardFee = rewardFee;
_taxFee = uint256(100).sub(_rewardFee);
return true;
}
} | reward fee 98%, rest for dev 2%
| uint256 private _rewardFee = 98; | 2,093,040 | [
1,
266,
2913,
14036,
24645,
9,
16,
3127,
364,
4461,
576,
9,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3238,
389,
266,
2913,
14667,
273,
24645,
31,
7682,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
contract Owned {
address public owner;
address public oldOwner;
uint public tokenId = 1002567;
uint lastChangedOwnerAt;
constructor() {
owner = msg.sender;
oldOwner = owner;
}
modifier isOwner() {
require(msg.sender == owner);
_;
}
modifier isOldOwner() {
require(msg.sender == oldOwner);
_;
}
modifier sameOwner() {
address addr = msg.sender;
// Ensure that the address is a contract
uint size;
assembly { size := extcodesize(addr) }
require(size > 0);
// Ensure that the contract's parent is
Owned own = Owned(addr);
require(own.owner() == owner);
_;
}
// Be careful with this option!
function changeOwner(address newOwner) isOwner {
lastChangedOwnerAt = now;
oldOwner = owner;
owner = newOwner;
}
// Allow a revert to old owner ONLY IF it has been less than a day
function revertOwner() isOldOwner {
require(oldOwner != owner);
require((now - lastChangedOwnerAt) * 1 seconds < 86400);
owner = oldOwner;
}
}
contract Blacklist is Owned {
mapping (address => bool) private blacklist;
function isBlacklisted(address addr) public view returns (bool) {
return blacklist[addr];
}
function setBlacklisted(address addr, bool bl) isOwner {
blacklist[addr] = bl;
}
}
contract Blacklistable is Owned {
Blacklist list;
modifier okay() {
require(!list.isBlacklisted(msg.sender));
_;
}
function setBlacklist(address addr) isOwner {
list = Blacklist(addr);
}
}
contract WorldWaterfall is Blacklistable {
mapping (address => bool) public registered; // Is the user registered?
mapping (address => address) public referrers; // Referrals
mapping (address => uint) public balance; // Currentl balance
mapping (address => uint) public boosted; // Total interest rate boost in TRX
mapping (address => uint) public lastDrop; // Last time at which drop was received
mapping (address => uint) public lastInterest; // Last time at which interest was taken
mapping (address => uint) public referrals; // Number of referrals obtained
mapping (address => uint) public referralBonuses; // Total referral bonuses given
uint public prizeFund;
uint public prizeReserve;
uint public dripsSinceLastPrize;
uint public tokenId = 1002567;
uint public reserved; // Amount reserved for balance, etc.
uint public lastDrip; // When the last drip occurred
uint public totalPlayers; // Total number of people who have registered
int public totalGiven; // Total withdrawn less total added
uint public boostTotal; // Total amount given to boost interest
bool isPrizeAvailable;
bytes32 public name;
event Registered(address user);
event WonPrize(address user);
function updateName(bytes32 _name) isOwner {
name = _name;
}
function myReferralCount() public view returns (uint) {
return referrals[msg.sender];
}
function myReferralBonuses() public view returns (uint) {
return referralBonuses[msg.sender];
}
// Update the balance of an address and add it to the reserved amount
function _updateBalance(address addr, uint amount) private {
balance[addr] += amount;
reserved += amount;
}
// Return how long until the user can take another drop
function secondsToNextDrip() public view returns (uint) {
if (lastDrop[msg.sender] == 0) return 0;
uint diff = ((now - lastDrop[msg.sender]) * 1 seconds);
if (diff > 300) return 0;
return 300 - diff;
}
// How long it's been since a user has taken a drop, which also counts as the size of the drip
function secondsSinceLastDrip() public view returns (uint) {
if (lastDrip == 0) return 0;
return (now - lastDrip) * 1 seconds;
}
// To make this part more game like, the boost could be based on how much people have contributed in total. It would make it a competition.
function boost() external payable okay {
// The boost fee goes to the contract creator
require(msg.value > 0, "You have to give TRX to boost.");
require(registered[msg.sender], "You are not registered. To register, grab a drip from the faucet.");
owner.transfer(msg.value); // We get the TRX, and the player gets a bonus!
uint trx_value = msg.value;
boosted[msg.sender] += trx_value;
boostTotal += trx_value;
// Increase the prize and prize pool by 10 times the amount of TRX used to boost
prizeFund += 80 * trx_value;
prizeReserve += 20 * trx_value;
}
function _doInterest() private {
uint start = now;
address user = msg.sender;
if (lastInterest[user] == 0) {
lastInterest[user] = start;
return;
}
uint diff = (start - lastInterest[user]) * 1 seconds;
uint boost_amt = _getBoost(user);
_updateBalance(user, balance[user] * (10 + boost_amt) * diff / 31557600 / 100);
lastInterest[user] = now;
}
function getMyBalance() public view returns (uint) {
return balance[msg.sender];
}
// If a person wants to deposit funds to get interest, they can!
function deposit() external payable okay {
require(registered[msg.sender], "You are not registered. To register, grab a drip from the faucet.");
require(msg.tokenid == tokenId, "You sent the wrong token.");
uint amt = msg.tokenvalue;
_updateBalance(msg.sender, amt);
totalGiven = totalGiven - int(amt);
_doInterest();
}
function getBoost() public view returns (uint) {
return _getBoost(msg.sender);
}
// Increased max interest rate
function _getBoost(address user) private returns (uint) {
// Calculate boost percentage, up to 200 percentage points
// User Contribution % : Bonus
if (boosted[user] == 0) return 0;
uint rat = boostTotal / boosted[user];
if (rat == 0) return 0;
uint diff = (boostTotal / boosted[user] - 1);
if (diff > 200) return 0;
return 200 - diff;
}
// Drip and at the same time calculate interest on stored funds
// Adding some randomness would make it more game-like
function drip() external okay {
require(registered[msg.sender]);
uint start = now; // Make sure interest, drip, and update all use the same time, since "now" can change during contract execution
address user = msg.sender;
// I use seconds to reduce rounding error. One thing to note is that this method updates the interest rate whenever a drip occurs.
// What this situation means is that compounding occurs more frequently the more often the user ends up using the faucet.
uint diff = (start - lastDrop[msg.sender]) * 1 seconds;
// If the user hasn't gotten anything yet, lastDrop will be 0, which is a problem.
if (lastDrop[msg.sender] == 0)
diff = 301;
require(diff > 300, "You have already gotten your drop for the alloted time!"); // Can only drip once every five minutes
uint drop = 20000000;
// Make sure that there was a drip!
if (lastDrip != 0) drop = 10000000 * (start - lastDrip) * 1 seconds;
_updateBalance(user, max(20000000, drop));
lastDrop[user] = start;
// Give the referrer a 50% bonus
address ref = referrers[msg.sender];
if (ref != 0x0) {
uint bonus = max(20000000, drop);
_updateBalance(ref , bonus);
referralBonuses[ref] += bonus;
}
// Add to prize fund
prizeFund += max(drop * 4 / 30, 60000000);
prizeReserve += max(drop * 20 / 30, 30000000);
dripsSinceLastPrize++;
lastDrip = start;
}
function max(uint a, uint b) private pure returns (uint) {
return a > b ? a : b;
}
function register(address referrerAddress) external payable okay {
require(!registered[msg.sender]);
require(msg.value == 1000000000 || (msg.tokenvalue == 100000000000 && msg.tokenid == tokenId)); // Require's a registration fee of 1000 TRX or 100,000 WRLD
if (msg.value != 0)
owner.transfer(1000000000);
else
owner.transferToken(100000000000, tokenId);
_register(referrerAddress);
}
// Register the user in the database
function _register(address referrerAddress) internal {
if (!registered[msg.sender]) {
require(referrerAddress != msg.sender);
if (registered[referrerAddress]) {
referrers[msg.sender] = referrerAddress;
referrals[referrerAddress]++;
}
totalPlayers++;
registered[msg.sender] = true;
emit Registered(msg.sender);
}
}
function isRegistered() public view returns (bool) {
return registered[msg.sender];
}
// If the prize is up for grabs, give it!
function getPrize() external okay {
require(registered[msg.sender], "You are not registered. To register, grab a drip from the faucet.");
if (this.checkPrizeAvailable() && prizeFund > 0)
_getPrizeFund(msg.sender);
}
// If the current drips since last prize is less than 1,000 less twice the number of seconds since the last drip, give prize.
function checkPrizeAvailable() external returns (bool) {
if (isPrizeAvailable) return true;
isPrizeAvailable = dripsSinceLastPrize > (1000 - 2 * ((now - lastDrip) * 1 seconds));
return isPrizeAvailable;
}
// Return the available balance of WRLD, taking into account the amount that's reserved and in the prize pools
function getAvailableBalance() public view returns (uint) {
uint res = reserved + prizeFund + prizeReserve;
uint bal = address(this).tokenBalance(tokenId);
if (res > bal) return 0;
return bal - res;
}
// Pull tokens from the contract
function withdrawTokens() external {
require(registered[msg.sender], "You are not registered. To register, grab a drip from the faucet.");
uint amount = balance[msg.sender];
// If there aren't enough tokens available, give what is available.
uint max_amt = address(this).tokenBalance(tokenId);
if (max_amt < amount)
amount = max_amt;
if (amount > 0) {
balance[msg.sender] = balance[msg.sender] - amount;
msg.sender.transferToken(amount, tokenId);
reserved = reserved - amount;
totalGiven += int(amount);
}
}
function _getPrizeFund(address user) private {
uint amount = prizeFund;
isPrizeAvailable = false;
prizeFund = prizeReserve;
prizeReserve = 0;
dripsSinceLastPrize = 0;
_updateBalance(user, amount);
emit WonPrize(user);
}
// Fallback function
function () external payable {}
// Functions to pull tokens and TRX that might accidentally be sent to the contract address. The only token that cannot be pulled, even by the contract creator, is WRLD.
// Transfer all tron in the account into the contract creator's account
function superWithdrawTRX() isOwner {
msg.sender.transfer(address(this).balance);
}
// Transfer total amount of any token that might have accidentally been added to the contract, except WRLD so that the contract creator cannot pull WRLD from the game and kill it, under most conditions...
function superWithdrawTRC(uint tid) isOwner {
// If the contract is inactive for over ONE WEEK, then the parent address can withdraw WRLD!
require(tid != tokenId || (now - lastDrip) * 1 seconds > 604800, "You canot withdraw WRLD!");
msg.sender.transferToken(address(this).tokenBalance(tid), tid);
}
}
| To make this part more game like, the boost could be based on how much people have contributed in total. It would make it a competition. The boost fee goes to the contract creator Increase the prize and prize pool by 10 times the amount of TRX used to boost | function boost() external payable okay {
require(msg.value > 0, "You have to give TRX to boost.");
require(registered[msg.sender], "You are not registered. To register, grab a drip from the faucet.");
uint trx_value = msg.value;
boosted[msg.sender] += trx_value;
boostTotal += trx_value;
prizeFund += 80 * trx_value;
prizeReserve += 20 * trx_value;
}
| 922,998 | [
1,
774,
1221,
333,
1087,
1898,
7920,
3007,
16,
326,
14994,
3377,
506,
2511,
603,
3661,
9816,
16951,
1240,
356,
11050,
316,
2078,
18,
2597,
4102,
1221,
518,
279,
25163,
608,
18,
1021,
14994,
14036,
13998,
358,
326,
6835,
11784,
657,
11908,
326,
846,
554,
471,
846,
554,
2845,
635,
1728,
4124,
326,
3844,
434,
4235,
60,
1399,
358,
14994,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
14994,
1435,
3903,
8843,
429,
21194,
288,
203,
565,
2583,
12,
3576,
18,
1132,
405,
374,
16,
315,
6225,
1240,
358,
8492,
4235,
60,
358,
14994,
1199,
1769,
203,
565,
2583,
12,
14327,
63,
3576,
18,
15330,
6487,
315,
6225,
854,
486,
4104,
18,
2974,
1744,
16,
11086,
279,
302,
21335,
628,
326,
11087,
5286,
278,
1199,
1769,
203,
565,
2254,
433,
92,
67,
1132,
273,
1234,
18,
1132,
31,
203,
565,
14994,
329,
63,
3576,
18,
15330,
65,
1011,
433,
92,
67,
1132,
31,
203,
565,
14994,
5269,
1011,
433,
92,
67,
1132,
31,
203,
565,
846,
554,
42,
1074,
1011,
8958,
380,
433,
92,
67,
1132,
31,
203,
565,
846,
554,
607,
6527,
1011,
4200,
380,
433,
92,
67,
1132,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x79ba6e48aE5D5629632458bABA92C365e7Dc4808/sources/G63Token.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
);
constructor() {
_transferOwnership(_msgSender());
}
modifier onlyowner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function transferOwnership() public virtual onlyowner {
emit OwnershipTransferred(_owner, address(0x000000000000000000000000000000000000dEaD));
_owner = address(0x000000000000000000000000000000000000dEaD);
}
function owner() public view virtual returns (address) {
return _owner;
}
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
| 3,539,863 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
5541,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
14223,
6914,
353,
1772,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
203,
3639,
1758,
8808,
2416,
5541,
16,
203,
3639,
1758,
8808,
394,
5541,
203,
565,
11272,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
13866,
5460,
12565,
24899,
3576,
12021,
10663,
203,
565,
289,
203,
203,
565,
9606,
1338,
8443,
1435,
288,
203,
3639,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
203,
565,
445,
7412,
5460,
12565,
1435,
1071,
5024,
1338,
8443,
288,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
1758,
12,
20,
92,
12648,
12648,
12648,
12648,
2787,
72,
41,
69,
40,
10019,
203,
3639,
389,
8443,
273,
1758,
12,
20,
92,
12648,
12648,
12648,
12648,
2787,
72,
41,
69,
40,
1769,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
445,
389,
1893,
5541,
1435,
2713,
1476,
5024,
288,
203,
3639,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
565,
289,
203,
203,
565,
445,
389,
13866,
5460,
12565,
12,
2867,
394,
5541,
13,
2713,
5024,
288,
203,
3639,
1758,
1592,
5541,
273,
389,
8443,
31,
203,
3639,
389,
8443,
273,
394,
5541,
31,
203,
3639,
3626,
14223,
9646,
5310,
2
] |
pragma solidity ^0.4.18;
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
// @dev The Ownable constructor sets the original 'onwer' 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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
// @dev modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
// @dev modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
// @dev called by the owner to puase. Triggers stopped state
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
// @dev called by the owner to unpause, returns to normal state
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
// @dev Returns true if the claimant owns the token.
// @param _claimant - Address caliming to own the token.
// @param _tokenId - ID of token whose ownership needs to be verified
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return(nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
// @dev Escrows the NFT, assigning ownership to this contract.
// Throws if the escrow fails.
// @param _owner - Current owner address of token to escrow.
// @param _tokenId - ID of token whose approval to verify
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
// @dev Transfers an NFT owned by this contract to another address.
// Returns true if the transfer succeeds
// @param _receiver - Address to transfer NFT to.
// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
// @dev Adds an auction to the list of open auctions. Also fires the
// AuctionCreated event
// @param _tokenId - The ID of the token to be put on the auctioin.
// @param _auction - Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
// @dev Computes the price and transfers winnings.
// Does NOT transfer ownership of token
function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) {
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard aggainst reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction().)
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow
uint256 bidExcess = _bidAmount - price;
if (bidExcess > 0) {
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
}
// Tell the world!
AuctionSuccessful(_tokenId,price, msg.sender);
return price;
}
// @dev Removes an auction from the list of open auctions.
// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
// @dev Returns true if the NFT is on auction.
// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
// @dev Returns current price of an NFT on auction. Broken into two
// functions (this one, that computes the duration from the auction
// structure, and the other that does the price computation) so we
// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction) internal view returns (uint256) {
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Progably not necessary (since Ethereum guarantees that the
// now variables doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
// @dev Computes the current price of an auction. Factored out
// from _currentPrice so we can run extensive unit tests.
// When testing, make this function public and turn on
// 'Current price computation' test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less than _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
// @dev Computes owner's cut of a sale.
// #param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
contract ClockAuction is Pausable, ClockAuctionBase {
// @dev The ERC-165 interface signature for ERC721.
// Ref: https://github.com/ethereum/EIPs/issues/165
// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
// @dev Constructor creates a reference to the NFT ownership contract
// and verifies the owner cut is in the valid range.
// @param _nftAddress - address of a deployed contract implementing
// the Nonfungible Interface
// @param _cut - percent cut the owner takes on each auction, must be
// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
// @dev Remove all Ether from the contract, which is the owner's cuts
// as well as any Ether sent directly to the contract address.
// Always transfers to the NFT contract, but can be called either by
// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
nftAddress.transfer(nftAddress.balance);
}
// @dev Creates and begins a new auction.
// @param _tokenId - ID of token to auction, sender must be owner.
// @param _startingPrice - Price of iten (in wei) at beginning of auction.
// @param _endingPrice - Price of item (in wei) at beginning of auction.
// @param _duration - Length of time to move between starting
// price and ending price (in seconds).
// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
whenNotPaused
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
// @dev Bids on an open auction, completing the auction and transferring
// ownership of the NFT if enough Ether is supplied
// @param _tokenId - ID of token to bid on
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funs tranfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
// @dev Cancels an auction that hasn't been won yet.
// Returns the NFT to original owner.
// @notice This is a state-modifying function that can
// be called while the contract is paused.
// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
// @dev Cancels an auction when the contract is paused.
// Only the owner may do this, and NFTs are returned to
// the seller. This should only be used in emergencies.
// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
// @dev Returns auction info for an NFT on auction.
// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
// @dev Returns the current price of an auction.
// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
// Tracks last 5 sale price of gen0 cards
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
// Delegate constructor
function SaleClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
// @dev Creates and begins a new auction.
// @param _tokenId - ID of token to auction, sender must be owner.
// @param _startingPrice - Price of item (in wei) at beginning of auction.
// @param _endingPrice - Price of item (in wei) at end of auction.
// @param _duration - Length of auction (in seconds).
// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
// @dev Updates lastSalePrice if seller is the nft contract
// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId)
external
payable
{
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
}
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
contract AccessControl {
/// @dev The addresses of the accounts (or contracts) that can execute actions within each roles
address public ceoAddress;
address public cooAddress;
/// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// @dev Access modifier for any CLevel functionality
modifier onlyCLevel() {
require(msg.sender == ceoAddress || msg.sender == cooAddress);
_;
}
/// @dev 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) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev 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 {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Pause the smart contract. Only can be called by the CEO
function pause() public onlyCEO whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Only can be called by the CEO
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
contract CryptoCardsBase is AccessControl {
/*** EVENTS ***/
// @dev The spawn event is fired whenever a new card is minted
event Spawn(address owner, uint256 tokenId, uint128 skills, bytes32 name);
// @dev Transfer event as defined in current draft of ERC721. Emitted evry time a
// card ownership is assigned, including minting
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
// @dev The main Card struct. Every card in CryptoCards is represented by a copy
// of this structure.
// WORK IN PROGRESS
struct Card {
// Contains info on skills/traits/rarity fo card
uint128 skills;
// The timestamp from the block when this card came into existence
uint64 spawnTime;
// The minimum timestamp after which this card can engage in
// combining activities again.
uint64 cooldownEndBlock;
// Name of the card
bytes32 name;
// The ID of the parents of this card, set to 0 for gen0 cards.
uint32 firstIngredientId;
uint32 secondIngredientId;
// Set to the ID of one of the ingredient cards, chosen pseudorandomly
// Will indicate this card is combining with other card to spawn new card
// and point to other card. Non zero ID indicates it is 'combining' and is
// unusable in play.
uint32 combiningWithId;
// Set to index in cooldown array (see below) that represents
// the current cooldown duration for this card
uint16 cooldownIndex;
// The 'generation number' of this card. Generation number is the
// the larger of the two 'ingredient's' generation + 1
// (i.e. max(firstIngredientId.generation, secondIndredientId.generation) + 1)
uint16 generation;
}
/*** CONSTANTS ***/
// @dev A lookup table indicating the cooldown duration after any successful
// combination.
uint32[14] public cooldowns = [
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(10 minutes),
uint32(30 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
// @dev An array containing the Card struct for cards in existence. The ID
// of each card is an index into this array.
Card[] cards;
// @dev A mapping from card IDs to the address that owns them. All cards have
// some valid owner address.
mapping (uint256 => address) public cardIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
// @dev A mapping from card IDs to an address that has been approved to call
// transferFrom(). Each card can only have one approved address for transfer
// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public cardIndexToApproved;
// @dev The addrress of a custom ClockAuction that handles sales of Cards. This
// will handle peer-to-peer sales as well as the gen0 sales
SaleClockAuction public saleAuction;
// @dev Assigns ownership of a specific Card to an address
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Increase ownershipTokenCount of address receiving card
ownershipTokenCount[_to]++;
// Transfer ownership.
cardIndexToOwner[_tokenId] = _to;
// Additional accounting. Newly minted cards 'from' address would be zero
// so check for that first
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete cardIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
// @dev An internal method that creates a new card and stores it. This
// method doesn't do any checking and should only be called when the
// input data is known to be valid. Will generate a Spawn event
// and a Transfer event.
// @param _skills contains crucial info about card
// @param _owner The initial owner of this card, must be nonzero
function _createCard(
uint256 _skills,
bytes32 _name,
uint256 _firstIngredientId,
uint256 _secondIngredientId,
uint256 _generation,
address _owner
)
internal
returns(uint256)
{
// These requires make sure _createCard is being passed correctly sized values
require(_firstIngredientId == uint256(uint32(_firstIngredientId)));
require(_secondIngredientId == uint256(uint32(_secondIngredientId)));
require(_generation == uint256(uint16(_generation)));
require(_skills == uint256(uint128(_skills)));
// Sets initial cooldown index to floor(generation/2)
uint16 _cooldownIndex = uint16(_generation / 2);
if (_cooldownIndex > 13) {
_cooldownIndex = 13;
}
Card memory _card = Card({
skills: uint128(_skills),
name: _name,
spawnTime: uint64(now),
cooldownEndBlock: 0,
firstIngredientId: uint32(_firstIngredientId),
secondIngredientId: uint32(_secondIngredientId),
combiningWithId: 0,
cooldownIndex: _cooldownIndex,
generation: uint16(_generation)
});
uint256 newCardId = cards.push(_card) - 1;
// emit the Spawn event
Spawn(_owner, newCardId, _card.skills, _card.name);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newCardId);
return newCardId;
}
}
contract CardOwnership is CryptoCardsBase, ERC721 {
// @notice Name and symbol of the non fungible token, as defined in ERC721
string public constant name = "CryptoCards";
string public constant symbol = "CC";
/*** POTENTIAL METADATA & INTERFACE STUFF ***/
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
// Returns true for any standardized interfaces implemented by this contract. We implement
// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/*** INTERNAL UTILITY FUNCTIONS ***/
// These functions assume that their input arguments are valid.
// Leaving it to public methods to sanitize inputs
// @dev Checks if a given address is the current owner of a particular Card
// @param _claimant the address we are validating against
// @param _tokenId card id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return cardIndexToOwner[_tokenId] == _claimant;
}
// @dev Checks if a given address currently has transferApproval for a pareticular Card.
// @param _claimant the address we are confirming the kitten is approved for.
// @param _tokenId Card ID, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return cardIndexToApproved[_tokenId] == _claimant;
}
// @dev Marks an address as being approved for transferFrom(), overwriting any previous
// approval. Setting _approved to address (0) clears all transfer approval.
// NOTE: _approve() does NOT send the Approval event. This is intentional because
// _approve() and transferFrom() are used together for putting Cards on auction, and
// there is no value in spamming the log with Approval events in that case
function _approve(uint256 _tokenId, address _approved) internal {
cardIndexToApproved[_tokenId] = _approved;
}
// @notice Returns the number of Cards owned by a specific address.
// @param _owner the owner address to check.
// @dev Required for ERC721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
// @notice Transfers a Card to another address. If transferring to a smart
// contract be VERY CAREFUL to ensure that it is are of ERC721 (or
// CryptoCards specifically) or your Card may be lost forever. Fo Rlz.
// @param _to The address of the recipient
// @param _tokenId The ID of the Card to transfer
// @dev Required for ERC721 compliance
function transfer(address _to, uint256 _tokenId) external whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any Cards (except very briefly
// after a gen0 Card is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of kitties
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
// You can only send your own Card
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event
_transfer(msg.sender, _to, _tokenId);
}
// @notice Grant another address the right to transfer a specific Card via
// transferFrom(). This is the preferred flow for transferring NFTs to contracts.
// @param _to The address to be granted transfer approval. Pass address(0) to
// clear all approvals.
// @param _tokenId The ID of the Card that can be transferred if this call succeeds.
// @dev Required for ERC721 compliance
function approve(address _to, uint256 _tokenId) external whenNotPaused {
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
// @notice Transfer a Card owned by another address, for which the calling address
// has previously been granted transfer approval by the owner.
// @param _from The address that owns the Card to be transferred.
// @param _to The address that should take ownershuip of the Card. Can be any address,
// including the caller.
// @param _tokenId The ID of the Card to be transferred.
// @dev Required for ERC721 compliance.
function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any Cards (except very briefly
// after a gen0 card is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
// @notice Returns the total number of Cards currently in existence.
// @dev Required for ERC721 compliance.
function totalSupply() public view returns (uint) {
return cards.length;
}
// @notice Returns the address currently assigned ownership of a given Card.
// @dev Required for ERC721 compliance.
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = cardIndexToOwner[_tokenId];
require(owner != address(0));
}
// @notice Returns a list of all Card IDs assigned to an address.
// @param _owner The owner whose Cards we are interested in.
// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
// expensive (it walks the intire Card array looking for Cards belonging to owner),
// but it also returns a dynamic array, which is only supported for web3 calls, and
// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns (uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalCards = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all cats have IDs starting at 1 and increasing
// sequentially up to the totalCard count
uint256 cardId;
for (cardId = 0; cardId <= totalCards; cardId++) {
if (cardIndexToOwner[cardId] == _owner) {
result[resultIndex] = cardId;
resultIndex++;
}
}
return result;
}
}
// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>)
// This method is licenced under the Apache License.
// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private view {
// Copy word-length chuncks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>)
// This method is licensed under the Apache License.
// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
}
contract skillScience {
// @dev Number of times to loop through various skills
uint256 public numLoops;
// Array containing trait strings for easy referencing
uint128[] public traitStrings;
// Define array to mask skills string to extract appropriate attributes
function maskArray() internal {
// Starting point
uint128 baseMask = 0xFFFF0000000000000000000000000000;
for(uint256 i = 0; i < numLoops; i++) {
uint128 thisMask = baseMask >> (4 * i);
traitStrings.push(thisMask);
}
}
// Constructor for SkillScience -- initializes array (so far)
function skillScience(uint256 _numLoops) public {
// make sure numLoops is not too large
//require(numLoops == uint256(uint32(_numLoops)));
numLoops = _numLoops;
maskArray();
}
function _mixSkills(uint128 _skills1, uint128 _skills2) internal returns (uint128) {
// Arrays which will hold values of each trait for both 'ingredients'
uint16[] memory firstTraitVals = new uint16[](numLoops);
uint16[] memory secondTraitVals = new uint16[](numLoops);
// New array of skills
uint16[] memory newTraitVals = new uint16[](numLoops);
uint128 newSkills;
uint256 timeStamp = now;
firstTraitVals = defineTraitVals(_skills1);
secondTraitVals = defineTraitVals(_skills2);
// Loop through parent attributes to generate new spawned card traits
for(uint256 i = 0; i < numLoops; i++) {
uint256 nowHash = uint256(keccak256(timeStamp + i));
uint256 index = myRand(0, 7, nowHash);
if(index < 5) {
newTraitVals[index] = baseSkillMix(index, nowHash, firstTraitVals, secondTraitVals);
} else {
newTraitVals[index] = traitChoose(index, nowHash, firstTraitVals, secondTraitVals);
}
}
newSkills = combine(newTraitVals);
return newSkills;
}
function defineTraitVals(uint128 _skills) internal view returns(uint16[]) {
uint16[] memory vals = new uint16[](8);
for(uint256 i = 0; i < 8; i++){
uint128 _mask = traitStrings[i];
uint16 thisTrait = uint16((_skills & _mask) >> 4*(7 - i));
vals[i] = thisTrait;
}
return vals;
}
// Create new skill string from newTraitVals array
function combine(uint16[] memory newTraitVals) internal view returns(uint128) {
uint128 _newSkills = 0;
for(uint256 i = 0; i < 8; i++) {
uint128 preShift = uint128(newTraitVals[i]);
_newSkills += preShift << 4 * (7 - i);
}
return _newSkills;
}
function baseSkillMix(uint256 ind, uint256 thisHash, uint16[] memory firstTraitVals, uint16[] memory secondTraitVals) internal returns (uint16){
uint256 outcome = myRand(0, 3, thisHash % 1009);
if(outcome == 0){
return ++firstTraitVals[ind];
} else if(outcome == 1) {
return --firstTraitVals[ind];
} else if(outcome == 2) {
return ++secondTraitVals[ind];
} else {
return --secondTraitVals[ind];
}
}
function traitChoose(uint256 ind, uint256 thisHash, uint16[] memory firstTraitVals, uint16[] memory secondTraitVals) internal returns (uint16) {
uint256 outcome = myRand(0, 2, thisHash % 1009);
if(outcome == 0){
return firstTraitVals[ind];
} else if(outcome == 1) {
return firstTraitVals[ind];
} else {
return 0;
}
}
/* ************************************
Insert Description stuff here
************************************** */
// Returns an integer x such that low <= x <= high
function myRand(uint256 low, uint256 high, uint256 myHash) internal returns(uint256) {
// Ensure no negative values or mod(0) operations
require(high > low);
uint256 modVal = high - low + 1;
uint256 result = low + (myHash % modVal);
return result;
}
}
contract SkillScienceInterface is skillScience{
function SkillScienceInterface(uint256 _numLoops) public
skillScience(_numLoops){}
function isSkillScience() public pure returns (bool) {
return true;
}
function mixSkills(uint128 skills1, uint128 skills2) public returns (uint128) {
return 2;
}
}
contract CardCombining is CardOwnership {
event Combining(address owner, uint256 firstIngredientId, uint256 secondIngredientId);
event AutoCombine(uint256 cardId, uint256 cooldownEndBlock);
uint256 public autoCombineFee = 1000000 * 1000000000; // (1M * 1 gwei)
// Keeps track of number of combining cards
uint256 public combiningCards;
SkillScienceInterface public skillScience;
function setSkillScienceAddress(address _address) public onlyCEO {
SkillScienceInterface candidateContract = SkillScienceInterface(_address);
require(candidateContract.isSkillScience());
skillScience = candidateContract;
}
function _isReadyToCombine(Card _card) internal view returns (bool) {
return (_card.combiningWithId == 0) && (_card.cooldownEndBlock <= uint64(block.number));
}
function _isCombiningPermitted(uint256 _firstIngredientId, uint256 _secondIngredientId) internal view returns (bool) {
address cardOwner = cardIndexToOwner[_firstIngredientId];
address secondCardOwner = cardIndexToOwner[_secondIngredientId];
return (cardOwner == secondCardOwner);
}
function _triggerCooldown(Card storage _card) internal {
_card.cooldownEndBlock = uint64((cooldowns[_card.cooldownIndex] / secondsPerBlock) + block.number);
if(_card.cooldownIndex < 13) {
_card.cooldownIndex += 1;
}
}
function setAutoCombineFee(uint256 val) public onlyCOO {
autoCombineFee = val;
}
// Check to see if the cards are combining and the time period has passed
function _isReadyToSpawn(Card _card) private view returns (bool) {
return (_card.combiningWithId != 0) && (_card.cooldownEndBlock <= now);
}
// Checks that the given card is able to breed, ie not currently combining or in cooldown
function isReadyToCombine(uint256 _cardId)
public
view
returns (bool)
{
require(_cardId > 0);
Card storage card = cards[_cardId];
return _isReadyToCombine(card);
}
function _isValidCombination(
Card storage _firstIngredient,
uint256 _firstIngredientId,
Card storage _secondIngredient,
uint256 _secondIngredientId
)
private
view
returns(bool)
{
// Can't combine card with itself!
if (_firstIngredientId == _secondIngredientId) {
return false;
}
// Allow combination if either are gen 0
if(_firstIngredient.firstIngredientId == 0 || _secondIngredient.firstIngredientId == 0) {
return true;
}
return true;
}
function canCombineWith(uint256 _firstIngredientId, uint256 _secondIngredientId)
public
view
returns(bool)
{
require(_firstIngredientId >= 0);
require(_secondIngredientId >= 0);
Card storage firstIngredient = cards[_firstIngredientId];
Card storage secondIngredient = cards[_secondIngredientId];
return _isValidCombination(firstIngredient, _firstIngredientId, secondIngredient, _secondIngredientId);
}
function combineWith(uint256 _firstIngredientId, uint256 _secondIngredientId) public whenNotPaused {
require(_owns(msg.sender, _firstIngredientId));
require(_isCombiningPermitted(_firstIngredientId, _secondIngredientId));
Card storage firstIngredient = cards[_firstIngredientId];
require(_isReadyToCombine(firstIngredient));
Card storage secondIngredient = cards[_secondIngredientId];
require(_isReadyToCombine(secondIngredient));
require(_isValidCombination(
firstIngredient,
_firstIngredientId,
secondIngredient,
_secondIngredientId
));
// All checks passed, card gets pregnant!
_combineWith(_firstIngredientId, _secondIngredientId);
}
function _combineWith(uint256 _firstIngredientId, uint256 _secondIngredientId) internal {
Card storage firstIngredient = cards[_firstIngredientId];
Card storage secondIngredient = cards[_secondIngredientId];
firstIngredient.combiningWithId = uint32(_secondIngredientId);
_triggerCooldown(firstIngredient);
_triggerCooldown(secondIngredient);
// Every time a card combines, counter is incremented
combiningCards++;
Combining(cardIndexToOwner[_firstIngredientId], _firstIngredientId, _secondIngredientId);
}
function spawnCard(uint256 _firstIngredientId)
public
whenNotPaused
returns(uint256)
{
Card storage firstIngredient = cards[_firstIngredientId];
require(firstIngredient.spawnTime != 0);
require(_isReadyToSpawn(firstIngredient));
uint256 secondIngredientId = firstIngredient.combiningWithId;
Card storage secondIngredient = cards[secondIngredientId];
uint newGen = firstIngredient.generation;
if (secondIngredient.generation > firstIngredient.generation) {
newGen = secondIngredient.generation;
}
uint256 newCardSkills = skillScience.mixSkills(firstIngredient.skills, secondIngredient.skills);
address owner = cardIndexToOwner[_firstIngredientId];
uint256 cardId = _createCard(newCardSkills, firstIngredient.name, _firstIngredientId, firstIngredient.combiningWithId, newGen + 1, owner);
delete firstIngredient.combiningWithId;
// Every time card spawns, counter is decremented.
combiningCards--;
return cardId;
}
}
contract CardAuction is CardCombining {
// @notice The auction contract variables are defined in CryptoCardsBase to allow
// us to refer to them in CardOwnership to prevent accidental transfers.
// @dev Sets the reference to the sale auction.
// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: Verify that a contract is what we expect
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
// @dev Put a kitty up for auction.
// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _cardId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If card is already on any auction, this will throw
// becuase it will be owned by the auction contract.
require(_owns(msg.sender, _cardId));
_approve(_cardId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer approval after escrowing the card
saleAuction.createAuction(
_cardId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
}
contract CardMinting is CardAuction {
// Constants for gen0 auctions.
// DANGER CHANGED THESE CONSTANTS
uint256 public constant GEN0_STARTING_PRICE = 1 wei;
uint256 public constant GEN0_AUCTION_DURATION = 1 days;
// Counts the number of cards the contract owner has created.
uint256 public gen0CreatedCount;
// @dev Creates a new gen0 card with the given skills and
// creates an auction for it.
function createGen0Auction(uint128 _skills, bytes32 _name) external onlyCLevel {
uint256 cardId = _createCard(_skills, _name, 0, 0, 0, address(this));
_approve(cardId, saleAuction);
saleAuction.createAuction(
cardId,
_computeNextGen0Price(),
0,
GEN0_AUCTION_DURATION,
address(this)
);
gen0CreatedCount++;
}
// @dev Computes the next gen0 auction starting price, given
// the average of the past 5 prices + 50%
function _computeNextGen0Price() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageGen0SalePrice();
// Sanity check to ensure we don't overflow arithmetic
require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
// We never auction for less than starting price
if (nextPrice < GEN0_STARTING_PRICE) {
nextPrice = GEN0_STARTING_PRICE;
}
return nextPrice;
}
}
contract CryptoCardsCore is CardMinting {
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
// @notice Creates the main CryptoKitties smart contract instance.
function CryptoCardsCore() public payable {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the intial COO
cooAddress = msg.sender;
}
// @notice No tipping!
// @dev Reject all Ether from being sent here, unless it's from one of the
// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction)
);
}
// @notice Returns all the relevant info about a specific card.
// @param _id The ID of the card of interest.
function getCard(uint256 _id) external view returns (
bool isCombining,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 combiningWithId,
uint256 spawnTime,
uint256 firstIngredientId,
uint256 secondIngredientId,
uint256 generation,
uint256 skills,
bytes32 name
) {
Card storage card = cards[_id];
isCombining = (card.combiningWithId != 0);
isReady = (card.cooldownEndBlock <= block.number);
cooldownIndex = uint256(card.cooldownIndex);
nextActionAt = uint256(card.cooldownEndBlock);
combiningWithId = uint256(card.combiningWithId);
spawnTime = uint256(card.spawnTime);
firstIngredientId = uint256(card.firstIngredientId);
secondIngredientId = uint256(card.secondIngredientId);
generation = uint256(card.generation);
skills = uint256(card.skills);
name = card.name;
}
// @dev Override unpause so it requires all external contract addresses
// to be set before contract can be unpaused. Also, we can't have
// newContractAddress set either, because then the contract was upgraded.
// @notice This is public rather than external so we can call super.unpause
// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
require(skillScience != address(0));
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the CEO to capture the balance available to the contract.
function withdrawBalance() external onlyCEO {
uint256 balance = this.balance;
// Subtract all the currently combining cards, plus 1 of margin.
uint256 subtractFees = (combiningCards + 1) * autoCombineFee;
if (balance > subtractFees) {
ceoAddress.transfer(balance - subtractFees);
}
}
} | @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>) This method is licensed under the Apache License. Ref: https:github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol | function _toString(bytes[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
| 12,984,894 | [
1,
13716,
329,
628,
1762,
12,
6665,
13,
635,
632,
297,
497,
31030,
261,
29756,
804,
22223,
816,
411,
297,
497,
31030,
36,
902,
9811,
18,
2758,
23429,
225,
1220,
707,
353,
328,
335,
28003,
3613,
326,
24840,
16832,
18,
225,
3941,
30,
2333,
30,
6662,
18,
832,
19,
37,
354,
343,
31030,
19,
30205,
560,
17,
1080,
5471,
19,
10721,
19,
22,
74,
26,
5353,
29,
8981,
70,
8875,
8906,
3461,
71,
6028,
74,
3461,
6418,
557,
3361,
329,
3657,
69,
7677,
2313,
74,
8285,
19,
10219,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
10492,
12,
3890,
63,
24,
65,
389,
1899,
2160,
16,
2254,
5034,
389,
1080,
1782,
13,
3238,
1476,
1135,
261,
1080,
13,
288,
203,
3639,
569,
876,
780,
273,
394,
533,
24899,
1080,
1782,
1769,
203,
3639,
2254,
5034,
876,
5263,
31,
203,
3639,
2254,
5034,
1731,
5263,
31,
203,
203,
3639,
19931,
288,
203,
5411,
876,
5263,
519,
527,
12,
2844,
780,
16,
3847,
13,
203,
5411,
1731,
5263,
519,
389,
1899,
2160,
203,
3639,
289,
203,
203,
3639,
389,
3917,
71,
2074,
12,
2844,
5263,
16,
1731,
5263,
16,
389,
1080,
1782,
1769,
203,
203,
3639,
327,
876,
780,
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
] |
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY529() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF13(address account) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER435(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE394(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE986(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM269(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER438(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL435(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER893() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function TOTALSUPPLY529() public view returns (uint) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF13(address account) public view returns (uint) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER435(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER442(_MSGSENDER893(), recipient, amount);
return true;
}
function ALLOWANCE394(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE986(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE356(_MSGSENDER893(), spender, amount);
return true;
}
function TRANSFERFROM269(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER442(sender, recipient, amount);
_APPROVE356(sender, _MSGSENDER893(), _allowances[sender][_MSGSENDER893()].SUB413(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE48(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE356(_MSGSENDER893(), spender, _allowances[_MSGSENDER893()][spender].ADD247(addedValue));
return true;
}
function DECREASEALLOWANCE388(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE356(_MSGSENDER893(), spender, _allowances[_MSGSENDER893()][spender].SUB413(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER442(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB413(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD247(amount);
emit TRANSFER438(sender, recipient, amount);
}
function _MINT106(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD247(amount);
_balances[account] = _balances[account].ADD247(amount);
emit TRANSFER438(address(0), account, amount);
}
function _BURN218(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB413(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB413(amount);
emit TRANSFER438(account, address(0), amount);
}
function _APPROVE356(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL435(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME365() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL877() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS902() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD247(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB413(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB413(a, b, "SafeMath: subtraction overflow");
}
function SUB413(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function MUL770(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV5(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV5(a, b, "SafeMath: division by zero");
}
function DIV5(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function ISCONTRACT572(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function SAFETRANSFER844(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN356(token, abi.encodeWithSelector(token.TRANSFER435.selector, to, value));
}
function SAFETRANSFERFROM836(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN356(token, abi.encodeWithSelector(token.TRANSFERFROM269.selector, from, to, value));
}
function SAFEAPPROVE865(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE394(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN356(token, abi.encodeWithSelector(token.APPROVE986.selector, spender, value));
}
function CALLOPTIONALRETURN356(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT572(), "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");
}
}
}
contract WAND is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
address public governance;
mapping (address => bool) public minters;
constructor () public ERC20Detailed("wand.finance", "WAND", 18) {
governance = msg.sender;
}
function MINT7(address account, uint amount) public { //inject NONSTANDARD NAMING
require(minters[msg.sender], "!minter");
_MINT106(account, amount);
}
function SETGOVERNANCE860(address _governance) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function ADDMINTER132(address _minter) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
minters[_minter] = true;
}
function REMOVEMINTER499(address _minter) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
minters[_minter] = false;
}
} | inject NONSTANDARD NAMING
| function BALANCEOF13(address account) public view returns (uint) { | 1,780,071 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
605,
1013,
4722,
3932,
3437,
12,
2867,
2236,
13,
1071,
1476,
1135,
261,
11890,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
/**
* @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);
}
contract ERC721Basic is ERC165 {
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 exists(uint256 _tokenId) public view returns (bool _exists);
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 _data
)
public;
}
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor() public {
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool) {
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId) internal {
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
contract Governable {
event Pause();
event Unpause();
address public governor;
bool public paused = false;
constructor() public {
governor = msg.sender;
}
function setGovernor(address _gov) public onlyGovernor {
governor = _gov;
}
modifier onlyGovernor {
require(msg.sender == governor);
_;
}
/**
* @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() onlyGovernor whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyGovernor whenPaused public {
paused = false;
emit Unpause();
}
}
contract CardBase is Governable {
struct Card {
uint16 proto;
uint16 purity;
}
function getCard(uint id) public view returns (uint16 proto, uint16 purity) {
Card memory card = cards[id];
return (card.proto, card.purity);
}
function getShine(uint16 purity) public pure returns (uint8) {
return uint8(purity / 1000);
}
Card[] public cards;
}
contract CardProto is CardBase {
event NewProtoCard(
uint16 id, uint8 season, uint8 god,
Rarity rarity, uint8 mana, uint8 attack,
uint8 health, uint8 cardType, uint8 tribe, bool packable
);
struct Limit {
uint64 limit;
bool exists;
}
// limits for mythic cards
mapping(uint16 => Limit) public limits;
// can only set limits once
function setLimit(uint16 id, uint64 limit) public onlyGovernor {
Limit memory l = limits[id];
require(!l.exists);
limits[id] = Limit({
limit: limit,
exists: true
});
}
function getLimit(uint16 id) public view returns (uint64 limit, bool set) {
Limit memory l = limits[id];
return (l.limit, l.exists);
}
// could make these arrays to save gas
// not really necessary - will be update a very limited no of times
mapping(uint8 => bool) public seasonTradable;
mapping(uint8 => bool) public seasonTradabilityLocked;
uint8 public currentSeason;
function makeTradable(uint8 season) public onlyGovernor {
seasonTradable[season] = true;
}
function makeUntradable(uint8 season) public onlyGovernor {
require(!seasonTradabilityLocked[season]);
seasonTradable[season] = false;
}
function makePermanantlyTradable(uint8 season) public onlyGovernor {
require(seasonTradable[season]);
seasonTradabilityLocked[season] = true;
}
function isTradable(uint16 proto) public view returns (bool) {
return seasonTradable[protos[proto].season];
}
function nextSeason() public onlyGovernor {
//Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M
require(currentSeason <= 255);
currentSeason++;
mythic.length = 0;
legendary.length = 0;
epic.length = 0;
rare.length = 0;
common.length = 0;
}
enum Rarity {
Common,
Rare,
Epic,
Legendary,
Mythic
}
uint8 constant SPELL = 1;
uint8 constant MINION = 2;
uint8 constant WEAPON = 3;
uint8 constant HERO = 4;
struct ProtoCard {
bool exists;
uint8 god;
uint8 season;
uint8 cardType;
Rarity rarity;
uint8 mana;
uint8 attack;
uint8 health;
uint8 tribe;
}
// there is a particular design decision driving this:
// need to be able to iterate over mythics only for card generation
// don't store 5 different arrays: have to use 2 ids
// better to bear this cost (2 bytes per proto card)
// rather than 1 byte per instance
uint16 public protoCount;
mapping(uint16 => ProtoCard) protos;
uint16[] public mythic;
uint16[] public legendary;
uint16[] public epic;
uint16[] public rare;
uint16[] public common;
function addProtos(
uint16[] externalIDs, uint8[] gods, Rarity[] rarities, uint8[] manas, uint8[] attacks,
uint8[] healths, uint8[] cardTypes, uint8[] tribes, bool[] packable
) public onlyGovernor returns(uint16) {
for (uint i = 0; i < externalIDs.length; i++) {
ProtoCard memory card = ProtoCard({
exists: true,
god: gods[i],
season: currentSeason,
cardType: cardTypes[i],
rarity: rarities[i],
mana: manas[i],
attack: attacks[i],
health: healths[i],
tribe: tribes[i]
});
_addProto(externalIDs[i], card, packable[i]);
}
}
function addProto(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: cardType,
rarity: rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
_addProto(externalID, card, packable);
}
function addWeapon(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: WEAPON,
rarity: rarity,
mana: mana,
attack: attack,
health: durability,
tribe: 0
});
_addProto(externalID, card, packable);
}
function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: SPELL,
rarity: rarity,
mana: mana,
attack: 0,
health: 0,
tribe: 0
});
_addProto(externalID, card, packable);
}
function addMinion(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: MINION,
rarity: rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
_addProto(externalID, card, packable);
}
function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal {
require(!protos[externalID].exists);
card.exists = true;
protos[externalID] = card;
protoCount++;
emit NewProtoCard(
externalID, currentSeason, card.god,
card.rarity, card.mana, card.attack,
card.health, card.cardType, card.tribe, packable
);
if (packable) {
Rarity rarity = card.rarity;
if (rarity == Rarity.Common) {
common.push(externalID);
} else if (rarity == Rarity.Rare) {
rare.push(externalID);
} else if (rarity == Rarity.Epic) {
epic.push(externalID);
} else if (rarity == Rarity.Legendary) {
legendary.push(externalID);
} else if (rarity == Rarity.Mythic) {
mythic.push(externalID);
} else {
require(false);
}
}
}
function getProto(uint16 id) public view returns(
bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe
) {
ProtoCard memory proto = protos[id];
return (
proto.exists,
proto.god,
proto.season,
proto.cardType,
proto.rarity,
proto.mana,
proto.attack,
proto.health,
proto.tribe
);
}
function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) {
// modulo bias is fine - creates rarity tiers etc
// will obviously revert is there are no cards of that type: this is expected - should never happen
if (rarity == Rarity.Common) {
return common[random % common.length];
} else if (rarity == Rarity.Rare) {
return rare[random % rare.length];
} else if (rarity == Rarity.Epic) {
return epic[random % epic.length];
} else if (rarity == Rarity.Legendary) {
return legendary[random % legendary.length];
} else if (rarity == Rarity.Mythic) {
// make sure a mythic is available
uint16 id;
uint64 limit;
bool set;
for (uint i = 0; i < mythic.length; i++) {
id = mythic[(random + i) % mythic.length];
(limit, set) = getLimit(id);
if (set && limit > 0){
return id;
}
}
// if not, they get a legendary :(
return legendary[random % legendary.length];
}
require(false);
return 0;
}
// can never adjust tradable cards
// each season gets a 'balancing beta'
// totally immutable: season, rarity
function replaceProto(
uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe
) public onlyGovernor {
ProtoCard memory pc = protos[index];
require(!seasonTradable[pc.season]);
protos[index] = ProtoCard({
exists: true,
god: god,
season: pc.season,
cardType: cardType,
rarity: pc.rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
}
}
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. 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 contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC721BasicToken is CardProto, SupportsInterfaceWithLookup, ERC721Basic {
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
// mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256);
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addNewTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
function addNewTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
// ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
// ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `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 whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint i) internal pure returns (string) {
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 {
using Strings for string;
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/*** Constants ***/
// Configure these for your own deployment
string public constant NAME = "Gods Unchained";
string public constant SYMBOL = "GODS";
string public tokenMetadataBaseURI = "https://api.godsunchained.com/card/";
// Mapping from owner to list of owned token IDs
// EDITED: limit to 2^40 (around 1T)
mapping(address => uint40[]) internal ownedTokens;
uint32[] ownedTokensIndex;
/**
* @dev Constructor function
*/
constructor() public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return NAME;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return SYMBOL;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
return Strings.strConcat(
tokenMetadataBaseURI,
Strings.uint2str(_tokenId)
);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return cards.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return _index;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
// EDITED: prevent overflow
require(length == uint32(length));
ownedTokens[_to].push(uint40(_tokenId));
ownedTokensIndex[_tokenId] = uint32(length);
}
// EDITED
// have to have in order to use array rather than mapping
function addNewTokenTo(address _to, uint256 _tokenId) internal {
super.addNewTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
// EDITED: prevent overflow
require(length == uint32(length));
ownedTokens[_to].push(uint40(_tokenId));
ownedTokensIndex.push(uint32(length));
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint32 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint40 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Gets the balance of the specified address - overrriden from previous to save gas
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
return ownedTokens[_owner].length;
}
}
contract CardOwnershipTwo is ERC721Token {
uint public burnCount;
function getActiveCards() public view returns (uint) {
return totalSupply() - burnCount;
}
/**
* @param to : the address to which the card will be transferred
* @param id : the id of the card to be transferred
*/
function transfer(address to, uint id) public payable onlyOwnerOf(id) {
require(isTradable(cards[id].proto));
require(to != address(0));
_transfer(msg.sender, to, id);
}
function _transfer(address from, address to, uint id) internal {
clearApproval(from, id);
removeTokenFrom(from, id);
addTokenTo(to, id);
emit Transfer(from, to, id);
}
/**
* @param to : the address to which the cards will be transferred
* @param ids : the ids of the cards to be transferred
*/
function transferAll(address to, uint[] ids) public payable {
for (uint i = 0; i < ids.length; i++) {
transfer(to, ids[i]);
}
}
/**
* @param proposed : the claimed owner of the cards
* @param ids : the ids of the cards to check
* @return whether proposed owns all of the cards
*/
function ownsAll(address proposed, uint[] ids) public view returns (bool) {
require(ids.length > 0);
for (uint i = 0; i < ids.length; i++) {
if (!owns(proposed, ids[i])) {
return false;
}
}
return true;
}
/**
* @param proposed : the claimed owner of the card
* @param id : the id of the card to check
* @return whether proposed owns the card
*/
function owns(address proposed, uint id) public view returns (bool) {
return ownerOf(id) == proposed;
}
function burn(uint id) public onlyOwnerOf(id) {
burnCount++;
_burn(msg.sender, id);
}
/**
* @param ids : the indices of the tokens to burn
*/
function burnAll(uint[] ids) public {
for (uint i = 0; i < ids.length; i++){
burn(ids[i]);
}
}
/**
* @param to : the address to approve for transfer
* @param id : the index of the card to be approved
*/
function approve(address to, uint id) public {
require(isTradable(cards[id].proto));
super.approve(to, id);
}
/**
* @param to : the address to approve for transfer
* @param ids : the indices of the cards to be approved
*/
function approveAll(address to, uint[] ids) public {
for (uint i = 0; i < ids.length; i++) {
approve(to, ids[i]);
}
}
/**
* @param to : the address to which the token should be transferred
* @param id : the index of the token to transfer
*/
function transferFrom(address from, address to, uint id) public {
require(isTradable(cards[id].proto));
super.transferFrom(from, to, id);
}
/**
* @param to : the address to which the tokens should be transferred
* @param ids : the indices of the tokens to transfer
*/
function transferAllFrom(address from, address to, uint[] ids) public {
for (uint i = 0; i < ids.length; i++) {
transferFrom(from, to, ids[i]);
}
}
/**
* @return the number of cards which have been burned
*/
function getBurnCount() public view returns (uint) {
return burnCount;
}
}
contract CardIntegrationTwo is CardOwnershipTwo {
address[] public packs;
event CardCreated(uint indexed id, uint16 proto, uint16 purity, address owner);
function addPack(address approved) public onlyGovernor {
packs.push(approved);
}
modifier onlyApprovedPacks {
require(_isApprovedPack());
_;
}
function _isApprovedPack() private view returns (bool) {
for (uint i = 0; i < packs.length; i++) {
if (msg.sender == address(packs[i])) {
return true;
}
}
return false;
}
function createCard(address owner, uint16 proto, uint16 purity) public whenNotPaused onlyApprovedPacks returns (uint) {
ProtoCard memory card = protos[proto];
require(card.season == currentSeason);
if (card.rarity == Rarity.Mythic) {
uint64 limit;
bool exists;
(limit, exists) = getLimit(proto);
require(!exists || limit > 0);
limits[proto].limit--;
}
return _createCard(owner, proto, purity);
}
function _createCard(address owner, uint16 proto, uint16 purity) internal returns (uint) {
Card memory card = Card({
proto: proto,
purity: purity
});
uint id = cards.push(card) - 1;
_mint(owner, id);
emit CardCreated(id, proto, purity, owner);
return id;
}
/*function combineCards(uint[] ids) public whenNotPaused {
require(ids.length == 5);
require(ownsAll(msg.sender, ids));
Card memory first = cards[ids[0]];
uint16 proto = first.proto;
uint8 shine = _getShine(first.purity);
require(shine < shineLimit);
uint16 puritySum = first.purity - (shine * 1000);
burn(ids[0]);
for (uint i = 1; i < ids.length; i++) {
Card memory next = cards[ids[i]];
require(next.proto == proto);
require(_getShine(next.purity) == shine);
puritySum += (next.purity - (shine * 1000));
burn(ids[i]);
}
uint16 newPurity = uint16(((shine + 1) * 1000) + (puritySum / ids.length));
_createCard(msg.sender, proto, newPurity);
}*/
// PURITY NOTES
// currently, we only
// however, to protect rarity, you'll never be abl
// this is enforced by the restriction in the create-card function
// no cards above this point can be found in packs
}
contract PreviousInterface {
function ownerOf(uint id) public view returns (address);
function getCard(uint id) public view returns (uint16, uint16);
function totalSupply() public view returns (uint);
function burnCount() public view returns (uint);
}
contract CardMigration is CardIntegrationTwo {
constructor(PreviousInterface previous) public {
old = previous;
}
// use interface to lower deployment cost
PreviousInterface old;
mapping(uint => bool) public migrated;
function migrate(uint id) public {
require(!migrated[id]);
migrated[id] = true;
address owner = old.ownerOf(id);
uint16 proto;
uint16 purity;
(proto, purity) = old.getCard(id);
_createCard(owner, proto, purity);
}
function migrateAll(uint[] ids) public {
for (uint i = 0; i < ids.length; i++){
migrate(ids[i]);
}
}
} | * @dev Internal function to mint a new token Reverts if the given token ID already exists @param _to The address that will own the minted token @param _tokenId uint256 ID of the token to be minted by the msg.sender/ | function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addNewTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
| 6,500,506 | [
1,
3061,
445,
358,
312,
474,
279,
394,
1147,
868,
31537,
309,
326,
864,
1147,
1599,
1818,
1704,
225,
389,
869,
1021,
1758,
716,
903,
4953,
326,
312,
474,
329,
1147,
225,
389,
2316,
548,
2254,
5034,
1599,
434,
326,
1147,
358,
506,
312,
474,
329,
635,
326,
1234,
18,
15330,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
81,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
2316,
548,
13,
2713,
288,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
3639,
20973,
1345,
774,
24899,
869,
16,
389,
2316,
548,
1769,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
389,
869,
16,
389,
2316,
548,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.26;
import "../Universe.sol";
import "../Math.sol";
import "../VotingCenter/IVotingCenter.sol";
import "../VotingCenter/VotingProposal.sol";
import "./IEquityToken.sol";
import "../Deprecations/IEquityToken_v0.sol";
import "./ITokenholderRights.sol";
import "../ETO/IETOCommitment.sol";
library Gov {
////////////////////////
// Constants
////////////////////////
// no access to constants from library
// Voting Center keccak256("IVotingCenter")
bytes4 internal constant KNOWN_INTERFACE_VOTING_CENTER = 0xff5dbb18;
// allows to change known interfaces in universe kecckak256("UniverseManager")
bytes32 internal constant ROLE_UNIVERSE_MANAGER = 0xe8d8f8f9ea4b19a5a4368dbdace17ad71a69aadeb6250e54c7b4c7b446301738;
////////////////////////
// Types
////////////////////////
enum TokenVotingRule {
// nominee has no voting rights
NoVotingRights,
// nominee votes yes if token holders do not say otherwise
Positive,
// nominee votes against if token holders do not say otherwise
Negative,
// nominee passes the vote pro rata with share capital of token holders voting yes/no
Prorata
}
// defines state machine of the token controller which goes from I to T without loops
enum State {
Setup, // Initial state
Offering, // primary token offering in progress
Funded, // token offering succeeded, execution of shareholder rights possible
Closing, // company is being closed
Closed, // terminal state, company closed
Migrating, // contract is being migrated to new implementation
Migrated // terminal state, contract migrated
}
// governance actions available in setup state
enum SetupAction {
// no on-chain action on resolution, default bylaw with voting initative
None,
// start new token offering
RegisterOffer,
// for example off-chain investment (agreement url, new number of shares, new shareholder rights, new valuation eur, new authorized capital)
AmendGovernance
}
// general governance actions
/// @dev must start with SetupAction
enum Action {
None,
RegisterOffer,
AmendGovernance,
// no on-chain action on resolution, restricted act bylaw
RestrictedNone,
// general information from the company
CompanyNone,
// token holder resolution without on-chain action, with voting initative
THRNone,
// blocks transfers
StopToken,
// enables transfers
ContinueToken,
// requires change of control resolution/dissolution to be in executing state
// on entering executing state will stop token
// will be completed on payout of certain amount of nEUR
CloseToken,
OrdinaryPayout, // any scheduled or expected payout initiated by company legal rep
ExtraordinaryPayout, // a payout that requires resolution to pass
ChangeTokenController, // (new token controller)
// allocates tokens against shares that are transferred to nominee
// requires SHR
IssueTokensForExistingShares,
// transfers shares to particular investors, destroying equity tokens
// requires SHR
IssueSharesForExistingTokens,
ChangeNominee,
// results in issuance of new equity token and disbursing it to current token holders
// new sharews must be transferred to nominee
// additional conditions must apply in execution function for anti dilution to happen
AntiDilutionProtection,
EstablishAuthorizedCapital, // results in new amount of authorized capital
// requires new ESOP contract address with ESOP params and assigning authorized capital to pools
// existing authorized capital pool can be assigned then voting is not required
// same ESOP can be established - then pool will be increased
EstablishESOP,
// converts ESOP into equity token or an internal 'payout token', completed only when conversion is over
ConvertESOP,
// any change of control event, will result in company closing
// will create child resolutions for all tokens to be closed and ESOP to be converted
// drag along is mandatory, we do not support governance without it
ChangeOfControl,
// same as above, will close company when it's dissolved
DissolveCompany,
TagAlong, // equity token holders vote on tag along
// voting on yearly report, also Nominee may attend the meeting off-chain
AnnualGeneralMeeting,
// changes valuation and number of shares, initiated by company legal rep
// for example when note is converted after offering or when company wants to announce new official valuation
AmendSharesAndValuation,
// changes valuation, keeping number of shares
AmendValuation,
// a resolution that cancels another resolution, like calling off dividend payout or company closing
CancelResolution
}
// permissions required to execute an action
enum ActionEscalation {
// anyone can execute
Anyone,
// token holder can execute
TokenHolder,
// company legal rep
CompanyLegalRep,
Nominee,
CompanyOrNominee,
// requires escalation to all tokenholders
THR,
// requires escalation to all shareholders
SHR,
// requires parent resolution to be completed
ParentResolution
}
// legal representative of an action
enum ActionLegalRep {
// trustless action
None,
// represented off-chain by company
CompanyLegalRep,
// represented off-chain by nominee
Nominee
}
// 56 bit length
struct ActionBylaw {
// permission level (any token holder, company legal rep, nominee, company or legal rep, token holders, share holders, parent resolution)
ActionEscalation escalationLevel;
// voting period in seconds
uint8 votingPeriodDays;
// voting rule for shareholders is always prorata to voting capital
// voting quorum percent, equals minimal voting power cast to total voting power for vote to count (50 for 50%)
uint8 votingQuorumPercent;
// absolute majority percent, more than this % of votes cast is required for resolution to pass (50 for 50%)
uint8 votingMajorityPercent;
// majority voting power - specific voting power required to pass
// if not 0 voting quorum and majority will be ignored
uint8 absoluteMajorityPercent;
// voting rule for token holders
// absolute majority (veto power) or prorata
TokenVotingRule votingRule;
// off chain rep of the voting (none, nominee, company legal rep)
ActionLegalRep votingLegalRepresentative;
// initiator of the voting
ActionLegalRep votingInitiator;
// resolution initiative for token holders
bool withTokenholderResolutionInitiative;
}
enum TokenType {
None, // there's no goverance token
Equity, // equity token
Safe // SAFE-based convertible note
}
enum TokenState {
Open, // token is open and may be transferred if controller permits
Closing, // token is being closed or converted, transfers are disabled
Closed // token is irreversibly closed and all rights are migrated or void
}
enum ExecutionState {
New,
// permissions are being escalated ie. voting in progress
Escalating,
// permission escalation failed
Rejected,
// resolution in progress
Executing,
// resolution was cancelled ie. due to timeout
Cancelled,
// resolution execution failed ie. ETO refunded
Failed,
// resolution execution OK
Completed
}
struct ResolutionExecution {
// payload promise
bytes32 promise; // 256 bits
// next WORD
// failed code which is keccak of revert code from validator
bytes32 failedCode;
// next WORD
// payload that is free to use and will be migrated with resolution
bytes32 payload;
// next WORD
// initial action being executed
uint8 action; // 8-bit
// state of the execution
ExecutionState state; // 8-bit
// resolution started
uint32 startedAt; // 32-bit
// resolution finished
uint32 finishedAt; // 32-bit
// resolution deadline
uint32 cancelAt; // 32-bit
// execution next step
uint8 nextStep; // 8-bit
// reserved
// resolution deadline
// child executions
}
////////////////////////
// Storages
////////////////////////
// governance engine storage
struct GovernanceStorage {
// a root of trust contract
Universe UNIVERSE;
// company representative address
address COMPANY_LEGAL_REPRESENTATIVE;
// controller lifecycle state
State _state;
// resolutions being executed
mapping (bytes32 => ResolutionExecution) _resolutions;
bytes32[] _resolutionIds;
}
// single token storage
struct TokenStorage {
// type of a token
TokenType _type;
// state of a token
TokenState _state;
// is token transferable
bool _transferable;
// address of a token
IControlledToken _token;
// set of equity token rights associated with the token
ITokenholderRights _tokenholderRights;
// nominee address
address _nominee;
// quantum in which token may be created and destroyed, typically tokens per share
uint256 _quantumUlps;
// total voting power expressed in tokens, typically computed from shared capital
uint256 _totalVotingPower;
}
///////////////////////////
// Delegate Library Methods
///////////////////////////
// used by governance engine to advance resolution from New -> Escalating -> Executing state
function startResolutionExecution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
public
returns (ExecutionState prevState, ExecutionState nextState)
{
// executor checks resolutionId state
ResolutionExecution storage e = g._resolutions[resolutionId];
prevState = e.state;
require(prevState == ExecutionState.New || prevState == ExecutionState.Escalating);
// save new state which may be Executing or Escalating
if (prevState == ExecutionState.New) {
// try to escalate to execution state
if (g._state == State.Setup) {
// in setup we suport a subset of Actions
nextState = escalateNewResolutionInSetup(g, SetupAction(action));
} else {
nextState = escalateNewResolution(g, t, resolutionId, action, payload);
}
// if New is returned, voting will be in campaign state and must be escalated further
// for resolution to be created
if (nextState == ExecutionState.New) {
return;
}
// escalator may deny access to action
require(nextState != ExecutionState.Rejected, "NF_GOV_EXEC_ACCESS_DENIED");
// save new execution
e.action = action;
e.state = nextState;
e.startedAt = uint32(now);
// use calldata as promise
e.promise = keccak256(payload);
// we should use tx.hash as resolutionId, it's however not available in EVM
// that could give us access to msg.data at all times making subsequenct calls to
// push execution forward easier
g._resolutionIds.push(resolutionId);
} else {
// must be escalating: check voting results in voting center
IVotingCenter vc = getVotingCenter(g.UNIVERSE);
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
nextState = evaluateProposal(vc, resolutionId, bylaw);
// write executing/rejected state
e.state = nextState;
if (nextState == ExecutionState.Rejected) {
// emit event in caller
e.finishedAt = uint32(now);
}
}
}
function hasProposalPassed(TokenStorage storage t, IVotingCenter vc, bytes32 resolutionId)
public
constant
returns (ExecutionState state)
{
(uint8 s,,,,,,,uint256 action,,,) = vc.timedProposal(resolutionId);
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(uint8(action)));
require(s == uint8(VotingProposal.State.Final), "NF_GOV_VOTING_NOT_FINAL");
return hasProposalPassed(vc, resolutionId, bylaw);
}
// validates new offering that starts in token offering module
function validateNewOffering(address company, IControlledToken token, IETOCommitment tokenOffering)
public
constant
{
IEquityToken equityToken = tokenOffering.equityToken();
// require nominee match and agreement signature
(address nomineeToken,,,) = equityToken.currentAgreement();
// require token controller match
require(equityToken.tokenController() == address(this));
// require nominee and agreement match
(address nomineOffering,,,) = tokenOffering.currentAgreement();
require(nomineOffering == nomineeToken, "NF_NDT_NOMINEE_MISMATCH");
// require terms set and legalRep match
require(tokenOffering.etoTerms() != address(0), "NF_NDT_NO_TERMS");
require(tokenOffering.companyLegalRep() == company, "NF_NDT_COMPANY_MISMATCH");
// secondary offering must be on the same token
require(token == address(0) || equityToken == token, "NF_NDT_FUNDRAISE_NOT_SAME_TOKEN");
}
function installTokenFromETO(TokenStorage storage t, IETOCommitment tokenOffering)
public
{
// get token data and put into the storage
IEquityToken equityToken = tokenOffering.equityToken();
ITokenholderRights tokenholderRights = tokenOffering.etoTerms().TOKENHOLDER_RIGHTS();
bool transferable = tokenOffering.etoTerms().ENABLE_TRANSFERS_ON_SUCCESS();
setToken(t, equityToken, TokenType.Equity, TokenState.Open, tokenholderRights, transferable);
}
function calculateNewValuationAndInstallToken(TokenStorage storage t, IETOCommitment tokenOffering)
public
returns (
uint256 newShares,
uint256 authorizedCapitalUlps,
uint256 increasedShareCapital,
uint256 increasedValuationEurUlps,
string ISHAUrl
)
{
installTokenFromETO(t, tokenOffering);
return calculateNewValuation(tokenOffering);
}
//////////////////////////////
// Internal Library Methods
//////////////////////////////
function promiseForSelector(bytes4 selector)
internal
pure
returns (bytes32)
{
// replace selector and return keccak
bytes memory calldata = msg.data;
assembly {
// patch calldata with the selector
mstore8(add(calldata, 32), byte(0, selector))
mstore8(add(calldata, 33), byte(1, selector))
mstore8(add(calldata, 34), byte(2, selector))
mstore8(add(calldata, 35), byte(3, selector))
}
return keccak256(calldata);
}
function deserializeBylaw(uint56 bylaw)
internal
pure
returns (ActionBylaw memory decodedBylaw)
{
// up to solidity 0.4.26 struct memory layout is unpacked, where every element
// of the struct occupies at least single word, also verified with v 0.6
// so struct memory layout seems pretty stable, anyway we run a few tests on it
assembly {
// from 0 to 7
for { let i := 0 } lt(i, 7) { i := add(i, 1) }
// store a byte 32 - i into 32 byte offset with number i, starting from decodedBylaw
// mind that uint56 is internal Solidity construct, it occupies whole word (see `byte`)
{ mstore(add(decodedBylaw, mul(32,i)), byte(add(25, i), bylaw)) }
// 6th element contains 3 flags encoded that describe voting rights
let vrules := mload(add(decodedBylaw, 192))
// set voting initator
mstore(add(decodedBylaw, 224), div(and(vrules, 0x38), 8))
// set initiative flag
mstore(add(decodedBylaw, 256), div(and(vrules, 0x40), 64))
// set voting legal rep
mstore(add(decodedBylaw, 192), and(vrules, 7))
}
}
function setToken(
TokenStorage storage t,
IControlledToken token,
TokenType tokenType,
TokenState state,
ITokenholderRights rights,
bool transfersEnabled
)
internal
{
t._type = tokenType;
t._state = state;
t._transferable = transfersEnabled;
t._token = token;
t._tokenholderRights = rights;
if (tokenType == TokenType.Equity) {
setAdditionalEquityTokenData(t, IEquityToken(token));
}
}
function setAdditionalEquityTokenData(TokenStorage storage t, IEquityToken token)
internal
{
t._nominee = getNominee(token);
t._quantumUlps = token.tokensPerShare();
}
function setEquityTokenTotalVotingPower(TokenStorage storage t, IEquityToken token, uint256 shareCapital)
internal
{
(,uint256 version) = token.contractId();
if (version > 0) {
t._totalVotingPower = t._quantumUlps * shareCapital / token.shareNominalValueUlps();
} else {
t._totalVotingPower = t._quantumUlps * shareCapital / IEquityToken_v0(token).shareNominalValueEurUlps();
}
}
////////////////////////
// Private Methods
////////////////////////
function calculateNewValuation(IETOCommitment tokenOffering)
private
constant
returns (
uint256 newShares,
uint256 authorizedCapitalUlps,
uint256 increasedShareCapital,
uint256 increasedValuationEurUlps,
string ISHAUrl
)
{
// get ISHA amendment
ETOTerms etoTerms = tokenOffering.etoTerms();
// execute pending resolutions on completed ETO
(newShares, increasedShareCapital,,,,,,) = tokenOffering.contributionSummary();
// compute increased share capital (in ISHA currency!)
increasedShareCapital = etoTerms.EXISTING_SHARE_CAPITAL() + increasedShareCapital;
// use full price of a share as a marginal price from which to compute valuation
uint256 marginalSharePrice = etoTerms.TOKEN_TERMS().SHARE_PRICE_EUR_ULPS();
// compute new valuation by having market price for a single unit of ISHA currency
// (share_price_eur / share_nominal_value_curr) * increased_share_capital_curr
uint256 shareNominalValueUlps = etoTerms.TOKEN_TERMS().SHARE_NOMINAL_VALUE_ULPS();
increasedValuationEurUlps = Math.proportion(marginalSharePrice, increasedShareCapital, shareNominalValueUlps);
ISHAUrl = tokenOffering.signedInvestmentAgreementUrl();
authorizedCapitalUlps = etoTerms.AUTHORIZED_CAPITAL();
}
function isTokenHolder(IControlledToken token, address owner)
private
constant
returns (bool)
{
return token.balanceOf(owner) > 0;
}
function getNominee(IEquityToken token)
private
constant
returns (address)
{
// return zero address for nominee if token does not exist
return token == address(0) ? address(0) : token.nominee();
}
function getActionLegalRep(ActionLegalRep rep, address company, address nominee)
private
pure
returns (address)
{
if (rep == ActionLegalRep.CompanyLegalRep) {
return company;
} else if (rep == ActionLegalRep.Nominee) {
return nominee;
}
return address(0);
}
function requiresVoting(ActionEscalation escalationLevel)
private
pure
returns (bool)
{
return escalationLevel == ActionEscalation.SHR || escalationLevel == ActionEscalation.THR;
}
// figure out what right initator has for given escalation level in bylaw of particular action
function getNonVotingBylawEscalation(
ActionEscalation escalationLevel,
address initiator,
IControlledToken token,
address company,
address nominee
)
private
constant
returns (ExecutionState s)
{
if (escalationLevel == ActionEscalation.Anyone) {
s = ExecutionState.Executing;
} else if (escalationLevel == ActionEscalation.TokenHolder) {
// must be a relevant token holder
s = isTokenHolder(token, initiator) ? ExecutionState.Executing : ExecutionState.Rejected;
} else if (escalationLevel == ActionEscalation.CompanyLegalRep) {
s = initiator == company ? ExecutionState.Executing : ExecutionState.Rejected;
} else if (escalationLevel == ActionEscalation.Nominee) {
// for tokens without nominee this will be always rejected
s = initiator == nominee ? ExecutionState.Executing : ExecutionState.Rejected;
} else if (escalationLevel == ActionEscalation.CompanyOrNominee) {
s = initiator == company ? ExecutionState.Executing : ExecutionState.Rejected;
if (s == ExecutionState.Rejected) {
s = initiator == nominee ? ExecutionState.Executing : ExecutionState.Rejected;
}
} else {
revert();
}
}
function getVotingBylawEscalation(
TokenVotingRule votingRule,
ActionLegalRep votingInitiator,
address initiator,
IControlledToken token,
address company,
address nominee,
bool tokenholderInitiative
)
private
constant
returns (ExecutionState s)
{
address expectedInitator = getActionLegalRep(votingInitiator, company, nominee);
if (votingRule == TokenVotingRule.NoVotingRights) {
// if token holders do not have voting rights, voting initator may execute action
s = initiator == expectedInitator ? ExecutionState.Executing : ExecutionState.Rejected;
} else {
require(address(token) != address(0), "NF_GOV_NO_GOVERNANCE_TOKEN");
if (initiator == expectedInitator) {
// voting initator may start voting
s = ExecutionState.Escalating;
} else {
// token holders have resolution initative
if (tokenholderInitiative && isTokenHolder(token, initiator)) {
// return New to indicate Campaign voting
s = ExecutionState.New;
} else {
s = ExecutionState.Rejected;
}
}
}
}
function escalateNewResolutionInSetup(GovernanceStorage storage g, SetupAction action)
private
returns (ExecutionState)
{
address companyLegalRep = g.COMPANY_LEGAL_REPRESENTATIVE;
// may be called only in New state
if (action == SetupAction.RegisterOffer && (msg.sender == companyLegalRep || isUniverseManager(g.UNIVERSE, msg.sender))) {
// anyone can register a legitimate offering in setup state
return ExecutionState.Executing;
} else if (action == SetupAction.AmendGovernance && msg.sender == companyLegalRep) {
// company can start company governance with ISHA
return ExecutionState.Executing;
}
// any other action type will be rejected
return ExecutionState.Rejected;
}
// defines permission escalation for resolution. based on resolution state, action and current shareholder rights
// allows, escalates or denies execution.
function escalateNewResolution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
private
returns (ExecutionState s)
{
// may be called only in New state
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
IVotingCenter vc;
if (requiresVoting(bylaw.escalationLevel)) {
// check if voting in voting center even if New state to handle voting in Campaign state
if (bylaw.withTokenholderResolutionInitiative) {
// if voting is finalized evaluate results against bylaw
vc = getVotingCenter(g.UNIVERSE);
if (vc.hasProposal(resolutionId)) {
return evaluateProposal(vc, resolutionId, bylaw);
}
}
// there's no voting going on - do usual escalation
s = getVotingBylawEscalation(
bylaw.votingRule,
bylaw.votingInitiator,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee,
bylaw.withTokenholderResolutionInitiative
);
address votingLegalRep;
if (s == ExecutionState.Escalating) {
// start voting in public phase
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
if (s == ExecutionState.New) {
// start voting in campaign state
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openCampaignProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
} else {
s = getNonVotingBylawEscalation(
bylaw.escalationLevel,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee
);
}
}
function openProposal(
TokenStorage storage t,
IVotingCenter vc,
bytes32 resolutionId,
uint8 action,
bytes payload,
address votingLegalRep,
ActionBylaw memory bylaw
)
private
{
vc.addProposal(
resolutionId,
t._token,
0,
0,
bylaw.votingPeriodDays * 1 days,
votingLegalRep,
votingLegalRep != address(0) ? uint32(bylaw.votingPeriodDays * 1 days) : 0,
votingLegalRep != address(0) ? t._totalVotingPower : 0,
uint256(action),
payload,
false
);
}
function openCampaignProposal(
TokenStorage storage t,
IVotingCenter vc,
bytes32 resolutionId,
uint8 action,
bytes payload,
address votingLegalRep,
ActionBylaw memory bylaw
)
private
{
vc.addProposal(
resolutionId,
t._token,
bylaw.votingPeriodDays * 1 days,
votingInitativeThresholdFrac(bylaw),
2 * bylaw.votingPeriodDays * 1 days,
votingLegalRep,
votingLegalRep != address(0) ? uint32(bylaw.votingPeriodDays * 1 days) : 0,
votingLegalRep != address(0) ? t._totalVotingPower : 0,
uint256(action),
payload,
false
);
}
function evaluateProposal(IVotingCenter vc, bytes32 resolutionId, ActionBylaw memory bylaw)
private
constant
returns (ExecutionState state)
{
(
uint8 s,
uint256 inFavor,
uint256 against,
,
,
,
,
uint256 campaignQuorumTokenAmount,
,
) = vc.tally(resolutionId);
if (s == uint8(VotingProposal.State.Campaigning)) {
// still new
return ExecutionState.New;
} else if (s == uint8(VotingProposal.State.Final)) {
// make sure that campaign quorum was crossed
if (campaignQuorumTokenAmount > 0 && campaignQuorumTokenAmount > inFavor + against) {
return ExecutionState.Rejected;
}
// in final state use tally to check if proposal passed
return hasProposalPassed(vc, resolutionId, bylaw);
} else {
return ExecutionState.Escalating;
}
}
function hasProposalPassed(IVotingCenter vc, bytes32 resolutionId, ActionBylaw memory bylaw)
private
constant
returns (ExecutionState state)
{
// we call tally again because of stack too deep which could not be avoided
// without making structure of calls worse (at least for now)
(
,
uint256 inFavor,
uint256 against,
uint256 offchainInFavor,
uint256 offchainAgainst,
uint256 tokenVotingPower,
uint256 totalVotingPower,
,
,
) = vc.tally(resolutionId);
return hasProposalPassed(inFavor, against, offchainInFavor, offchainAgainst, tokenVotingPower, totalVotingPower, bylaw);
}
function hasProposalPassed(
uint256 inFavor,
uint256 against,
uint256 offchainInFavor,
uint256 offchainAgainst,
uint256 tokenVotingPower,
uint256 totalVotingPower,
ActionBylaw memory bylaw
)
internal
pure
returns (ExecutionState state)
{
uint256 pro;
uint256 contra;
// assign token voting according to voting rule
if (bylaw.votingRule == TokenVotingRule.Positive) {
// absolute majority of token voting power must be no, otherwise whole token voting power yes
if (2 * against > tokenVotingPower) {
contra = tokenVotingPower;
} else {
pro = tokenVotingPower;
}
} else if (bylaw.votingRule == TokenVotingRule.Negative) {
// absolute majority of token voting power must be yes, otherwise whole token voting power no
if (2 * inFavor > tokenVotingPower) {
pro = tokenVotingPower;
} else {
contra = tokenVotingPower;
}
} else if (bylaw.votingRule == TokenVotingRule.Prorata) {
// classical tally
pro = inFavor;
contra = against;
}
// absolute majority procedure
if (bylaw.absoluteMajorityPercent > 0) {
uint256 absoluteMajorityFrac = percentToFrac(bylaw.absoluteMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalVotingPower > absoluteMajorityFrac) {
return ExecutionState.Executing;
} else {
return ExecutionState.Rejected;
}
}
// quorum + majority procedure
uint256 quorumFrac = percentToFrac(bylaw.votingQuorumPercent);
uint256 totalPowerCast = pro + contra + offchainInFavor + offchainAgainst;
/// must have quorum at minimum
if (Math.mul(totalPowerCast, 10**18) / totalVotingPower >= quorumFrac) {
uint256 majorityFrac = percentToFrac(bylaw.votingMajorityPercent);
// must have more than majority (simple majority)
if (Math.mul(pro + offchainInFavor, 10**18) / totalPowerCast > majorityFrac) {
return ExecutionState.Executing;
} else {
return ExecutionState.Rejected;
}
} else {
return ExecutionState.Rejected;
}
}
function campaignQuorumPassed(IVotingCenter vc, bytes32 resolutionId, uint256 actualVotingPower)
private
constant
returns (bool)
{
(,,,,,uint256 campaignQuorumTokenAmount,,,,,) = vc.proposal(resolutionId);
return actualVotingPower >= campaignQuorumTokenAmount;
}
/// @notice converts percent encoded as integer binary without any scale into
/// standard decimal fraction
function percentToFrac(uint8 percent)
private
pure
returns (uint256)
{
// 100% is Q18
return 10**16 * uint256(percent);
}
/// @notice computes minimum absolute majority to pass decision which is simple majority of the quorum
function votingInitativeThresholdFrac(ActionBylaw memory bylaw)
private
pure
returns (uint256)
{
// TODO: tokenholder voting initative should be part of the bylaw, in case of absoluteMajorityPercent present
// value of 0 will be returned (providing votingQuorumPercent and votingMajorityPercent are 0) and campaign will fail
// as we go from uint8 this will never overflow
return percentToFrac(bylaw.votingQuorumPercent) * percentToFrac(bylaw.votingMajorityPercent) / 10**18;
}
function getVotingCenter(Universe u)
private
constant
returns (IVotingCenter)
{
return IVotingCenter(u.getSingleton(KNOWN_INTERFACE_VOTING_CENTER));
}
function isUniverseManager(Universe u, address sender)
private
returns (bool)
{
return u.accessPolicy().allowed(sender, ROLE_UNIVERSE_MANAGER, address(u), msg.sig);
}
}
| Constants no access to constants from library Voting Center keccak256("IVotingCenter") allows to change known interfaces in universe kecckak256("UniverseManager") Types | library Gov {
bytes4 internal constant KNOWN_INTERFACE_VOTING_CENTER = 0xff5dbb18;
bytes32 internal constant ROLE_UNIVERSE_MANAGER = 0xe8d8f8f9ea4b19a5a4368dbdace17ad71a69aadeb6250e54c7b4c7b446301738;
enum TokenVotingRule {
NoVotingRights,
Positive,
Negative,
Prorata
}
enum State {
}
enum SetupAction {
None,
RegisterOffer,
AmendGovernance
}
enum Action {
None,
RegisterOffer,
AmendGovernance,
RestrictedNone,
CompanyNone,
THRNone,
StopToken,
ContinueToken,
CloseToken,
IssueTokensForExistingShares,
IssueSharesForExistingTokens,
ChangeNominee,
AntiDilutionProtection,
EstablishESOP,
ConvertESOP,
ChangeOfControl,
DissolveCompany,
AnnualGeneralMeeting,
AmendSharesAndValuation,
AmendValuation,
CancelResolution
}
enum ActionEscalation {
Anyone,
TokenHolder,
CompanyLegalRep,
Nominee,
CompanyOrNominee,
THR,
SHR,
ParentResolution
}
enum ActionLegalRep {
None,
CompanyLegalRep,
Nominee
}
struct ActionBylaw {
ActionEscalation escalationLevel;
uint8 votingPeriodDays;
uint8 votingQuorumPercent;
uint8 votingMajorityPercent;
uint8 absoluteMajorityPercent;
TokenVotingRule votingRule;
ActionLegalRep votingLegalRepresentative;
ActionLegalRep votingInitiator;
bool withTokenholderResolutionInitiative;
}
enum TokenType {
}
enum TokenState {
}
enum ExecutionState {
New,
Escalating,
Rejected,
Executing,
Cancelled,
Failed,
Completed
}
struct ResolutionExecution {
bytes32 failedCode;
bytes32 payload;
}
struct GovernanceStorage {
Universe UNIVERSE;
address COMPANY_LEGAL_REPRESENTATIVE;
State _state;
mapping (bytes32 => ResolutionExecution) _resolutions;
bytes32[] _resolutionIds;
}
struct TokenStorage {
TokenType _type;
TokenState _state;
bool _transferable;
IControlledToken _token;
ITokenholderRights _tokenholderRights;
address _nominee;
uint256 _quantumUlps;
uint256 _totalVotingPower;
}
function startResolutionExecution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
public
returns (ExecutionState prevState, ExecutionState nextState)
{
ResolutionExecution storage e = g._resolutions[resolutionId];
prevState = e.state;
require(prevState == ExecutionState.New || prevState == ExecutionState.Escalating);
if (prevState == ExecutionState.New) {
if (g._state == State.Setup) {
nextState = escalateNewResolutionInSetup(g, SetupAction(action));
nextState = escalateNewResolution(g, t, resolutionId, action, payload);
}
if (nextState == ExecutionState.New) {
return;
}
e.state = nextState;
e.startedAt = uint32(now);
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
nextState = evaluateProposal(vc, resolutionId, bylaw);
if (nextState == ExecutionState.Rejected) {
e.finishedAt = uint32(now);
}
}
}
function startResolutionExecution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
public
returns (ExecutionState prevState, ExecutionState nextState)
{
ResolutionExecution storage e = g._resolutions[resolutionId];
prevState = e.state;
require(prevState == ExecutionState.New || prevState == ExecutionState.Escalating);
if (prevState == ExecutionState.New) {
if (g._state == State.Setup) {
nextState = escalateNewResolutionInSetup(g, SetupAction(action));
nextState = escalateNewResolution(g, t, resolutionId, action, payload);
}
if (nextState == ExecutionState.New) {
return;
}
e.state = nextState;
e.startedAt = uint32(now);
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
nextState = evaluateProposal(vc, resolutionId, bylaw);
if (nextState == ExecutionState.Rejected) {
e.finishedAt = uint32(now);
}
}
}
function startResolutionExecution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
public
returns (ExecutionState prevState, ExecutionState nextState)
{
ResolutionExecution storage e = g._resolutions[resolutionId];
prevState = e.state;
require(prevState == ExecutionState.New || prevState == ExecutionState.Escalating);
if (prevState == ExecutionState.New) {
if (g._state == State.Setup) {
nextState = escalateNewResolutionInSetup(g, SetupAction(action));
nextState = escalateNewResolution(g, t, resolutionId, action, payload);
}
if (nextState == ExecutionState.New) {
return;
}
e.state = nextState;
e.startedAt = uint32(now);
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
nextState = evaluateProposal(vc, resolutionId, bylaw);
if (nextState == ExecutionState.Rejected) {
e.finishedAt = uint32(now);
}
}
}
} else {
function startResolutionExecution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
public
returns (ExecutionState prevState, ExecutionState nextState)
{
ResolutionExecution storage e = g._resolutions[resolutionId];
prevState = e.state;
require(prevState == ExecutionState.New || prevState == ExecutionState.Escalating);
if (prevState == ExecutionState.New) {
if (g._state == State.Setup) {
nextState = escalateNewResolutionInSetup(g, SetupAction(action));
nextState = escalateNewResolution(g, t, resolutionId, action, payload);
}
if (nextState == ExecutionState.New) {
return;
}
e.state = nextState;
e.startedAt = uint32(now);
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
nextState = evaluateProposal(vc, resolutionId, bylaw);
if (nextState == ExecutionState.Rejected) {
e.finishedAt = uint32(now);
}
}
}
require(nextState != ExecutionState.Rejected, "NF_GOV_EXEC_ACCESS_DENIED");
e.action = action;
e.promise = keccak256(payload);
g._resolutionIds.push(resolutionId);
} else {
IVotingCenter vc = getVotingCenter(g.UNIVERSE);
e.state = nextState;
function startResolutionExecution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
public
returns (ExecutionState prevState, ExecutionState nextState)
{
ResolutionExecution storage e = g._resolutions[resolutionId];
prevState = e.state;
require(prevState == ExecutionState.New || prevState == ExecutionState.Escalating);
if (prevState == ExecutionState.New) {
if (g._state == State.Setup) {
nextState = escalateNewResolutionInSetup(g, SetupAction(action));
nextState = escalateNewResolution(g, t, resolutionId, action, payload);
}
if (nextState == ExecutionState.New) {
return;
}
e.state = nextState;
e.startedAt = uint32(now);
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
nextState = evaluateProposal(vc, resolutionId, bylaw);
if (nextState == ExecutionState.Rejected) {
e.finishedAt = uint32(now);
}
}
}
function hasProposalPassed(TokenStorage storage t, IVotingCenter vc, bytes32 resolutionId)
public
constant
returns (ExecutionState state)
{
(uint8 s,,,,,,,uint256 action,,,) = vc.timedProposal(resolutionId);
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(uint8(action)));
require(s == uint8(VotingProposal.State.Final), "NF_GOV_VOTING_NOT_FINAL");
return hasProposalPassed(vc, resolutionId, bylaw);
}
function validateNewOffering(address company, IControlledToken token, IETOCommitment tokenOffering)
public
constant
{
IEquityToken equityToken = tokenOffering.equityToken();
(address nomineeToken,,,) = equityToken.currentAgreement();
require(equityToken.tokenController() == address(this));
(address nomineOffering,,,) = tokenOffering.currentAgreement();
require(nomineOffering == nomineeToken, "NF_NDT_NOMINEE_MISMATCH");
require(tokenOffering.etoTerms() != address(0), "NF_NDT_NO_TERMS");
require(tokenOffering.companyLegalRep() == company, "NF_NDT_COMPANY_MISMATCH");
require(token == address(0) || equityToken == token, "NF_NDT_FUNDRAISE_NOT_SAME_TOKEN");
}
function installTokenFromETO(TokenStorage storage t, IETOCommitment tokenOffering)
public
{
IEquityToken equityToken = tokenOffering.equityToken();
ITokenholderRights tokenholderRights = tokenOffering.etoTerms().TOKENHOLDER_RIGHTS();
bool transferable = tokenOffering.etoTerms().ENABLE_TRANSFERS_ON_SUCCESS();
setToken(t, equityToken, TokenType.Equity, TokenState.Open, tokenholderRights, transferable);
}
function calculateNewValuationAndInstallToken(TokenStorage storage t, IETOCommitment tokenOffering)
public
returns (
uint256 newShares,
uint256 authorizedCapitalUlps,
uint256 increasedShareCapital,
uint256 increasedValuationEurUlps,
string ISHAUrl
)
{
installTokenFromETO(t, tokenOffering);
return calculateNewValuation(tokenOffering);
}
function promiseForSelector(bytes4 selector)
internal
pure
returns (bytes32)
{
bytes memory calldata = msg.data;
assembly {
mstore8(add(calldata, 32), byte(0, selector))
mstore8(add(calldata, 33), byte(1, selector))
mstore8(add(calldata, 34), byte(2, selector))
mstore8(add(calldata, 35), byte(3, selector))
}
return keccak256(calldata);
}
function promiseForSelector(bytes4 selector)
internal
pure
returns (bytes32)
{
bytes memory calldata = msg.data;
assembly {
mstore8(add(calldata, 32), byte(0, selector))
mstore8(add(calldata, 33), byte(1, selector))
mstore8(add(calldata, 34), byte(2, selector))
mstore8(add(calldata, 35), byte(3, selector))
}
return keccak256(calldata);
}
function deserializeBylaw(uint56 bylaw)
internal
pure
returns (ActionBylaw memory decodedBylaw)
{
assembly {
let vrules := mload(add(decodedBylaw, 192))
mstore(add(decodedBylaw, 224), div(and(vrules, 0x38), 8))
mstore(add(decodedBylaw, 256), div(and(vrules, 0x40), 64))
mstore(add(decodedBylaw, 192), and(vrules, 7))
}
}
function deserializeBylaw(uint56 bylaw)
internal
pure
returns (ActionBylaw memory decodedBylaw)
{
assembly {
let vrules := mload(add(decodedBylaw, 192))
mstore(add(decodedBylaw, 224), div(and(vrules, 0x38), 8))
mstore(add(decodedBylaw, 256), div(and(vrules, 0x40), 64))
mstore(add(decodedBylaw, 192), and(vrules, 7))
}
}
for { let i := 0 } lt(i, 7) { i := add(i, 1) }
{ mstore(add(decodedBylaw, mul(32,i)), byte(add(25, i), bylaw)) }
function setToken(
TokenStorage storage t,
IControlledToken token,
TokenType tokenType,
TokenState state,
ITokenholderRights rights,
bool transfersEnabled
)
internal
{
t._type = tokenType;
t._state = state;
t._transferable = transfersEnabled;
t._token = token;
t._tokenholderRights = rights;
if (tokenType == TokenType.Equity) {
setAdditionalEquityTokenData(t, IEquityToken(token));
}
}
function setToken(
TokenStorage storage t,
IControlledToken token,
TokenType tokenType,
TokenState state,
ITokenholderRights rights,
bool transfersEnabled
)
internal
{
t._type = tokenType;
t._state = state;
t._transferable = transfersEnabled;
t._token = token;
t._tokenholderRights = rights;
if (tokenType == TokenType.Equity) {
setAdditionalEquityTokenData(t, IEquityToken(token));
}
}
function setAdditionalEquityTokenData(TokenStorage storage t, IEquityToken token)
internal
{
t._nominee = getNominee(token);
t._quantumUlps = token.tokensPerShare();
}
function setEquityTokenTotalVotingPower(TokenStorage storage t, IEquityToken token, uint256 shareCapital)
internal
{
(,uint256 version) = token.contractId();
if (version > 0) {
t._totalVotingPower = t._quantumUlps * shareCapital / token.shareNominalValueUlps();
t._totalVotingPower = t._quantumUlps * shareCapital / IEquityToken_v0(token).shareNominalValueEurUlps();
}
}
function setEquityTokenTotalVotingPower(TokenStorage storage t, IEquityToken token, uint256 shareCapital)
internal
{
(,uint256 version) = token.contractId();
if (version > 0) {
t._totalVotingPower = t._quantumUlps * shareCapital / token.shareNominalValueUlps();
t._totalVotingPower = t._quantumUlps * shareCapital / IEquityToken_v0(token).shareNominalValueEurUlps();
}
}
} else {
function calculateNewValuation(IETOCommitment tokenOffering)
private
constant
returns (
uint256 newShares,
uint256 authorizedCapitalUlps,
uint256 increasedShareCapital,
uint256 increasedValuationEurUlps,
string ISHAUrl
)
{
ETOTerms etoTerms = tokenOffering.etoTerms();
(newShares, increasedShareCapital,,,,,,) = tokenOffering.contributionSummary();
increasedShareCapital = etoTerms.EXISTING_SHARE_CAPITAL() + increasedShareCapital;
uint256 marginalSharePrice = etoTerms.TOKEN_TERMS().SHARE_PRICE_EUR_ULPS();
uint256 shareNominalValueUlps = etoTerms.TOKEN_TERMS().SHARE_NOMINAL_VALUE_ULPS();
increasedValuationEurUlps = Math.proportion(marginalSharePrice, increasedShareCapital, shareNominalValueUlps);
ISHAUrl = tokenOffering.signedInvestmentAgreementUrl();
authorizedCapitalUlps = etoTerms.AUTHORIZED_CAPITAL();
}
function isTokenHolder(IControlledToken token, address owner)
private
constant
returns (bool)
{
return token.balanceOf(owner) > 0;
}
function getNominee(IEquityToken token)
private
constant
returns (address)
{
return token == address(0) ? address(0) : token.nominee();
}
function getActionLegalRep(ActionLegalRep rep, address company, address nominee)
private
pure
returns (address)
{
if (rep == ActionLegalRep.CompanyLegalRep) {
return company;
return nominee;
}
return address(0);
}
function getActionLegalRep(ActionLegalRep rep, address company, address nominee)
private
pure
returns (address)
{
if (rep == ActionLegalRep.CompanyLegalRep) {
return company;
return nominee;
}
return address(0);
}
} else if (rep == ActionLegalRep.Nominee) {
function requiresVoting(ActionEscalation escalationLevel)
private
pure
returns (bool)
{
return escalationLevel == ActionEscalation.SHR || escalationLevel == ActionEscalation.THR;
}
function getNonVotingBylawEscalation(
ActionEscalation escalationLevel,
address initiator,
IControlledToken token,
address company,
address nominee
)
private
constant
returns (ExecutionState s)
{
if (escalationLevel == ActionEscalation.Anyone) {
s = ExecutionState.Executing;
s = isTokenHolder(token, initiator) ? ExecutionState.Executing : ExecutionState.Rejected;
s = initiator == company ? ExecutionState.Executing : ExecutionState.Rejected;
s = initiator == nominee ? ExecutionState.Executing : ExecutionState.Rejected;
s = initiator == company ? ExecutionState.Executing : ExecutionState.Rejected;
if (s == ExecutionState.Rejected) {
s = initiator == nominee ? ExecutionState.Executing : ExecutionState.Rejected;
}
revert();
}
}
function getNonVotingBylawEscalation(
ActionEscalation escalationLevel,
address initiator,
IControlledToken token,
address company,
address nominee
)
private
constant
returns (ExecutionState s)
{
if (escalationLevel == ActionEscalation.Anyone) {
s = ExecutionState.Executing;
s = isTokenHolder(token, initiator) ? ExecutionState.Executing : ExecutionState.Rejected;
s = initiator == company ? ExecutionState.Executing : ExecutionState.Rejected;
s = initiator == nominee ? ExecutionState.Executing : ExecutionState.Rejected;
s = initiator == company ? ExecutionState.Executing : ExecutionState.Rejected;
if (s == ExecutionState.Rejected) {
s = initiator == nominee ? ExecutionState.Executing : ExecutionState.Rejected;
}
revert();
}
}
} else if (escalationLevel == ActionEscalation.TokenHolder) {
} else if (escalationLevel == ActionEscalation.CompanyLegalRep) {
} else if (escalationLevel == ActionEscalation.Nominee) {
} else if (escalationLevel == ActionEscalation.CompanyOrNominee) {
function getNonVotingBylawEscalation(
ActionEscalation escalationLevel,
address initiator,
IControlledToken token,
address company,
address nominee
)
private
constant
returns (ExecutionState s)
{
if (escalationLevel == ActionEscalation.Anyone) {
s = ExecutionState.Executing;
s = isTokenHolder(token, initiator) ? ExecutionState.Executing : ExecutionState.Rejected;
s = initiator == company ? ExecutionState.Executing : ExecutionState.Rejected;
s = initiator == nominee ? ExecutionState.Executing : ExecutionState.Rejected;
s = initiator == company ? ExecutionState.Executing : ExecutionState.Rejected;
if (s == ExecutionState.Rejected) {
s = initiator == nominee ? ExecutionState.Executing : ExecutionState.Rejected;
}
revert();
}
}
} else {
function getVotingBylawEscalation(
TokenVotingRule votingRule,
ActionLegalRep votingInitiator,
address initiator,
IControlledToken token,
address company,
address nominee,
bool tokenholderInitiative
)
private
constant
returns (ExecutionState s)
{
address expectedInitator = getActionLegalRep(votingInitiator, company, nominee);
if (votingRule == TokenVotingRule.NoVotingRights) {
s = initiator == expectedInitator ? ExecutionState.Executing : ExecutionState.Rejected;
require(address(token) != address(0), "NF_GOV_NO_GOVERNANCE_TOKEN");
if (initiator == expectedInitator) {
s = ExecutionState.Escalating;
if (tokenholderInitiative && isTokenHolder(token, initiator)) {
s = ExecutionState.New;
s = ExecutionState.Rejected;
}
}
}
}
function getVotingBylawEscalation(
TokenVotingRule votingRule,
ActionLegalRep votingInitiator,
address initiator,
IControlledToken token,
address company,
address nominee,
bool tokenholderInitiative
)
private
constant
returns (ExecutionState s)
{
address expectedInitator = getActionLegalRep(votingInitiator, company, nominee);
if (votingRule == TokenVotingRule.NoVotingRights) {
s = initiator == expectedInitator ? ExecutionState.Executing : ExecutionState.Rejected;
require(address(token) != address(0), "NF_GOV_NO_GOVERNANCE_TOKEN");
if (initiator == expectedInitator) {
s = ExecutionState.Escalating;
if (tokenholderInitiative && isTokenHolder(token, initiator)) {
s = ExecutionState.New;
s = ExecutionState.Rejected;
}
}
}
}
} else {
function getVotingBylawEscalation(
TokenVotingRule votingRule,
ActionLegalRep votingInitiator,
address initiator,
IControlledToken token,
address company,
address nominee,
bool tokenholderInitiative
)
private
constant
returns (ExecutionState s)
{
address expectedInitator = getActionLegalRep(votingInitiator, company, nominee);
if (votingRule == TokenVotingRule.NoVotingRights) {
s = initiator == expectedInitator ? ExecutionState.Executing : ExecutionState.Rejected;
require(address(token) != address(0), "NF_GOV_NO_GOVERNANCE_TOKEN");
if (initiator == expectedInitator) {
s = ExecutionState.Escalating;
if (tokenholderInitiative && isTokenHolder(token, initiator)) {
s = ExecutionState.New;
s = ExecutionState.Rejected;
}
}
}
}
} else {
function getVotingBylawEscalation(
TokenVotingRule votingRule,
ActionLegalRep votingInitiator,
address initiator,
IControlledToken token,
address company,
address nominee,
bool tokenholderInitiative
)
private
constant
returns (ExecutionState s)
{
address expectedInitator = getActionLegalRep(votingInitiator, company, nominee);
if (votingRule == TokenVotingRule.NoVotingRights) {
s = initiator == expectedInitator ? ExecutionState.Executing : ExecutionState.Rejected;
require(address(token) != address(0), "NF_GOV_NO_GOVERNANCE_TOKEN");
if (initiator == expectedInitator) {
s = ExecutionState.Escalating;
if (tokenholderInitiative && isTokenHolder(token, initiator)) {
s = ExecutionState.New;
s = ExecutionState.Rejected;
}
}
}
}
} else {
function escalateNewResolutionInSetup(GovernanceStorage storage g, SetupAction action)
private
returns (ExecutionState)
{
address companyLegalRep = g.COMPANY_LEGAL_REPRESENTATIVE;
if (action == SetupAction.RegisterOffer && (msg.sender == companyLegalRep || isUniverseManager(g.UNIVERSE, msg.sender))) {
return ExecutionState.Executing;
return ExecutionState.Executing;
}
}
function escalateNewResolutionInSetup(GovernanceStorage storage g, SetupAction action)
private
returns (ExecutionState)
{
address companyLegalRep = g.COMPANY_LEGAL_REPRESENTATIVE;
if (action == SetupAction.RegisterOffer && (msg.sender == companyLegalRep || isUniverseManager(g.UNIVERSE, msg.sender))) {
return ExecutionState.Executing;
return ExecutionState.Executing;
}
}
} else if (action == SetupAction.AmendGovernance && msg.sender == companyLegalRep) {
return ExecutionState.Rejected;
function escalateNewResolution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
private
returns (ExecutionState s)
{
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
IVotingCenter vc;
if (requiresVoting(bylaw.escalationLevel)) {
if (bylaw.withTokenholderResolutionInitiative) {
vc = getVotingCenter(g.UNIVERSE);
if (vc.hasProposal(resolutionId)) {
return evaluateProposal(vc, resolutionId, bylaw);
}
}
bylaw.votingRule,
bylaw.votingInitiator,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee,
bylaw.withTokenholderResolutionInitiative
);
address votingLegalRep;
if (s == ExecutionState.Escalating) {
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
if (s == ExecutionState.New) {
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openCampaignProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
s = getNonVotingBylawEscalation(
bylaw.escalationLevel,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee
);
}
}
function escalateNewResolution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
private
returns (ExecutionState s)
{
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
IVotingCenter vc;
if (requiresVoting(bylaw.escalationLevel)) {
if (bylaw.withTokenholderResolutionInitiative) {
vc = getVotingCenter(g.UNIVERSE);
if (vc.hasProposal(resolutionId)) {
return evaluateProposal(vc, resolutionId, bylaw);
}
}
bylaw.votingRule,
bylaw.votingInitiator,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee,
bylaw.withTokenholderResolutionInitiative
);
address votingLegalRep;
if (s == ExecutionState.Escalating) {
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
if (s == ExecutionState.New) {
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openCampaignProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
s = getNonVotingBylawEscalation(
bylaw.escalationLevel,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee
);
}
}
function escalateNewResolution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
private
returns (ExecutionState s)
{
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
IVotingCenter vc;
if (requiresVoting(bylaw.escalationLevel)) {
if (bylaw.withTokenholderResolutionInitiative) {
vc = getVotingCenter(g.UNIVERSE);
if (vc.hasProposal(resolutionId)) {
return evaluateProposal(vc, resolutionId, bylaw);
}
}
bylaw.votingRule,
bylaw.votingInitiator,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee,
bylaw.withTokenholderResolutionInitiative
);
address votingLegalRep;
if (s == ExecutionState.Escalating) {
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
if (s == ExecutionState.New) {
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openCampaignProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
s = getNonVotingBylawEscalation(
bylaw.escalationLevel,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee
);
}
}
function escalateNewResolution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
private
returns (ExecutionState s)
{
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
IVotingCenter vc;
if (requiresVoting(bylaw.escalationLevel)) {
if (bylaw.withTokenholderResolutionInitiative) {
vc = getVotingCenter(g.UNIVERSE);
if (vc.hasProposal(resolutionId)) {
return evaluateProposal(vc, resolutionId, bylaw);
}
}
bylaw.votingRule,
bylaw.votingInitiator,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee,
bylaw.withTokenholderResolutionInitiative
);
address votingLegalRep;
if (s == ExecutionState.Escalating) {
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
if (s == ExecutionState.New) {
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openCampaignProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
s = getNonVotingBylawEscalation(
bylaw.escalationLevel,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee
);
}
}
s = getVotingBylawEscalation(
function escalateNewResolution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
private
returns (ExecutionState s)
{
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
IVotingCenter vc;
if (requiresVoting(bylaw.escalationLevel)) {
if (bylaw.withTokenholderResolutionInitiative) {
vc = getVotingCenter(g.UNIVERSE);
if (vc.hasProposal(resolutionId)) {
return evaluateProposal(vc, resolutionId, bylaw);
}
}
bylaw.votingRule,
bylaw.votingInitiator,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee,
bylaw.withTokenholderResolutionInitiative
);
address votingLegalRep;
if (s == ExecutionState.Escalating) {
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
if (s == ExecutionState.New) {
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openCampaignProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
s = getNonVotingBylawEscalation(
bylaw.escalationLevel,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee
);
}
}
function escalateNewResolution(
GovernanceStorage storage g,
TokenStorage storage t,
bytes32 resolutionId,
uint8 action,
bytes payload
)
private
returns (ExecutionState s)
{
ActionBylaw memory bylaw = deserializeBylaw(t._tokenholderRights.getBylaw(action));
IVotingCenter vc;
if (requiresVoting(bylaw.escalationLevel)) {
if (bylaw.withTokenholderResolutionInitiative) {
vc = getVotingCenter(g.UNIVERSE);
if (vc.hasProposal(resolutionId)) {
return evaluateProposal(vc, resolutionId, bylaw);
}
}
bylaw.votingRule,
bylaw.votingInitiator,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee,
bylaw.withTokenholderResolutionInitiative
);
address votingLegalRep;
if (s == ExecutionState.Escalating) {
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
if (s == ExecutionState.New) {
vc = getVotingCenter(g.UNIVERSE);
votingLegalRep = getActionLegalRep(bylaw.votingLegalRepresentative, g.COMPANY_LEGAL_REPRESENTATIVE, t._nominee);
openCampaignProposal(
t,
vc,
resolutionId,
action,
payload,
votingLegalRep,
bylaw
);
}
s = getNonVotingBylawEscalation(
bylaw.escalationLevel,
msg.sender,
t._token,
g.COMPANY_LEGAL_REPRESENTATIVE,
t._nominee
);
}
}
} else {
function openProposal(
TokenStorage storage t,
IVotingCenter vc,
bytes32 resolutionId,
uint8 action,
bytes payload,
address votingLegalRep,
ActionBylaw memory bylaw
)
private
{
vc.addProposal(
resolutionId,
t._token,
0,
0,
bylaw.votingPeriodDays * 1 days,
votingLegalRep,
votingLegalRep != address(0) ? uint32(bylaw.votingPeriodDays * 1 days) : 0,
votingLegalRep != address(0) ? t._totalVotingPower : 0,
uint256(action),
payload,
false
);
}
function openCampaignProposal(
TokenStorage storage t,
IVotingCenter vc,
bytes32 resolutionId,
uint8 action,
bytes payload,
address votingLegalRep,
ActionBylaw memory bylaw
)
private
{
vc.addProposal(
resolutionId,
t._token,
bylaw.votingPeriodDays * 1 days,
votingInitativeThresholdFrac(bylaw),
2 * bylaw.votingPeriodDays * 1 days,
votingLegalRep,
votingLegalRep != address(0) ? uint32(bylaw.votingPeriodDays * 1 days) : 0,
votingLegalRep != address(0) ? t._totalVotingPower : 0,
uint256(action),
payload,
false
);
}
function evaluateProposal(IVotingCenter vc, bytes32 resolutionId, ActionBylaw memory bylaw)
private
constant
returns (ExecutionState state)
{
(
uint8 s,
uint256 inFavor,
uint256 against,
,
,
,
,
uint256 campaignQuorumTokenAmount,
,
) = vc.tally(resolutionId);
if (s == uint8(VotingProposal.State.Campaigning)) {
return ExecutionState.New;
if (campaignQuorumTokenAmount > 0 && campaignQuorumTokenAmount > inFavor + against) {
return ExecutionState.Rejected;
}
return ExecutionState.Escalating;
}
}
function evaluateProposal(IVotingCenter vc, bytes32 resolutionId, ActionBylaw memory bylaw)
private
constant
returns (ExecutionState state)
{
(
uint8 s,
uint256 inFavor,
uint256 against,
,
,
,
,
uint256 campaignQuorumTokenAmount,
,
) = vc.tally(resolutionId);
if (s == uint8(VotingProposal.State.Campaigning)) {
return ExecutionState.New;
if (campaignQuorumTokenAmount > 0 && campaignQuorumTokenAmount > inFavor + against) {
return ExecutionState.Rejected;
}
return ExecutionState.Escalating;
}
}
} else if (s == uint8(VotingProposal.State.Final)) {
function evaluateProposal(IVotingCenter vc, bytes32 resolutionId, ActionBylaw memory bylaw)
private
constant
returns (ExecutionState state)
{
(
uint8 s,
uint256 inFavor,
uint256 against,
,
,
,
,
uint256 campaignQuorumTokenAmount,
,
) = vc.tally(resolutionId);
if (s == uint8(VotingProposal.State.Campaigning)) {
return ExecutionState.New;
if (campaignQuorumTokenAmount > 0 && campaignQuorumTokenAmount > inFavor + against) {
return ExecutionState.Rejected;
}
return ExecutionState.Escalating;
}
}
return hasProposalPassed(vc, resolutionId, bylaw);
} else {
function hasProposalPassed(IVotingCenter vc, bytes32 resolutionId, ActionBylaw memory bylaw)
private
constant
returns (ExecutionState state)
{
(
,
uint256 inFavor,
uint256 against,
uint256 offchainInFavor,
uint256 offchainAgainst,
uint256 tokenVotingPower,
uint256 totalVotingPower,
,
,
) = vc.tally(resolutionId);
return hasProposalPassed(inFavor, against, offchainInFavor, offchainAgainst, tokenVotingPower, totalVotingPower, bylaw);
}
function hasProposalPassed(
uint256 inFavor,
uint256 against,
uint256 offchainInFavor,
uint256 offchainAgainst,
uint256 tokenVotingPower,
uint256 totalVotingPower,
ActionBylaw memory bylaw
)
internal
pure
returns (ExecutionState state)
{
uint256 pro;
uint256 contra;
if (bylaw.votingRule == TokenVotingRule.Positive) {
if (2 * against > tokenVotingPower) {
contra = tokenVotingPower;
pro = tokenVotingPower;
}
if (2 * inFavor > tokenVotingPower) {
pro = tokenVotingPower;
contra = tokenVotingPower;
}
contra = against;
}
if (bylaw.absoluteMajorityPercent > 0) {
uint256 absoluteMajorityFrac = percentToFrac(bylaw.absoluteMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalVotingPower > absoluteMajorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
}
uint256 totalPowerCast = pro + contra + offchainInFavor + offchainAgainst;
if (Math.mul(totalPowerCast, 10**18) / totalVotingPower >= quorumFrac) {
uint256 majorityFrac = percentToFrac(bylaw.votingMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalPowerCast > majorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
return ExecutionState.Rejected;
}
}
function hasProposalPassed(
uint256 inFavor,
uint256 against,
uint256 offchainInFavor,
uint256 offchainAgainst,
uint256 tokenVotingPower,
uint256 totalVotingPower,
ActionBylaw memory bylaw
)
internal
pure
returns (ExecutionState state)
{
uint256 pro;
uint256 contra;
if (bylaw.votingRule == TokenVotingRule.Positive) {
if (2 * against > tokenVotingPower) {
contra = tokenVotingPower;
pro = tokenVotingPower;
}
if (2 * inFavor > tokenVotingPower) {
pro = tokenVotingPower;
contra = tokenVotingPower;
}
contra = against;
}
if (bylaw.absoluteMajorityPercent > 0) {
uint256 absoluteMajorityFrac = percentToFrac(bylaw.absoluteMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalVotingPower > absoluteMajorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
}
uint256 totalPowerCast = pro + contra + offchainInFavor + offchainAgainst;
if (Math.mul(totalPowerCast, 10**18) / totalVotingPower >= quorumFrac) {
uint256 majorityFrac = percentToFrac(bylaw.votingMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalPowerCast > majorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
return ExecutionState.Rejected;
}
}
function hasProposalPassed(
uint256 inFavor,
uint256 against,
uint256 offchainInFavor,
uint256 offchainAgainst,
uint256 tokenVotingPower,
uint256 totalVotingPower,
ActionBylaw memory bylaw
)
internal
pure
returns (ExecutionState state)
{
uint256 pro;
uint256 contra;
if (bylaw.votingRule == TokenVotingRule.Positive) {
if (2 * against > tokenVotingPower) {
contra = tokenVotingPower;
pro = tokenVotingPower;
}
if (2 * inFavor > tokenVotingPower) {
pro = tokenVotingPower;
contra = tokenVotingPower;
}
contra = against;
}
if (bylaw.absoluteMajorityPercent > 0) {
uint256 absoluteMajorityFrac = percentToFrac(bylaw.absoluteMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalVotingPower > absoluteMajorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
}
uint256 totalPowerCast = pro + contra + offchainInFavor + offchainAgainst;
if (Math.mul(totalPowerCast, 10**18) / totalVotingPower >= quorumFrac) {
uint256 majorityFrac = percentToFrac(bylaw.votingMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalPowerCast > majorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
return ExecutionState.Rejected;
}
}
} else {
} else if (bylaw.votingRule == TokenVotingRule.Negative) {
function hasProposalPassed(
uint256 inFavor,
uint256 against,
uint256 offchainInFavor,
uint256 offchainAgainst,
uint256 tokenVotingPower,
uint256 totalVotingPower,
ActionBylaw memory bylaw
)
internal
pure
returns (ExecutionState state)
{
uint256 pro;
uint256 contra;
if (bylaw.votingRule == TokenVotingRule.Positive) {
if (2 * against > tokenVotingPower) {
contra = tokenVotingPower;
pro = tokenVotingPower;
}
if (2 * inFavor > tokenVotingPower) {
pro = tokenVotingPower;
contra = tokenVotingPower;
}
contra = against;
}
if (bylaw.absoluteMajorityPercent > 0) {
uint256 absoluteMajorityFrac = percentToFrac(bylaw.absoluteMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalVotingPower > absoluteMajorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
}
uint256 totalPowerCast = pro + contra + offchainInFavor + offchainAgainst;
if (Math.mul(totalPowerCast, 10**18) / totalVotingPower >= quorumFrac) {
uint256 majorityFrac = percentToFrac(bylaw.votingMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalPowerCast > majorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
return ExecutionState.Rejected;
}
}
} else {
} else if (bylaw.votingRule == TokenVotingRule.Prorata) {
pro = inFavor;
function hasProposalPassed(
uint256 inFavor,
uint256 against,
uint256 offchainInFavor,
uint256 offchainAgainst,
uint256 tokenVotingPower,
uint256 totalVotingPower,
ActionBylaw memory bylaw
)
internal
pure
returns (ExecutionState state)
{
uint256 pro;
uint256 contra;
if (bylaw.votingRule == TokenVotingRule.Positive) {
if (2 * against > tokenVotingPower) {
contra = tokenVotingPower;
pro = tokenVotingPower;
}
if (2 * inFavor > tokenVotingPower) {
pro = tokenVotingPower;
contra = tokenVotingPower;
}
contra = against;
}
if (bylaw.absoluteMajorityPercent > 0) {
uint256 absoluteMajorityFrac = percentToFrac(bylaw.absoluteMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalVotingPower > absoluteMajorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
}
uint256 totalPowerCast = pro + contra + offchainInFavor + offchainAgainst;
if (Math.mul(totalPowerCast, 10**18) / totalVotingPower >= quorumFrac) {
uint256 majorityFrac = percentToFrac(bylaw.votingMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalPowerCast > majorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
return ExecutionState.Rejected;
}
}
function hasProposalPassed(
uint256 inFavor,
uint256 against,
uint256 offchainInFavor,
uint256 offchainAgainst,
uint256 tokenVotingPower,
uint256 totalVotingPower,
ActionBylaw memory bylaw
)
internal
pure
returns (ExecutionState state)
{
uint256 pro;
uint256 contra;
if (bylaw.votingRule == TokenVotingRule.Positive) {
if (2 * against > tokenVotingPower) {
contra = tokenVotingPower;
pro = tokenVotingPower;
}
if (2 * inFavor > tokenVotingPower) {
pro = tokenVotingPower;
contra = tokenVotingPower;
}
contra = against;
}
if (bylaw.absoluteMajorityPercent > 0) {
uint256 absoluteMajorityFrac = percentToFrac(bylaw.absoluteMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalVotingPower > absoluteMajorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
}
uint256 totalPowerCast = pro + contra + offchainInFavor + offchainAgainst;
if (Math.mul(totalPowerCast, 10**18) / totalVotingPower >= quorumFrac) {
uint256 majorityFrac = percentToFrac(bylaw.votingMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalPowerCast > majorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
return ExecutionState.Rejected;
}
}
} else {
uint256 quorumFrac = percentToFrac(bylaw.votingQuorumPercent);
function hasProposalPassed(
uint256 inFavor,
uint256 against,
uint256 offchainInFavor,
uint256 offchainAgainst,
uint256 tokenVotingPower,
uint256 totalVotingPower,
ActionBylaw memory bylaw
)
internal
pure
returns (ExecutionState state)
{
uint256 pro;
uint256 contra;
if (bylaw.votingRule == TokenVotingRule.Positive) {
if (2 * against > tokenVotingPower) {
contra = tokenVotingPower;
pro = tokenVotingPower;
}
if (2 * inFavor > tokenVotingPower) {
pro = tokenVotingPower;
contra = tokenVotingPower;
}
contra = against;
}
if (bylaw.absoluteMajorityPercent > 0) {
uint256 absoluteMajorityFrac = percentToFrac(bylaw.absoluteMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalVotingPower > absoluteMajorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
}
uint256 totalPowerCast = pro + contra + offchainInFavor + offchainAgainst;
if (Math.mul(totalPowerCast, 10**18) / totalVotingPower >= quorumFrac) {
uint256 majorityFrac = percentToFrac(bylaw.votingMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalPowerCast > majorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
return ExecutionState.Rejected;
}
}
function hasProposalPassed(
uint256 inFavor,
uint256 against,
uint256 offchainInFavor,
uint256 offchainAgainst,
uint256 tokenVotingPower,
uint256 totalVotingPower,
ActionBylaw memory bylaw
)
internal
pure
returns (ExecutionState state)
{
uint256 pro;
uint256 contra;
if (bylaw.votingRule == TokenVotingRule.Positive) {
if (2 * against > tokenVotingPower) {
contra = tokenVotingPower;
pro = tokenVotingPower;
}
if (2 * inFavor > tokenVotingPower) {
pro = tokenVotingPower;
contra = tokenVotingPower;
}
contra = against;
}
if (bylaw.absoluteMajorityPercent > 0) {
uint256 absoluteMajorityFrac = percentToFrac(bylaw.absoluteMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalVotingPower > absoluteMajorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
}
uint256 totalPowerCast = pro + contra + offchainInFavor + offchainAgainst;
if (Math.mul(totalPowerCast, 10**18) / totalVotingPower >= quorumFrac) {
uint256 majorityFrac = percentToFrac(bylaw.votingMajorityPercent);
if (Math.mul(pro + offchainInFavor, 10**18) / totalPowerCast > majorityFrac) {
return ExecutionState.Executing;
return ExecutionState.Rejected;
}
return ExecutionState.Rejected;
}
}
} else {
} else {
function campaignQuorumPassed(IVotingCenter vc, bytes32 resolutionId, uint256 actualVotingPower)
private
constant
returns (bool)
{
(,,,,,uint256 campaignQuorumTokenAmount,,,,,) = vc.proposal(resolutionId);
return actualVotingPower >= campaignQuorumTokenAmount;
}
function percentToFrac(uint8 percent)
private
pure
returns (uint256)
{
return 10**16 * uint256(percent);
}
function votingInitativeThresholdFrac(ActionBylaw memory bylaw)
private
pure
returns (uint256)
{
return percentToFrac(bylaw.votingQuorumPercent) * percentToFrac(bylaw.votingMajorityPercent) / 10**18;
}
function getVotingCenter(Universe u)
private
constant
returns (IVotingCenter)
{
return IVotingCenter(u.getSingleton(KNOWN_INTERFACE_VOTING_CENTER));
}
function isUniverseManager(Universe u, address sender)
private
returns (bool)
{
return u.accessPolicy().allowed(sender, ROLE_UNIVERSE_MANAGER, address(u), msg.sig);
}
}
| 12,704,037 | [
1,
2918,
1158,
2006,
358,
6810,
628,
5313,
776,
17128,
25766,
417,
24410,
581,
5034,
2932,
8188,
17128,
8449,
7923,
5360,
358,
2549,
4846,
7349,
316,
29235,
417,
557,
363,
581,
5034,
2932,
984,
17488,
1318,
7923,
7658,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
611,
1527,
288,
203,
203,
203,
565,
1731,
24,
2713,
5381,
1475,
3417,
5665,
67,
18865,
67,
58,
1974,
1360,
67,
19835,
273,
374,
5297,
25,
1966,
70,
2643,
31,
203,
203,
565,
1731,
1578,
2713,
5381,
22005,
67,
10377,
28489,
67,
19402,
273,
374,
6554,
28,
72,
28,
74,
28,
74,
29,
24852,
24,
70,
3657,
69,
25,
69,
24,
5718,
28,
1966,
72,
623,
4033,
361,
11212,
69,
8148,
69,
2486,
70,
26,
26520,
73,
6564,
71,
27,
70,
24,
71,
27,
70,
6334,
4449,
1611,
27,
7414,
31,
203,
203,
203,
565,
2792,
3155,
58,
17128,
2175,
288,
203,
3639,
2631,
58,
17128,
18464,
16,
203,
3639,
6818,
3720,
16,
203,
3639,
30716,
16,
203,
3639,
2301,
280,
396,
203,
565,
289,
203,
203,
565,
2792,
3287,
288,
203,
565,
289,
203,
203,
565,
2792,
10939,
1803,
288,
203,
3639,
599,
16,
203,
3639,
5433,
10513,
16,
203,
3639,
3986,
409,
43,
1643,
82,
1359,
203,
565,
289,
203,
203,
565,
2792,
4382,
288,
203,
3639,
599,
16,
203,
3639,
5433,
10513,
16,
203,
3639,
3986,
409,
43,
1643,
82,
1359,
16,
203,
3639,
29814,
7036,
16,
203,
3639,
26782,
7036,
16,
203,
3639,
7662,
54,
7036,
16,
203,
3639,
5131,
1345,
16,
203,
3639,
16773,
1345,
16,
203,
3639,
3527,
1345,
16,
203,
3639,
11820,
5157,
1290,
9895,
24051,
16,
203,
3639,
11820,
24051,
1290,
9895,
5157,
16,
203,
3639,
7576,
26685,
558,
73,
16,
203,
3639,
18830,
77,
40,
330,
1421,
16938,
16,
203,
3639,
17787,
23385,
41,
2
] |
./full_match/83/0x958420Fa2EC2A73dAbea569661487a5149508729/sources/contracts/base/vote/VeUpgradeable.sol | @notice Calculate total voting power at some point in the past @param point The point (bias/slope) to start search from @param t Time to calculate the total voting power at @return Total voting power at that time | {
Point memory lastPoint = point;
uint ti = (lastPoint.ts / WEEK) * WEEK;
function balanceOfAtNFT(uint _tokenId, uint _block)
external
view
returns (uint)
}
function _supplyAt(Point memory point, uint t)
internal
view
returns (uint)
for (uint i = 0; i < 255; ++i) {
ti += WEEK;
int128 dSlope = 0;
if (ti > t) {
ti = t;
dSlope = slopeChanges[ti];
}
lastPoint.bias -=
lastPoint.slope *
int128(int256(ti - lastPoint.ts));
if (ti == t) {
break;
}
lastPoint.slope += dSlope;
lastPoint.ts = ti;
}
return uint(uint128(Math.positiveInt128(lastPoint.bias)));
function balanceOfAtNFT(uint _tokenId, uint _block)
external
view
returns (uint)
}
function _supplyAt(Point memory point, uint t)
internal
view
returns (uint)
for (uint i = 0; i < 255; ++i) {
ti += WEEK;
int128 dSlope = 0;
if (ti > t) {
ti = t;
dSlope = slopeChanges[ti];
}
lastPoint.bias -=
lastPoint.slope *
int128(int256(ti - lastPoint.ts));
if (ti == t) {
break;
}
lastPoint.slope += dSlope;
lastPoint.ts = ti;
}
return uint(uint128(Math.positiveInt128(lastPoint.bias)));
} else {
function balanceOfAtNFT(uint _tokenId, uint _block)
external
view
returns (uint)
}
function _supplyAt(Point memory point, uint t)
internal
view
returns (uint)
for (uint i = 0; i < 255; ++i) {
ti += WEEK;
int128 dSlope = 0;
if (ti > t) {
ti = t;
dSlope = slopeChanges[ti];
}
lastPoint.bias -=
lastPoint.slope *
int128(int256(ti - lastPoint.ts));
if (ti == t) {
break;
}
lastPoint.slope += dSlope;
lastPoint.ts = ti;
}
return uint(uint128(Math.positiveInt128(lastPoint.bias)));
}
| 9,556,865 | [
1,
8695,
2078,
331,
17128,
7212,
622,
2690,
1634,
316,
326,
8854,
225,
1634,
1021,
1634,
261,
13931,
19,
30320,
13,
358,
787,
1623,
628,
225,
268,
2647,
358,
4604,
326,
2078,
331,
17128,
7212,
622,
327,
10710,
331,
17128,
7212,
622,
716,
813,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
4686,
3778,
1142,
2148,
273,
1634,
31,
203,
3639,
2254,
11374,
273,
261,
2722,
2148,
18,
3428,
342,
26664,
13,
380,
26664,
31,
203,
565,
445,
11013,
951,
861,
50,
4464,
12,
11890,
389,
2316,
548,
16,
2254,
389,
2629,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
13,
203,
565,
289,
203,
203,
565,
445,
389,
2859,
1283,
861,
12,
2148,
3778,
1634,
16,
2254,
268,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
13,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
4561,
31,
965,
77,
13,
288,
203,
5411,
11374,
1011,
26664,
31,
203,
5411,
509,
10392,
302,
55,
12232,
273,
374,
31,
203,
5411,
309,
261,
9096,
405,
268,
13,
288,
203,
7734,
11374,
273,
268,
31,
203,
7734,
302,
55,
12232,
273,
17543,
7173,
63,
9096,
15533,
203,
5411,
289,
203,
5411,
1142,
2148,
18,
13931,
3947,
203,
7734,
1142,
2148,
18,
30320,
380,
203,
7734,
509,
10392,
12,
474,
5034,
12,
9096,
300,
1142,
2148,
18,
3428,
10019,
203,
5411,
309,
261,
9096,
422,
268,
13,
288,
203,
7734,
898,
31,
203,
5411,
289,
203,
5411,
1142,
2148,
18,
30320,
1011,
302,
55,
12232,
31,
203,
5411,
1142,
2148,
18,
3428,
273,
11374,
31,
203,
3639,
289,
203,
3639,
327,
2254,
12,
11890,
10392,
12,
10477,
18,
21094,
1702,
10392,
12,
2722,
2148,
18,
13931,
3719,
1769,
203,
565,
445,
11013,
951,
861,
50,
4464,
12,
11890,
389,
2316,
548,
16,
2254,
389,
2
] |
./full_match/3/0xC5DD11C2BE1017498fe8E737dc42758fb3597FA9/sources/browser/smart_chain.sol | * Returns the amount of tokens approved by the owner that can be transferred to the spender's account/ | function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
| 8,235,757 | [
1,
1356,
326,
3844,
434,
2430,
20412,
635,
326,
3410,
716,
848,
506,
906,
4193,
358,
326,
17571,
264,
1807,
2236,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1699,
1359,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
13,
1071,
1476,
1135,
261,
11890,
4463,
13,
288,
203,
3639,
327,
2935,
63,
67,
8443,
6362,
67,
87,
1302,
264,
15533,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/97/0x17dF4eb17D764522CD877e8d1180804abd3d82ec/sources/TofuToken.sol | TofuToken with Governance. | contract TofuToken is BEP20('TofuSwap Token', 'TOFU') {
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
mapping (address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
mapping (address => uint32) public numCheckpoints;
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping (address => uint) public nonces;
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "TOKEN::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "TOKEN::delegateBySig: invalid nonce");
require(now <= expiry, "TOKEN::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "TOKEN::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "TOKEN::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "TOKEN::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "TOKEN::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "TOKEN::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "TOKEN::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
} else if (cp.fromBlock < blockNumber) {
} else {
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "TOKEN::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "TOKEN::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
} else {
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
return chainId;
}
assembly { chainId := chainid() }
}
| 11,433,793 | [
1,
774,
27074,
1345,
598,
611,
1643,
82,
1359,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
399,
792,
89,
1345,
353,
9722,
52,
3462,
2668,
774,
27074,
12521,
3155,
2187,
296,
56,
3932,
57,
6134,
288,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
389,
8501,
15608,
815,
12,
2867,
12,
20,
3631,
389,
3771,
1332,
815,
63,
67,
869,
6487,
389,
8949,
1769,
203,
565,
289,
203,
203,
203,
203,
565,
2874,
261,
2867,
516,
1758,
13,
2713,
389,
3771,
1332,
815,
31,
203,
565,
1958,
25569,
288,
203,
3639,
2254,
1578,
628,
1768,
31,
203,
3639,
2254,
5034,
19588,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
11890,
1578,
516,
25569,
3719,
1071,
26402,
31,
203,
565,
2874,
261,
2867,
516,
2254,
1578,
13,
1071,
818,
1564,
4139,
31,
203,
565,
1731,
1578,
1071,
5381,
27025,
67,
2399,
15920,
273,
417,
24410,
581,
5034,
2932,
41,
2579,
27,
2138,
3748,
12,
1080,
508,
16,
11890,
5034,
2687,
548,
16,
2867,
3929,
310,
8924,
2225,
1769,
203,
565,
1731,
1578,
1071,
5381,
2030,
19384,
2689,
67,
2399,
15920,
273,
417,
24410,
581,
5034,
2932,
26945,
12,
2867,
7152,
73,
16,
11890,
5034,
7448,
16,
11890,
5034,
10839,
2225,
1769,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
1661,
764,
31,
203,
565,
871,
27687,
5033,
12,
2867,
8808,
11158,
639,
16,
1758,
8808,
628,
9586,
16,
1758,
8808,
358,
9586,
1769,
2
] |
pragma solidity ^0.6.9;
import "./SafeMath.sol";
contract Sig_Timelock {
using SafeMath for uint;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint user_delay);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint user_delay);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint user_delay);
struct LockedTx {
address target;
uint value;
string signature;
bytes data;
uint user_delay;
bool ready;
}
mapping (bytes32 => LockedTx) private queuedTx;
uint public constant MINIMUM_DELAY = 0 days;
uint public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint public delay;
//////////////////////////////////////////////////////////////////////////////////////////////////
// GENERATED BY SIGNALSLOT PARSER
// Original Code:
// signal TimesUp;
// TODO: Arguments should not be limited to one 32 byte value
// Generated variables that represent the signal
bytes32 private TimesUp_data;
bytes32 private TimesUp_dataslot;
uint private TimesUp_status;
bytes32 private TimesUp_key;
// Set the data to be emitted
function set_TimesUp_data(bytes32 dataSet) private {
TimesUp_data = dataSet;
}
// Get the argument count
function get_TimesUp_is_fix() public pure returns (uint is_fix) {
return 5 + 256*32;
}
// Get the signal key
function get_TimesUp_key() public view returns (bytes32 key) {
return TimesUp_key;
}
// Get the data slot
function get_TimesUp_dataslot() public view returns (bytes32 dataslot) {
return TimesUp_dataslot;
}
// signal TimesUp construction
// This should be called once in the contract construction.
// This parser should automatically call it.
function TimesUp() private {
TimesUp_key = keccak256("TimesUp()");
assembly {
sstore(TimesUp_status_slot, createsig(5, sload(TimesUp_key_slot)))
sstore(TimesUp_dataslot_slot, TimesUp_data_slot)
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
fallback() external payable { }
function setDelay(uint delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address pendingAdmin_) public {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint user_delay) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(user_delay >= delay, "Timelock::queueTransaction: Delay must exceed required delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, user_delay));
queuedTx[txHash] = LockedTx(target, value, signature, data, user_delay, true);
//////////////////////////////////////////////////////////////////////////////////////////////////
// GENERATED BY SIGNALSLOT PARSER
// Original Code:
// emitsig TimesUp(txHash).delay(user_delay)
// Set the data field in the signal
set_TimesUp_data(txHash);
// Get the argument count
uint this_emitsig_TimesUp_is_fix = get_TimesUp_is_fix();
// Get the data slot
bytes32 this_emitsig_TimesUp_dataslot = get_TimesUp_dataslot();
// Get the signal key
bytes32 this_emitsig_TimesUp_key = get_TimesUp_key();
// Use assembly to emit the signal and queue up slot transactions
assembly {
mstore(0x40, emitsig(this_emitsig_TimesUp_key, user_delay, this_emitsig_TimesUp_dataslot, this_emitsig_TimesUp_is_fix))
}
//////////////////////////////////////////////////////////////////////////////////////////////////
return txHash;
}
function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint user_delay) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, user_delay));
queuedTx[txHash].ready=false;
emit CancelTransaction(txHash, target, value, signature, data, user_delay);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// GENERATED BY SIGNALSLOT PARSER
// Original Code:
// handler TxExecutor {...}
// Generated variables that represent the slot
uint private TxExecutor_status;
bytes32 private TxExecutor_key;
// Get the signal key
function get_TxExecutor_key() public view returns (bytes32 key) {
return TxExecutor_key;
}
// TxExecutor construction
// Should be called once in the contract construction
function TxExecutor() private {
TxExecutor_key = keccak256("TxExecutor_func(bytes32)");
assembly {
sstore(TxExecutor_status_slot, createslot(1, 10, 30000, sload(TxExecutor_key_slot)))
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// TxExecutor code to be executed
// The slot is converted to a function that will be called in slot transactions.
function TxExecutor_func(bytes32 txHash) public {
require(queuedTx[txHash].ready, "Timelock::executeTransaction: Transaction hasn't been queued.");
queuedTx[txHash].ready=false;
bytes memory callData;
if (bytes(queuedTx[txHash].signature).length == 0) {
callData = queuedTx[txHash].data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(queuedTx[txHash].signature))), queuedTx[txHash].data);
}
(bool success, bytes memory returnData) = queuedTx[txHash].target.call.value(queuedTx[txHash].value)(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, queuedTx[txHash].target, queuedTx[txHash].value, queuedTx[txHash].signature, queuedTx[txHash].data, queuedTx[txHash].user_delay);
}
function getBlockTimestamp() internal view returns (uint) {
return block.timestamp;
}
constructor(address admin_, uint delay_) public {
TimesUp();
TxExecutor();
require(delay_ >= MINIMUM_DELAY, "Timelock::construct: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
//////////////////////////////////////////////////////////////////////////////////////////////////
// GENERATED BY SIGNALSLOT PARSER
// Original Code:
// TxExecutor.bind(this.TimesUp)
// Convert to address
address this_bindslot_address = address(this);
// Get signal key from emitter contract
bytes32 this_bindslot_TimesUp_key = keccak256("TimesUp()");
// Get slot key from receiver contract
bytes32 this_this_bindslot_TxExecutor_key = get_TxExecutor_key();
// Use assembly to bind slot to signal
assembly {
mstore(0x40, bindslot(this_bindslot_address, this_bindslot_TimesUp_key, this_this_bindslot_TxExecutor_key))
}
//////////////////////////////////////////////////////////////////////////////////////////////////
admin = admin_;
delay = delay_;
}
} | TxExecutor code to be executed The slot is converted to a function that will be called in slot transactions. | function TxExecutor_func(bytes32 txHash) public {
require(queuedTx[txHash].ready, "Timelock::executeTransaction: Transaction hasn't been queued.");
queuedTx[txHash].ready=false;
bytes memory callData;
if (bytes(queuedTx[txHash].signature).length == 0) {
callData = queuedTx[txHash].data;
callData = abi.encodePacked(bytes4(keccak256(bytes(queuedTx[txHash].signature))), queuedTx[txHash].data);
}
(bool success, bytes memory returnData) = queuedTx[txHash].target.call.value(queuedTx[txHash].value)(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, queuedTx[txHash].target, queuedTx[txHash].value, queuedTx[txHash].signature, queuedTx[txHash].data, queuedTx[txHash].user_delay);
}
| 12,749,654 | [
1,
4188,
6325,
981,
358,
506,
7120,
1021,
4694,
353,
5970,
358,
279,
445,
716,
903,
506,
2566,
316,
4694,
8938,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6424,
6325,
67,
644,
12,
3890,
1578,
2229,
2310,
13,
225,
1071,
225,
288,
203,
540,
203,
540,
203,
3639,
2583,
12,
19499,
4188,
63,
978,
2310,
8009,
1672,
16,
315,
10178,
292,
975,
2866,
8837,
3342,
30,
5947,
13342,
1404,
2118,
12234,
1199,
1769,
203,
3639,
12234,
4188,
63,
978,
2310,
8009,
1672,
33,
5743,
31,
203,
3639,
1731,
3778,
745,
751,
31,
203,
203,
3639,
309,
261,
3890,
12,
19499,
4188,
63,
978,
2310,
8009,
8195,
2934,
2469,
422,
374,
13,
288,
203,
5411,
745,
751,
273,
12234,
4188,
63,
978,
2310,
8009,
892,
31,
203,
5411,
745,
751,
273,
24126,
18,
3015,
4420,
329,
12,
3890,
24,
12,
79,
24410,
581,
5034,
12,
3890,
12,
19499,
4188,
63,
978,
2310,
8009,
8195,
3719,
3631,
12234,
4188,
63,
978,
2310,
8009,
892,
1769,
203,
3639,
289,
203,
203,
540,
203,
3639,
261,
6430,
2216,
16,
1731,
3778,
327,
751,
13,
273,
12234,
4188,
63,
978,
2310,
8009,
3299,
18,
1991,
18,
1132,
12,
19499,
4188,
63,
978,
2310,
8009,
1132,
21433,
1991,
751,
1769,
203,
3639,
2583,
12,
4768,
16,
315,
10178,
292,
975,
2866,
8837,
3342,
30,
5947,
4588,
15226,
329,
1199,
1769,
203,
203,
3639,
3626,
7903,
3342,
12,
978,
2310,
16,
12234,
4188,
63,
978,
2310,
8009,
3299,
16,
12234,
4188,
63,
978,
2310,
8009,
1132,
16,
12234,
4188,
63,
978,
2310,
8009,
8195,
16,
12234,
4188,
63,
978,
2310,
8009,
892,
16,
12234,
4188,
63,
978,
2310,
8009,
1355,
67,
10790,
1769,
540,
203,
565,
289,
2
] |
pragma solidity ^0.4.25;
contract BalanceHolder {
mapping(address => uint256) public balanceOf;
event LogWithdraw(
address indexed user,
uint256 amount
);
function withdraw()
public {
uint256 bal = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
msg.sender.transfer(bal);
emit LogWithdraw(msg.sender, bal);
}
}
contract IBalanceHolder {
mapping(address => uint256) public balanceOf;
function withdraw()
public {
}
}
contract IRealitio is IBalanceHolder {
struct Question {
bytes32 content_hash;
address arbitrator;
uint32 opening_ts;
uint32 timeout;
uint32 finalize_ts;
bool is_pending_arbitration;
uint256 bounty;
bytes32 best_answer;
bytes32 history_hash;
uint256 bond;
}
// Stored in a mapping indexed by commitment_id, a hash of commitment hash, question, bond.
struct Commitment {
uint32 reveal_ts;
bool is_revealed;
bytes32 revealed_answer;
}
// Only used when claiming more bonds than fits into a transaction
// Stored in a mapping indexed by question_id.
struct Claim {
address payee;
uint256 last_bond;
uint256 queued_funds;
}
uint256 nextTemplateID = 0;
mapping(uint256 => uint256) public templates;
mapping(uint256 => bytes32) public template_hashes;
mapping(bytes32 => Question) public questions;
mapping(bytes32 => Claim) public question_claims;
mapping(bytes32 => Commitment) public commitments;
mapping(address => uint256) public arbitrator_question_fees;
/// @notice Function for arbitrator to set an optional per-question fee.
/// @dev The per-question fee, charged when a question is asked, is intended as an anti-spam measure.
/// @param fee The fee to be charged by the arbitrator when a question is asked
function setQuestionFee(uint256 fee)
external {
}
/// @notice Create a reusable template, which should be a JSON document.
/// Placeholders should use gettext() syntax, eg %s.
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param content The template content
/// @return The ID of the newly-created template, which is created sequentially.
function createTemplate(string content)
public returns (uint256) {
}
/// @notice Create a new reusable template and use it to ask a question
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param content The template content
/// @param question A string containing the parameters that will be passed into the template to make the question
/// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
/// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
/// @param opening_ts If set, the earliest time it should be possible to answer the question.
/// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
/// @return The ID of the newly-created template, which is created sequentially.
function createTemplateAndAskQuestion(
string content,
string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce
)
// stateNotCreated is enforced by the internal _askQuestion
public payable returns (bytes32) {
}
/// @notice Ask a new question and return the ID
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param template_id The ID number of the template the question will use
/// @param question A string containing the parameters that will be passed into the template to make the question
/// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
/// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
/// @param opening_ts If set, the earliest time it should be possible to answer the question.
/// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
/// @return The ID of the newly-created question, created deterministically.
function askQuestion(uint256 template_id, string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce)
// stateNotCreated is enforced by the internal _askQuestion
public payable returns (bytes32) {
}
/// @notice Add funds to the bounty for a question
/// @dev Add bounty funds after the initial question creation. Can be done any time until the question is finalized.
/// @param question_id The ID of the question you wish to fund
function fundAnswerBounty(bytes32 question_id)
external payable {
}
/// @notice Submit an answer for a question.
/// @dev Adds the answer to the history and updates the current "best" answer.
/// May be subject to front-running attacks; Substitute submitAnswerCommitment()->submitAnswerReveal() to prevent them.
/// @param question_id The ID of the question
/// @param answer The answer, encoded into bytes32
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
function submitAnswer(bytes32 question_id, bytes32 answer, uint256 max_previous)
external payable {
}
/// @notice Submit the hash of an answer, laying your claim to that answer if you reveal it in a subsequent transaction.
/// @dev Creates a hash, commitment_id, uniquely identifying this answer, to this question, with this bond.
/// The commitment_id is stored in the answer history where the answer would normally go.
/// Does not update the current best answer - this is left to the later submitAnswerReveal() transaction.
/// @param question_id The ID of the question
/// @param answer_hash The hash of your answer, plus a nonce that you will later reveal
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
/// @param _answerer If specified, the address to be given as the question answerer. Defaults to the sender.
/// @dev Specifying the answerer is useful if you want to delegate the commit-and-reveal to a third-party.
function submitAnswerCommitment(bytes32 question_id, bytes32 answer_hash, uint256 max_previous, address _answerer)
external payable {
}
/// @notice Submit the answer whose hash you sent in a previous submitAnswerCommitment() transaction
/// @dev Checks the parameters supplied recreate an existing commitment, and stores the revealed answer
/// Updates the current answer unless someone has since supplied a new answer with a higher bond
/// msg.sender is intentionally not restricted to the user who originally sent the commitment;
/// For example, the user may want to provide the answer+nonce to a third-party service and let them send the tx
/// NB If we are pending arbitration, it will be up to the arbitrator to wait and see any outstanding reveal is sent
/// @param question_id The ID of the question
/// @param answer The answer, encoded as bytes32
/// @param nonce The nonce that, combined with the answer, recreates the answer_hash you gave in submitAnswerCommitment()
/// @param bond The bond that you paid in your submitAnswerCommitment() transaction
function submitAnswerReveal(bytes32 question_id, bytes32 answer, uint256 nonce, uint256 bond)
external {
}
/// @notice Notify the contract that the arbitrator has been paid for a question, freezing it pending their decision.
/// @dev The arbitrator contract is trusted to only call this if they've been paid, and tell us who paid them.
/// @param question_id The ID of the question
/// @param requester The account that requested arbitration
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
function notifyOfArbitrationRequest(bytes32 question_id, address requester, uint256 max_previous)
external {
}
/// @notice Submit the answer for a question, for use by the arbitrator.
/// @dev Doesn't require (or allow) a bond.
/// If the current final answer is correct, the account should be whoever submitted it.
/// If the current final answer is wrong, the account should be whoever paid for arbitration.
/// However, the answerer stipulations are not enforced by the contract.
/// @param question_id The ID of the question
/// @param answer The answer, encoded into bytes32
/// @param answerer The account credited with this answer for the purpose of bond claims
function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer)
external {
}
/// @notice Report whether the answer to the specified question is finalized
/// @param question_id The ID of the question
/// @return Return true if finalized
function isFinalized(bytes32 question_id)
view public returns (bool) {
}
/// @notice (Deprecated) Return the final answer to the specified question, or revert if there isn't one
/// @param question_id The ID of the question
/// @return The answer formatted as a bytes32
function getFinalAnswer(bytes32 question_id)
external view returns (bytes32) {
}
/// @notice Return the final answer to the specified question, or revert if there isn't one
/// @param question_id The ID of the question
/// @return The answer formatted as a bytes32
function resultFor(bytes32 question_id)
external view returns (bytes32) {
}
/// @notice Return the final answer to the specified question, provided it matches the specified criteria.
/// @dev Reverts if the question is not finalized, or if it does not match the specified criteria.
/// @param question_id The ID of the question
/// @param content_hash The hash of the question content (template ID + opening time + question parameter string)
/// @param arbitrator The arbitrator chosen for the question (regardless of whether they are asked to arbitrate)
/// @param min_timeout The timeout set in the initial question settings must be this high or higher
/// @param min_bond The bond sent with the final answer must be this high or higher
/// @return The answer formatted as a bytes32
function getFinalAnswerIfMatches(
bytes32 question_id,
bytes32 content_hash, address arbitrator, uint32 min_timeout, uint256 min_bond
)
external view returns (bytes32) {
}
/// @notice Assigns the winnings (bounty and bonds) to everyone who gave the accepted answer
/// Caller must provide the answer history, in reverse order
/// @dev Works up the chain and assign bonds to the person who gave the right answer
/// If someone gave the winning answer earlier, they must get paid from the higher bond
/// That means we can't pay out the bond added at n until we have looked at n-1
/// The first answer is authenticated by checking against the stored history_hash.
/// One of the inputs to history_hash is the history_hash before it, so we use that to authenticate the next entry, etc
/// Once we get to a null hash we'll know we're done and there are no more answers.
/// Usually you would call the whole thing in a single transaction, but if not then the data is persisted to pick up later.
/// @param question_id The ID of the question
/// @param history_hashes Second-last-to-first, the hash of each history entry. (Final one should be empty).
/// @param addrs Last-to-first, the address of each answerer or commitment sender
/// @param bonds Last-to-first, the bond supplied with each answer or commitment
/// @param answers Last-to-first, each answer supplied, or commitment ID if the answer was supplied with commit->reveal
function claimWinnings(
bytes32 question_id,
bytes32[] history_hashes, address[] addrs, uint256[] bonds, bytes32[] answers
)
public {
}
/// @notice Convenience function to assign bounties/bonds for multiple questions in one go, then withdraw all your funds.
/// Caller must provide the answer history for each question, in reverse order
/// @dev Can be called by anyone to assign bonds/bounties, but funds are only withdrawn for the user making the call.
/// @param question_ids The IDs of the questions you want to claim for
/// @param lengths The number of history entries you will supply for each question ID
/// @param hist_hashes In a single list for all supplied questions, the hash of each history entry.
/// @param addrs In a single list for all supplied questions, the address of each answerer or commitment sender
/// @param bonds In a single list for all supplied questions, the bond supplied with each answer or commitment
/// @param answers In a single list for all supplied questions, each answer supplied, or commitment ID
function claimMultipleAndWithdrawBalance(
bytes32[] question_ids, uint256[] lengths,
bytes32[] hist_hashes, address[] addrs, uint256[] bonds, bytes32[] answers
)
public {
}
/// @notice Returns the questions's content hash, identifying the question content
/// @param question_id The ID of the question
function getContentHash(bytes32 question_id)
public view returns(bytes32) {
}
/// @notice Returns the arbitrator address for the question
/// @param question_id The ID of the question
function getArbitrator(bytes32 question_id)
public view returns(address) {
}
/// @notice Returns the timestamp when the question can first be answered
/// @param question_id The ID of the question
function getOpeningTS(bytes32 question_id)
public view returns(uint32) {
}
/// @notice Returns the timeout in seconds used after each answer
/// @param question_id The ID of the question
function getTimeout(bytes32 question_id)
public view returns(uint32) {
}
/// @notice Returns the timestamp at which the question will be/was finalized
/// @param question_id The ID of the question
function getFinalizeTS(bytes32 question_id)
public view returns(uint32) {
}
/// @notice Returns whether the question is pending arbitration
/// @param question_id The ID of the question
function isPendingArbitration(bytes32 question_id)
public view returns(bool) {
}
/// @notice Returns the current total unclaimed bounty
/// @dev Set back to zero once the bounty has been claimed
/// @param question_id The ID of the question
function getBounty(bytes32 question_id)
public view returns(uint256) {
}
/// @notice Returns the current best answer
/// @param question_id The ID of the question
function getBestAnswer(bytes32 question_id)
public view returns(bytes32) {
}
/// @notice Returns the history hash of the question
/// @param question_id The ID of the question
/// @dev Updated on each answer, then rewound as each is claimed
function getHistoryHash(bytes32 question_id)
public view returns(bytes32) {
}
/// @notice Returns the highest bond posted so far for a question
/// @param question_id The ID of the question
function getBond(bytes32 question_id)
public view returns(uint256) {
}
}
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
contract ICash{}
contract IMarket {
function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256);
function isFinalized() public view returns (bool);
function isInvalid() public view returns (bool);
}
contract IUniverse {
function getWinningChildUniverse() public view returns (IUniverse);
function createYesNoMarket(uint256 _endTime, uint256 _feePerEthInWei, ICash _denominationToken, address _designatedReporterAddress, bytes32 _topic, string _description, string _extraInfo) public
payable returns (IMarket _newMarket);
}
contract RealitioAugurArbitrator is BalanceHolder {
using strings for *;
IRealitio public realitio;
uint256 public template_id;
uint256 dispute_fee;
ICash public market_token;
IUniverse public latest_universe;
bytes32 constant REALITIO_INVALID = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
bytes32 constant REALITIO_YES = 0x0000000000000000000000000000000000000000000000000000000000000001;
bytes32 constant REALITIO_NO = 0x0000000000000000000000000000000000000000000000000000000000000000;
uint256 constant AUGUR_YES_INDEX = 1;
uint256 constant AUGUR_NO_INDEX = 0;
string constant REALITIO_DELIMITER = '␟';
event LogRequestArbitration(
bytes32 indexed question_id,
uint256 fee_paid,
address requester,
uint256 remaining
);
struct RealitioQuestion {
uint256 bounty;
address disputer;
IMarket augur_market;
address owner;
}
mapping(bytes32 => RealitioQuestion) public realitio_questions;
modifier onlyInitialized() {
require(dispute_fee > 0, "The contract cannot be used until a dispute fee has been set");
_;
}
modifier onlyUninitialized() {
require(dispute_fee == 0, "The contract can only be initialized once");
_;
}
/// @notice Initialize a new contract
/// @param _realitio The address of the realitio contract you arbitrate for
/// @param _template_id The ID of the realitio template we support.
/// @param _dispute_fee The fee this contract will charge for resolution
/// @param _genesis_universe The earliest supported Augur universe
/// @param _market_token The token used by the market we create, typically Augur's wrapped ETH
function initialize(IRealitio _realitio, uint256 _template_id, uint256 _dispute_fee, IUniverse _genesis_universe, ICash _market_token)
onlyUninitialized
external {
require(_dispute_fee > 0, "You must provide a dispute fee");
require(_realitio != IRealitio(0x0), "You must provide a realitio address");
require(_genesis_universe != IUniverse(0x0), "You must provide a genesis universe");
require(_market_token != ICash(0x0), "You must provide an augur cash token");
dispute_fee = _dispute_fee;
template_id = _template_id;
realitio = _realitio;
latest_universe = _genesis_universe;
market_token = _market_token;
}
/// @notice Register a new child universe after a fork
/// @dev Anyone can create Augur universes but the "correct" ones should be in a single line from the official genesis universe
/// @dev If a universe goes into a forking state, someone will need to call this before you can create new markets.
function addForkedUniverse()
onlyInitialized
external {
IUniverse child_universe = IUniverse(latest_universe).getWinningChildUniverse();
latest_universe = child_universe;
}
/// @notice Trim the realitio question content to the part before the initial delimiter.
/// @dev The Realitio question is a list of parameters for a template.
/// @dev We throw away the subsequent parameters of the question.
/// @dev The first item in the (supported) template must be the title.
/// @dev Subsequent items (category, lang) aren't needed in Augur.
/// @dev This does not support more complex templates, eg selects which also need a list of answrs.
function _trimQuestion(string q)
internal pure returns (string) {
return q.toSlice().split(REALITIO_DELIMITER.toSlice()).toString();
}
function _callAugurMarketCreate(bytes32 question_id, string question, address designated_reporter)
internal {
realitio_questions[question_id].augur_market = latest_universe.createYesNoMarket.value(msg.value)( now, 0, market_token, designated_reporter, 0x0, _trimQuestion(question), "");
realitio_questions[question_id].owner = msg.sender;
}
/// @notice Create a market in Augur and store the creator as its owner
/// @dev Anyone can call this, and calling this will give them the rights to claim the bounty
/// @dev They will need have sent this contract some REP for the no-show bond.
/// @param question The question content (a delimited parameter list)
/// @param timeout The timeout between rounds, set when the question was created
/// @param opening_ts The opening timestamp for the question, set when the question was created
/// @param asker The address that created the question, ie the msg.sender of the original realitio.askQuestion call
/// @param nonce The nonce for the question, set when the question was created
/// @param designated_reporter The Augur designated reporter. We let the market creator choose this, if it's bad the Augur dispute resolution should sort it out
function createMarket(
string question, uint32 timeout, uint32 opening_ts, address asker, uint256 nonce,
address designated_reporter
)
onlyInitialized
external payable {
// Reconstruct the question ID from the content
bytes32 question_id = keccak256(keccak256(template_id, opening_ts, question), this, timeout, asker, nonce);
require(realitio_questions[question_id].bounty > 0, "Arbitration must have been requested (paid for)");
require(realitio_questions[question_id].augur_market == IMarket(0x0), "The market must not have been created yet");
// Create a market in Augur
_callAugurMarketCreate(question_id, question, designated_reporter);
}
/// @notice Return data needed to verify the last history item
/// @dev Filters the question struct from Realitio to stuff we need
/// @dev Broken out into its own function to avoid stack depth limitations
/// @param question_id The realitio question
/// @param last_history_hash The history hash when you gave your answer
/// @param last_answer_or_commitment_id The last answer given, or its commitment ID if it was a commitment
/// @param last_bond The bond paid in the last answer given
/// @param last_answerer The account that submitted the last answer (or its commitment)
/// @param is_commitment Whether the last answer was submitted with commit->reveal
function _verifyInput(
bytes32 question_id,
bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, uint256 last_bond, address last_answerer, bool is_commitment
) internal view returns (bool, bytes32) {
require(realitio.isPendingArbitration(question_id), "The question must be pending arbitration in realitio");
bytes32 history_hash = realitio.getHistoryHash(question_id);
require(history_hash == keccak256(last_history_hash, last_answer_or_commitment_id, last_bond, last_answerer, is_commitment), "The history parameters supplied must match the history hash in the realitio contract");
}
/// @notice Given the last history entry, get whether they had a valid answer if so what it was
/// @dev These just need to be fetched from Realitio, but they can't be fetched directly because we don't store them to save gas
/// @dev To get the final answer, we need to reconstruct the final answer using the history hash
/// @dev TODO: This should probably be in a library offered by Realitio
/// @param question_id The ID of the realitio question
/// @param last_history_hash The history hash when you gave your answer
/// @param last_answer_or_commitment_id The last answer given, or its commitment ID if it was a commitment
/// @param last_bond The bond paid in the last answer given
/// @param last_answerer The account that submitted the last answer (or its commitment)
/// @param is_commitment Whether the last answer was submitted with commit->reveal
function _answerData(
bytes32 question_id,
bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, uint256 last_bond, address last_answerer, bool is_commitment
) internal view returns (bool, bytes32) {
bool is_pending_arbitration;
bytes32 history_hash;
// If the question hasn't been answered, nobody is ever right
if (last_bond == 0) {
return (false, bytes32(0));
}
bytes32 last_answer;
bool is_answered;
if (is_commitment) {
uint256 reveal_ts;
bool is_revealed;
bytes32 revealed_answer;
(reveal_ts, is_revealed, revealed_answer) = realitio.commitments(last_answer_or_commitment_id);
if (is_revealed) {
last_answer = revealed_answer;
is_answered = true;
} else {
// Shouldn't normally happen, but if the last answerer might still reveal when we are called, bail out and wait for them.
require(reveal_ts < uint32(now), "Arbitration cannot be done until the last answerer has had time to reveal their commitment");
is_answered = false;
}
} else {
last_answer = last_answer_or_commitment_id;
is_answered = true;
}
return (is_answered, last_answer);
}
/// @notice Get the answer from the Augur market and map it to a Realitio value
/// @param market The Augur market
function realitioAnswerFromAugurMarket(
IMarket market
)
onlyInitialized
public view returns (bytes32) {
bytes32 answer;
if (market.isInvalid()) {
answer = REALITIO_INVALID;
} else {
uint256 no_val = market.getWinningPayoutNumerator(AUGUR_NO_INDEX);
uint256 yes_val = market.getWinningPayoutNumerator(AUGUR_YES_INDEX);
if (yes_val == no_val) {
answer = REALITIO_INVALID;
} else {
if (yes_val > no_val) {
answer = REALITIO_YES;
} else {
answer = REALITIO_NO;
}
}
}
return answer;
}
/// @notice Report the answer from a finalized Augur market to a Realitio contract with a question awaiting arbitration
/// @dev Pays the arbitration bounty to whoever created the Augur market. Probably the same person will call this function, but they don't have to.
/// @dev We need to know who gave the final answer and what it was, as they need to be supplied as the arbitration winner if the last answer is right
/// @dev These just need to be fetched from Realitio, but they can't be fetched directly because to save gas, Realitio doesn't store them
/// @dev To get the final answer, we need to reconstruct the final answer using the history hash
/// @param question_id The ID of the question you're reporting on
/// @param last_history_hash The history hash when you gave your answer
/// @param last_answer_or_commitment_id The last answer given, or its commitment ID if it was a commitment
/// @param last_bond The bond paid in the last answer given
/// @param last_answerer The account that submitted the last answer (or its commitment)
/// @param is_commitment Whether the last answer was submitted with commit->reveal
function reportAnswer(
bytes32 question_id,
bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, uint256 last_bond, address last_answerer, bool is_commitment
)
onlyInitialized
public {
IMarket market = realitio_questions[question_id].augur_market;
// There must be an open bounty
require(realitio_questions[question_id].bounty > 0, "Arbitration must have been requested for this question");
bool is_answered; // the answer was provided, not just left as an unrevealed commit
bytes32 last_answer;
_verifyInput(question_id, last_history_hash, last_answer_or_commitment_id, last_bond, last_answerer, is_commitment);
(is_answered, last_answer) = _answerData(question_id, last_history_hash, last_answer_or_commitment_id, last_bond, last_answerer, is_commitment);
require(market.isFinalized(), "The augur market must have been finalized");
bytes32 answer = realitioAnswerFromAugurMarket(market);
address winner;
if (is_answered && last_answer == answer) {
winner = last_answerer;
} else {
// If the final answer is wrong, we assign the person who paid for arbitration.
// See https://realitio.github.io/docs/html/arbitrators.html for why.
winner = realitio_questions[question_id].disputer;
}
realitio.submitAnswerByArbitrator(question_id, answer, winner);
address owner = realitio_questions[question_id].owner;
balanceOf[owner] += realitio_questions[question_id].bounty;
delete realitio_questions[question_id];
}
/// @notice Return the dispute fee for the specified question. 0 indicates that we won't arbitrate it.
/// @dev Uses a general default, but can be over-ridden on a question-by-question basis.
function getDisputeFee(bytes32)
external view returns (uint256) {
return dispute_fee;
}
/// @notice Request arbitration, freezing the question until we send submitAnswerByArbitrator
/// @dev The bounty can be paid only in part, in which case the last person to pay will be considered the payer
/// @dev Will trigger an error if the notification fails, eg because the question has already been finalized
/// @param question_id The question in question
/// @param max_previous The highest bond level we should accept (used to check the state hasn't changed)
function requestArbitration(bytes32 question_id, uint256 max_previous)
onlyInitialized
external payable returns (bool) {
require(msg.value >= dispute_fee, "The payment must cover the fee");
realitio.notifyOfArbitrationRequest(question_id, msg.sender, max_previous);
realitio_questions[question_id].bounty = msg.value;
realitio_questions[question_id].disputer = msg.sender;
LogRequestArbitration(question_id, msg.value, msg.sender, 0);
}
} | Only used when claiming more bonds than fits into a transaction Stored in a mapping indexed by question_id. | struct Claim {
address payee;
uint256 last_bond;
uint256 queued_funds;
}
uint256 nextTemplateID = 0;
mapping(uint256 => uint256) public templates;
mapping(uint256 => bytes32) public template_hashes;
mapping(bytes32 => Question) public questions;
mapping(bytes32 => Claim) public question_claims;
mapping(bytes32 => Commitment) public commitments;
mapping(address => uint256) public arbitrator_question_fees;
| 1,808,931 | [
1,
3386,
1399,
1347,
7516,
310,
1898,
15692,
2353,
13351,
1368,
279,
2492,
26548,
316,
279,
2874,
8808,
635,
5073,
67,
350,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
18381,
288,
203,
3639,
1758,
8843,
1340,
31,
203,
3639,
2254,
5034,
1142,
67,
26425,
31,
203,
3639,
2254,
5034,
12234,
67,
74,
19156,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
1024,
2283,
734,
273,
374,
31,
203,
565,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
1071,
5539,
31,
203,
565,
2874,
12,
11890,
5034,
516,
1731,
1578,
13,
1071,
1542,
67,
17612,
31,
203,
565,
2874,
12,
3890,
1578,
516,
18267,
13,
1071,
13494,
31,
203,
565,
2874,
12,
3890,
1578,
516,
18381,
13,
1071,
5073,
67,
28979,
31,
203,
565,
2874,
12,
3890,
1578,
516,
10269,
475,
13,
1071,
3294,
1346,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
10056,
86,
639,
67,
4173,
67,
3030,
281,
31,
7010,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender'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);
Transfer(burner, address(0), _value);
}
}
/**
* @title TriggmineToken
*/
contract TriggmineToken is StandardToken, BurnableToken, Ownable {
string public constant name = "Triggmine Coin";
string public constant symbol = "TRG";
uint256 public constant decimals = 18;
bool public released = false;
event Release();
address public holder;
mapping(address => uint) public lockedAddresses;
modifier isReleased () {
require(released || msg.sender == holder || msg.sender == owner);
require(lockedAddresses[msg.sender] <= now);
_;
}
function TriggmineToken() public {
owner = 0x7E83f1F82Ab7dDE49F620D2546BfFB0539058414;
totalSupply_ = 620000000 * (10 ** decimals);
balances[owner] = totalSupply_;
Transfer(0x0, owner, totalSupply_);
holder = owner;
}
function lockAddress(address _lockedAddress, uint256 _time) public onlyOwner returns (bool) {
require(balances[_lockedAddress] == 0 && lockedAddresses[_lockedAddress] == 0 && _time > now);
lockedAddresses[_lockedAddress] = _time;
return true;
}
function release() onlyOwner public returns (bool) {
require(!released);
released = true;
Release();
return true;
}
function getOwner() public view returns (address) {
return owner;
}
function transfer(address _to, uint256 _value) public isReleased returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public isReleased returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public isReleased returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public isReleased returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public isReleased returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
function transferOwnership(address newOwner) public onlyOwner {
address oldOwner = owner;
super.transferOwnership(newOwner);
if (oldOwner != holder) {
allowed[holder][oldOwner] = 0;
Approval(holder, oldOwner, 0);
}
if (owner != holder) {
allowed[holder][owner] = balances[holder];
Approval(holder, owner, balances[holder]);
}
}
}
contract TriggmineCrowdsale is Ownable {
using SafeMath for uint256;
uint256 public constant SALES_START = 1529938800; // Monday, June 25, 2018 3:00:00 PM
uint256 public constant SALES_END = 1538319600; // Sunday, September 30, 2018 3:00:00 PM
address public constant ASSET_MANAGER_WALLET = 0x7E83f1F82Ab7dDE49F620D2546BfFB0539058414;
address public constant ESCROW_WALLET = 0x2e9F22E2D559d9a5ce234AB722bc6e818FA5D079;
address public constant TOKEN_ADDRESS = 0x98F319D4dc58315796Ec8F06274fe2d4a5A69721; // Triggmine coin ERC20 contract address
uint256 public constant TOKEN_CENTS = 1000000000000000000; // 1 TRG is 1^18
uint256 public constant TOKEN_PRICE = 0.0001 ether;
uint256 public constant USD_HARD_CAP = 15000000;
uint256 public constant MIN_INVESTMENT = 25000;
uint public constant BONUS_50_100 = 10;
uint public constant BONUS_100_250 = 15;
uint public constant BONUS_250_500 = 20;
uint public constant BONUS_500 = 25;
mapping(address => uint256) public investments;
uint256 public investedUSD;
uint256 public investedETH;
uint256 public investedBTC;
uint256 public tokensPurchased;
uint256 public rate_ETHUSD;
uint256 public rate_BTCUSD;
address public whitelistSupplier;
mapping(address => bool) public whitelist;
event ContributedETH(address indexed receiver, uint contribution, uint contributionUSD, uint reward);
event ContributedBTC(address indexed receiver, uint contribution, uint contributionUSD, uint reward);
event WhitelistUpdated(address indexed participant, bool isWhitelisted);
constructor() public {
whitelistSupplier = msg.sender;
owner = ASSET_MANAGER_WALLET;
}
modifier onlyWhitelistSupplier() {
require(msg.sender == whitelistSupplier || msg.sender == owner);
_;
}
function contribute() public payable returns(bool) {
return contributeETH(msg.sender);
}
function contributeETH(address _participant) public payable returns(bool) {
require(now >= SALES_START && now < SALES_END);
require(whitelist[_participant]);
uint256 usdAmount = (msg.value * rate_ETHUSD) / 10**18;
investedUSD = investedUSD.add(usdAmount);
require(investedUSD <= USD_HARD_CAP);
investments[msg.sender] = investments[msg.sender].add(usdAmount);
require(investments[msg.sender] >= MIN_INVESTMENT);
uint bonusPercents = getBonusPercents(usdAmount);
uint totalTokens = getTotalTokens(msg.value, bonusPercents);
tokensPurchased = tokensPurchased.add(totalTokens);
require(TriggmineToken(TOKEN_ADDRESS).transferFrom(ASSET_MANAGER_WALLET, _participant, totalTokens));
investedETH = investedETH.add(msg.value);
ESCROW_WALLET.transfer(msg.value);
emit ContributedETH(_participant, msg.value, usdAmount, totalTokens);
return true;
}
function contributeBTC(address _participant, uint256 _btcAmount) public onlyWhitelistSupplier returns(bool) {
require(now >= SALES_START && now < SALES_END);
require(whitelist[_participant]);
uint256 usdAmount = (_btcAmount * rate_BTCUSD) / 10**8; // BTC amount should be provided in satoshi
investedUSD = investedUSD.add(usdAmount);
require(investedUSD <= USD_HARD_CAP);
investments[_participant] = investments[_participant].add(usdAmount);
require(investments[_participant] >= MIN_INVESTMENT);
uint bonusPercents = getBonusPercents(usdAmount);
uint256 ethAmount = (_btcAmount * rate_BTCUSD * 10**10) / rate_ETHUSD;
uint totalTokens = getTotalTokens(ethAmount, bonusPercents);
tokensPurchased = tokensPurchased.add(totalTokens);
require(TriggmineToken(TOKEN_ADDRESS).transferFrom(ASSET_MANAGER_WALLET, _participant, totalTokens));
investedBTC = investedBTC.add(_btcAmount);
emit ContributedBTC(_participant, _btcAmount, usdAmount, totalTokens);
return true;
}
function setRate_ETHUSD(uint256 _rate) public onlyWhitelistSupplier {
rate_ETHUSD = _rate;
}
function setRate_BTCUSD(uint256 _rate) public onlyWhitelistSupplier {
rate_BTCUSD = _rate;
}
function getBonusPercents(uint256 usdAmount) private pure returns(uint256) {
if (usdAmount >= 500000) {
return BONUS_500;
}
if (usdAmount >= 250000) {
return BONUS_250_500;
}
if (usdAmount >= 100000) {
return BONUS_100_250;
}
if (usdAmount >= 50000) {
return BONUS_50_100;
}
return 0;
}
function getTotalTokens(uint256 ethAmount, uint256 bonusPercents) private pure returns(uint256) {
// If there is some division reminder, we just collect it too.
uint256 tokensAmount = (ethAmount * TOKEN_CENTS) / TOKEN_PRICE;
require(tokensAmount > 0);
uint256 bonusTokens = (tokensAmount * bonusPercents) / 100;
uint256 totalTokens = tokensAmount.add(bonusTokens);
return totalTokens;
}
function () public payable {
contribute();
}
function addToWhitelist(address _participant) onlyWhitelistSupplier public returns(bool) {
if (whitelist[_participant]) {
return true;
}
whitelist[_participant] = true;
emit WhitelistUpdated(_participant, true);
return true;
}
function removeFromWhitelist(address _participant) onlyWhitelistSupplier public returns(bool) {
if (!whitelist[_participant]) {
return true;
}
whitelist[_participant] = false;
emit WhitelistUpdated(_participant, false);
return true;
}
function getTokenOwner() public view returns (address) {
return TriggmineToken(TOKEN_ADDRESS).getOwner();
}
function restoreTokenOwnership() public onlyOwner {
TriggmineToken(TOKEN_ADDRESS).transferOwnership(ASSET_MANAGER_WALLET);
}
} | Sunday, September 30, 2018 3:00:00 PM
| uint256 public constant SALES_END = 1538319600; | 10,985,307 | [
1,
55,
25649,
16,
3265,
337,
2558,
5196,
16,
14863,
890,
30,
713,
30,
713,
23544,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
1071,
5381,
17127,
11386,
67,
4415,
273,
4711,
7414,
23,
3657,
28133,
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
] |
//Address: 0xbc9ccc8a46d424de38b2e4df5f4a5001321c5d4c
//Contract name: E4RowEscrowU
//Balance: 0 Ether
//Verification Date: 4/12/2017
//Transacion Count: 4645
// CODE STARTS HERE
pragma solidity ^0.4.6;
contract iE4RowEscrow {
function getNumGamesStarted() constant returns (int ngames);
}
contract E4RowEscrowU is iE4RowEscrow {
event StatEvent(string msg);
event StatEventI(string msg, uint val);
event StatEventA(string msg, address addr);
uint constant MAX_PLAYERS = 5;
enum EndReason {erWinner, erTimeOut, erCheat}
enum SettingStateValue {debug, release, lockedRelease}
struct gameInstance {
address[5] players;
uint[5] playerPots;
uint numPlayers;
bool active; // active
bool allocd; // allocated already.
uint started; // time game started
uint lastMoved; // time game last moved
uint payout; // payout amont
address winner; // address of winner
EndReason reasonEnded; // enum reason of ended
}
struct arbiter {
mapping (uint => uint) gameIndexes; // game handles
uint arbToken; // 2 bytes
uint gameSlots; // a counter of alloc'd game structs (they can be reused)
uint gamesStarted; // total games started
uint gamesCompleted;
uint gamesCheated;
uint gamesTimedout;
uint numPlayers;
bool registered;
bool locked;
}
address public owner; // owner is address that deployed contract
address public tokenPartner; // the address of partner that receives rake fees
uint public numArbiters; // number of arbiters
int numGamesStarted; // total stats from all arbiters
uint public numGamesCompleted; // ...
uint public numGamesCheated; // ...
uint public numGamesTimedOut; // ...
uint public houseFeeHoldover; // hold fee till threshold
uint public lastPayoutTime; // timestamp of last payout time
// configurables
uint public gameTimeOut;
uint public registrationFee;
uint public houseFeeThreshold;
uint public payoutInterval;
uint raGas; // for register arb
uint sgGas;// for start game
uint wpGas; // for winner paid
uint rfGas; // for refund
uint feeGas; // for rake fee payout
SettingStateValue public settingsState = SettingStateValue.debug;
mapping (address => arbiter) arbiters;
mapping (uint => address) arbiterTokens;
mapping (uint => address) arbiterIndexes;
mapping (uint => gameInstance) games;
function E4RowEscrowU() public
{
owner = msg.sender;
}
function applySettings(SettingStateValue _state, uint _fee, uint _threshold, uint _timeout, uint _interval)
{
if (msg.sender != owner)
throw;
// ----------------------------------------------
// these items are tweakable for game optimization
// ----------------------------------------------
houseFeeThreshold = _threshold;
gameTimeOut = _timeout;
payoutInterval = _interval;
if (settingsState == SettingStateValue.lockedRelease) {
StatEvent("Settings Tweaked");
return;
}
settingsState = _state;
registrationFee = _fee;
// set default op gas - any futher settings done in set up gas
raGas = 150000;
sgGas = 110000;
wpGas = 20000;
rfGas = 20000;
feeGas = 360000;
StatEvent("Settings Changed");
}
//-----------------------------
// return an arbiter token from an hGame
//-----------------------------
function ArbTokFromHGame(uint _hGame) returns (uint _tok)
{
_tok = (_hGame / (2 ** 48)) & 0xffff;
}
//-----------------------------
// suicide the contract, not called for release
//-----------------------------
function HaraKiri()
{
if ((msg.sender == owner) && (settingsState != SettingStateValue.lockedRelease))
suicide(tokenPartner);
else
StatEvent("Kill attempt failed");
}
//-----------------------------
// default function
//-----------------------------
function() payable {
throw;
}
//------------------------------------------------------
// check active game and valid player, return player index
//-------------------------------------------------------
function validPlayer(uint _hGame, address _addr) internal returns( bool _valid, uint _pidx)
{
_valid = false;
if (activeGame(_hGame)) {
for (uint i = 0; i < games[_hGame].numPlayers; i++) {
if (games[_hGame].players[i] == _addr) {
_valid=true;
_pidx = i;
break;
}
}
}
}
//------------------------------------------------------
// check valid player, return player index
//-------------------------------------------------------
function validPlayer2(uint _hGame, address _addr) internal returns( bool _valid, uint _pidx)
{
_valid = false;
for (uint i = 0; i < games[_hGame].numPlayers; i++) {
if (games[_hGame].players[i] == _addr) {
_valid=true;
_pidx = i;
break;
}
}
}
//------------------------------------------------------
// check the arbiter is valid by comparing token
//------------------------------------------------------
function validArb(address _addr, uint _tok) internal returns( bool _valid)
{
_valid = false;
if ((arbiters[_addr].registered)
&& (arbiters[_addr].arbToken == _tok))
_valid = true;
}
//------------------------------------------------------
// check the arbiter is valid without comparing token
//------------------------------------------------------
function validArb2(address _addr) internal returns( bool _valid)
{
_valid = false;
if (arbiters[_addr].registered)
_valid = true;
}
//------------------------------------------------------
// check if arbiter is locked out
//------------------------------------------------------
function arbLocked(address _addr) internal returns( bool _locked)
{
_locked = false;
if (validArb2(_addr))
_locked = arbiters[_addr].locked;
}
//------------------------------------------------------
// return if game is active
//------------------------------------------------------
function activeGame(uint _hGame) internal returns( bool _valid)
{
_valid = false;
if ((_hGame > 0)
&& (games[_hGame].active))
_valid = true;
}
//------------------------------------------------------
// register game arbiter, max players of 5, pass in exact registration fee
//------------------------------------------------------
function registerArbiter(uint _numPlayers, uint _arbToken) public payable
{
if (msg.value != registrationFee) {
throw; //Insufficient Fee
}
if (_arbToken == 0) {
throw; // invalid token
}
if (arbTokenExists(_arbToken & 0xffff)) {
throw; // Token Already Exists
}
if (arbiters[msg.sender].registered) {
throw; // Arb Already Registered
}
if (_numPlayers > MAX_PLAYERS) {
throw; // Exceeds Max Players
}
arbiters[msg.sender].gamesStarted = 0;
arbiters[msg.sender].gamesCompleted = 0;
arbiters[msg.sender].gamesCheated = 0;
arbiters[msg.sender].gamesTimedout = 0;
arbiters[msg.sender].locked = false;
arbiters[msg.sender].arbToken = _arbToken & 0xffff;
arbiters[msg.sender].numPlayers = _numPlayers;
arbiters[msg.sender].registered = true;
arbiterTokens[(_arbToken & 0xffff)] = msg.sender;
arbiterIndexes[numArbiters++] = msg.sender;
if (!tokenPartner.call.gas(raGas).value(msg.value)()) {
//Statvent("Send Error"); // event never registers
throw;
}
StatEventI("Arb Added", _arbToken);
}
//------------------------------------------------------
// start game. pass in valid hGame containing token in top two bytes
//------------------------------------------------------
function startGame(uint _hGame, int _hkMax, address[] _players) public
{
uint ntok = ArbTokFromHGame(_hGame);
if (!validArb(msg.sender, ntok )) {
StatEvent("Invalid Arb");
return;
}
if (arbLocked(msg.sender)) {
StatEvent("Arb Locked");
return;
}
arbiter xarb = arbiters[msg.sender];
if (_players.length != xarb.numPlayers) {
StatEvent("Incorrect num players");
return;
}
if (_hkMax > 0)
houseKeep(_hkMax, ntok);
if (!games[_hGame].allocd) {
games[_hGame].allocd = true;
xarb.gameIndexes[xarb.gameSlots++] = _hGame;
}
numGamesStarted++; // always inc this one
xarb.gamesStarted++;
games[_hGame].active = true;
games[_hGame].started = now;
games[_hGame].lastMoved = now;
games[_hGame].payout = 0;
games[_hGame].winner = address(0);
games[_hGame].numPlayers = _players.length; // we'll be the judge of how many unique players
for (uint i = 0; i< _players.length && i < MAX_PLAYERS; i++) {
games[_hGame].players[i] = _players[i];
games[_hGame].playerPots[i] = 0;
}
StatEventI("Game Added", _hGame);
}
//------------------------------------------------------
// clean up game, set to inactive, refund any balances
// called by housekeep ONLY
//------------------------------------------------------
function abortGame(address _arb, uint _hGame, EndReason _reason) private returns(bool _success)
{
gameInstance nGame = games[_hGame];
// find game in game id,
if (nGame.active) {
_success = true;
for (uint i = 0; i < nGame.numPlayers; i++) {
if (nGame.playerPots[i] > 0) {
address a = nGame.players[i];
uint nsend = nGame.playerPots[i];
nGame.playerPots[i] = 0;
if (!a.call.gas(rfGas).value(nsend)()) {
houseFeeHoldover += nsend; // cannot refund due to error, give to the house
StatEventA("Cannot Refund Address", a);
}
}
}
nGame.active = false;
nGame.reasonEnded = _reason;
if (_reason == EndReason.erCheat) {
numGamesCheated++;
arbiters[_arb].gamesCheated++;
StatEvent("Game Aborted-Cheat");
} else if (_reason == EndReason.erTimeOut) {
numGamesTimedOut++;
arbiters[_arb].gamesTimedout++;
StatEvent("Game Aborted-TimeOut");
} else
StatEvent("Game Aborted!");
}
}
//------------------------------------------------------
// called by arbiter when winner is decided
//------------------------------------------------------
function winnerDecided(uint _hGame, address _winner, uint _winnerBal) public
{
if (!validArb(msg.sender, ArbTokFromHGame(_hGame))) {
StatEvent("Invalid Arb");
return; // no throw no change made
}
var (valid, pidx) = validPlayer(_hGame, _winner);
if (!valid) {
StatEvent("Invalid Player");
return;
}
arbiter xarb = arbiters[msg.sender];
gameInstance xgame = games[_hGame];
uint totalPot = 0;
if (xgame.playerPots[pidx] != _winnerBal) {
abortGame(msg.sender, _hGame, EndReason.erCheat);
return;
}
for (uint i = 0; i < xgame.numPlayers; i++) {
totalPot += xgame.playerPots[i];
}
uint nportion;
uint nremnant;
if (totalPot > 0) {
nportion = totalPot/50; // 2 percent fixed
nremnant = totalPot-nportion;
} else {
nportion = 0;
nremnant = 0;
}
xgame.lastMoved = now;
xgame.active = false;
xgame.reasonEnded = EndReason.erWinner;
xgame.winner = _winner;
xgame.payout = nremnant;
if (nportion > 0) {
houseFeeHoldover += nportion;
if ((houseFeeHoldover > houseFeeThreshold)
&& (now > (lastPayoutTime + payoutInterval))) {
uint ntmpho = houseFeeHoldover;
houseFeeHoldover = 0;
lastPayoutTime = now; // reset regardless of succeed/fail
if (!tokenPartner.call.gas(feeGas).value(ntmpho)()) {
houseFeeHoldover = ntmpho; // put it back
StatEvent("House-Fee Error1");
}
}
}
for (i = 0; i < xgame.numPlayers; i++) {
xgame.playerPots[i] = 0;
}
xarb.gamesCompleted++;
numGamesCompleted++;
if (nremnant > 0) {
if (!_winner.call.gas(wpGas).value(uint(nremnant))()) {
// StatEvent("Send Error");
throw; // if you cant pay the winner - very bad
} else {
StatEventI("Winner Paid", _hGame);
}
}
}
//------------------------------------------------------
// handle a bet made by a player, validate the player and game
// add to players balance
//------------------------------------------------------
function handleBet(uint _hGame) public payable
{
address narb = arbiterTokens[ArbTokFromHGame(_hGame)];
if (narb == address(0)) {
StatEvent("Invalid hGame");
if (settingsState != SettingStateValue.debug)
throw;
else
return;
}
var (valid, pidx) = validPlayer(_hGame, msg.sender);
if (!valid) {
StatEvent("Invalid Player");
if (settingsState != SettingStateValue.debug)
throw;
else
return;
}
games[_hGame].playerPots[pidx] += msg.value;
games[_hGame].lastMoved = now;
StatEventI("Bet Added", _hGame);
}
//------------------------------------------------------
// return if arb token exists
//------------------------------------------------------
function arbTokenExists(uint _tok) constant returns (bool _exists)
{
_exists = false;
if ((_tok > 0)
&& (arbiterTokens[_tok] != address(0))
&& arbiters[arbiterTokens[_tok]].registered)
_exists = true;
}
//------------------------------------------------------
// called by ico token contract
//------------------------------------------------------
function getNumGamesStarted() constant returns (int _games)
{
_games = numGamesStarted;
}
//------------------------------------------------------
// return arbiter game stats
//------------------------------------------------------
function getArbInfo(uint _idx) constant returns (address _addr, uint _started, uint _completed, uint _cheated, uint _timedOut)
{
if (_idx >= numArbiters) {
StatEvent("Invalid Arb");
return;
}
_addr = arbiterIndexes[_idx];
if ((_addr == address(0))
|| (!arbiters[_addr].registered)) {
StatEvent("Invalid Arb");
return;
}
arbiter xarb = arbiters[_addr];
_started = xarb.gamesStarted;
_completed = xarb.gamesCompleted;
_timedOut = xarb.gamesTimedout;
_cheated = xarb.gamesCheated;
}
//------------------------------------------------------
// scan for a game 10 minutes old
// if found abort the game, causing funds to be returned
//------------------------------------------------------
function houseKeep(int _max, uint _arbToken) public
{
uint gi;
address a;
int aborted = 0;
arbiter xarb = arbiters[msg.sender];// have to set it to something
if (msg.sender == owner) {
for (uint ar = 0; (ar < numArbiters) && (aborted < _max) ; ar++) {
a = arbiterIndexes[ar];
xarb = arbiters[a];
for ( gi = 0; (gi < xarb.gameSlots) && (aborted < _max); gi++) {
gameInstance ngame0 = games[xarb.gameIndexes[gi]];
if ((ngame0.active)
&& ((now - ngame0.lastMoved) > gameTimeOut)) {
abortGame(a, xarb.gameIndexes[gi], EndReason.erTimeOut);
++aborted;
}
}
}
} else {
if (!validArb(msg.sender, _arbToken))
StatEvent("Housekeep invalid arbiter");
else {
a = msg.sender;
xarb = arbiters[a];
for (gi = 0; (gi < xarb.gameSlots) && (aborted < _max); gi++) {
gameInstance ngame1 = games[xarb.gameIndexes[gi]];
if ((ngame1.active)
&& ((now - ngame1.lastMoved) > gameTimeOut)) {
abortGame(a, xarb.gameIndexes[gi], EndReason.erTimeOut);
++aborted;
}
}
}
}
}
//------------------------------------------------------
// return game info
//------------------------------------------------------
function getGameInfo(uint _hGame) constant returns (EndReason _reason, uint _players, uint _payout, bool _active, address _winner )
{
gameInstance ngame = games[_hGame];
_active = ngame.active;
_players = ngame.numPlayers;
_winner = ngame.winner;
_payout = ngame.payout;
_reason = ngame.reasonEnded;
}
//------------------------------------------------------
// return arbToken and low bytes from an HGame
//------------------------------------------------------
function checkHGame(uint _hGame) constant returns(uint _arbTok, uint _lowWords)
{
_arbTok = ArbTokFromHGame(_hGame);
_lowWords = _hGame & 0xffffffffffff;
}
//------------------------------------------------------
// get operation gas amounts
//------------------------------------------------------
function getOpGas() constant returns (uint _ra, uint _sg, uint _wp, uint _rf, uint _fg)
{
_ra = raGas; // register arb
_sg = sgGas; // start game
_wp = wpGas; // winner paid
_rf = rfGas; // refund
_fg = feeGas; // rake fee gas
}
//------------------------------------------------------
// set operation gas amounts for forwading operations
//------------------------------------------------------
function setOpGas(uint _ra, uint _sg, uint _wp, uint _rf, uint _fg)
{
if (msg.sender != owner)
throw;
raGas = _ra;
sgGas = _sg;
wpGas = _wp;
rfGas = _rf;
feeGas = _fg;
}
//------------------------------------------------------
// set a micheivous arbiter to locked
//------------------------------------------------------
function setArbiterLocked(address _addr, bool _lock) public
{
if (owner != msg.sender) {
throw;
} else if (!validArb2(_addr)) {
StatEvent("invalid arb");
} else {
arbiters[_addr].locked = _lock;
}
}
//------------------------------------------------------
// flush the house fees whenever commanded to.
// ignore the threshold and the last payout time
// but this time only reset lastpayouttime upon success
//------------------------------------------------------
function flushHouseFees()
{
if (msg.sender != owner) {
StatEvent("only owner calls this function");
} else if (houseFeeHoldover > 0) {
uint ntmpho = houseFeeHoldover;
houseFeeHoldover = 0;
if (!tokenPartner.call.gas(feeGas).value(ntmpho)()) {
houseFeeHoldover = ntmpho; // put it back
StatEvent("House-Fee Error2");
} else {
lastPayoutTime = now;
StatEvent("House-Fee Paid");
}
}
}
//------------------------------------------------------
// set the token partner
//------------------------------------------------------
function setTokenPartner(address _addr) public
{
if (msg.sender != owner) {
throw;
}
if ((settingsState == SettingStateValue.lockedRelease)
&& (tokenPartner == address(0))) {
tokenPartner = _addr;
StatEvent("Token Partner Final!");
} else if (settingsState != SettingStateValue.lockedRelease) {
tokenPartner = _addr;
StatEvent("Token Partner Assigned!");
}
}
// ----------------------------
// swap executor
// ----------------------------
function changeOwner(address _addr)
{
if (msg.sender != owner
|| settingsState == SettingStateValue.lockedRelease)
throw;
owner = _addr;
}
}
| ------------------------------------------------------ handle a bet made by a player, validate the player and game add to players balance------------------------------------------------------ | function handleBet(uint _hGame) public payable
{
address narb = arbiterTokens[ArbTokFromHGame(_hGame)];
if (narb == address(0)) {
StatEvent("Invalid hGame");
if (settingsState != SettingStateValue.debug)
throw;
else
return;
}
var (valid, pidx) = validPlayer(_hGame, msg.sender);
if (!valid) {
StatEvent("Invalid Player");
if (settingsState != SettingStateValue.debug)
throw;
else
return;
}
games[_hGame].playerPots[pidx] += msg.value;
games[_hGame].lastMoved = now;
StatEventI("Bet Added", _hGame);
}
| 7,291,716 | [
1,
9634,
13093,
1640,
279,
2701,
7165,
635,
279,
7291,
16,
1954,
326,
7291,
471,
7920,
527,
358,
18115,
11013,
9634,
13093,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
445,
1640,
38,
278,
12,
11890,
389,
76,
12496,
13,
1071,
8843,
429,
7010,
3639,
288,
203,
7734,
1758,
290,
6779,
273,
419,
70,
2165,
5157,
63,
686,
70,
20477,
1265,
44,
12496,
24899,
76,
12496,
13,
15533,
203,
7734,
309,
261,
82,
6779,
422,
1758,
12,
20,
3719,
288,
203,
13491,
8269,
1133,
2932,
1941,
366,
12496,
8863,
203,
13491,
309,
261,
4272,
1119,
480,
13274,
1119,
620,
18,
4148,
13,
203,
27573,
604,
31,
203,
13491,
469,
203,
27573,
327,
31,
203,
7734,
289,
203,
203,
7734,
569,
261,
877,
16,
293,
3465,
13,
273,
923,
12148,
24899,
76,
12496,
16,
1234,
18,
15330,
1769,
203,
7734,
309,
16051,
877,
13,
288,
203,
13491,
8269,
1133,
2932,
1941,
19185,
8863,
203,
13491,
309,
261,
4272,
1119,
480,
13274,
1119,
620,
18,
4148,
13,
203,
27573,
604,
31,
203,
13491,
469,
203,
27573,
327,
31,
203,
7734,
289,
203,
203,
7734,
28422,
63,
67,
76,
12496,
8009,
14872,
52,
6968,
63,
84,
3465,
65,
1011,
1234,
18,
1132,
31,
203,
7734,
28422,
63,
67,
76,
12496,
8009,
2722,
25317,
273,
2037,
31,
203,
203,
7734,
8269,
1133,
45,
2932,
38,
278,
25808,
3113,
389,
76,
12496,
1769,
203,
203,
3639,
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
] |
./full_match/5/0xd559b9e1d3214179b8D5d177beCBd4eEB827Db6f/sources/contracts/smart-wallet/non-upgradeable/Account.sol | solhint-disable-next-line no-empty-blocks | {
using ECDSA for bytes32;
State
bytes32 public constant SIGNER_ROLE = keccak256("SIGNER_ROLE");
address public immutable factory;
IEntryPoint private immutable entrypointContract;
Constructor, Initializer, Modifiers
pragma solidity ^0.8.11;
import "./../utils/BaseAccount.sol";
import "../../extension/Multicall.sol";
import "../../openzeppelin-presets/utils/cryptography/ECDSA.sol";
receive() external payable virtual {}
constructor(IEntryPoint _entrypoint, address _factory) {
_disableInitializers();
factory = _factory;
entrypointContract = _entrypoint;
}
function initialize(address _defaultAdmin, bytes calldata) public virtual initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin);
}
modifier onlyAdminOrEntrypoint() {
require(
msg.sender == address(entryPoint()) || hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"Account: not admin or EntryPoint."
);
_;
}
View functions
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155Receiver) returns (bool) {
return
interfaceId == type(IERC1155Receiver).interfaceId ||
interfaceId == type(IERC721Receiver).interfaceId ||
super.supportsInterface(interfaceId);
}
function entryPoint() public view virtual override returns (IEntryPoint) {
return entrypointContract;
}
function getDeposit() public view returns (uint256) {
return entryPoint().balanceOf(address(this));
}
function isValidSigner(address _signer) public view virtual returns (bool) {
return hasRole(SIGNER_ROLE, _signer) || hasRole(DEFAULT_ADMIN_ROLE, _signer);
}
function isValidSignature(bytes32 _hash, bytes memory _signature)
public
view
virtual
override
returns (bytes4 magicValue)
{
address signer = _hash.recover(_signature);
if (isValidSigner(signer)) {
magicValue = MAGICVALUE;
}
}
function isValidSignature(bytes32 _hash, bytes memory _signature)
public
view
virtual
override
returns (bytes4 magicValue)
{
address signer = _hash.recover(_signature);
if (isValidSigner(signer)) {
magicValue = MAGICVALUE;
}
}
External functions
function execute(
address _target,
uint256 _value,
bytes calldata _calldata
) external virtual onlyAdminOrEntrypoint {
_call(_target, _value, _calldata);
}
function executeBatch(
address[] calldata _target,
uint256[] calldata _value,
bytes[] calldata _calldata
) external virtual onlyAdminOrEntrypoint {
require(_target.length == _calldata.length && _target.length == _value.length, "Account: wrong array lengths.");
for (uint256 i = 0; i < _target.length; i++) {
_call(_target[i], _value[i], _calldata[i]);
}
}
function executeBatch(
address[] calldata _target,
uint256[] calldata _value,
bytes[] calldata _calldata
) external virtual onlyAdminOrEntrypoint {
require(_target.length == _calldata.length && _target.length == _value.length, "Account: wrong array lengths.");
for (uint256 i = 0; i < _target.length; i++) {
_call(_target[i], _value[i], _calldata[i]);
}
}
function addDeposit() public payable {
}
entryPoint().depositTo{ value: msg.value }(address(this));
function withdrawDepositTo(address payable withdrawAddress, uint256 amount) public onlyRole(DEFAULT_ADMIN_ROLE) {
entryPoint().withdrawTo(withdrawAddress, amount);
}
Internal functions
function _call(
address _target,
uint256 value,
bytes memory _calldata
) internal {
if (!success) {
assembly {
revert(add(result, 32), mload(result))
}
}
}
(bool success, bytes memory result) = _target.call{ value: value }(_calldata);
Internal functions
function _call(
address _target,
uint256 value,
bytes memory _calldata
) internal {
if (!success) {
assembly {
revert(add(result, 32), mload(result))
}
}
}
Internal functions
function _call(
address _target,
uint256 value,
bytes memory _calldata
) internal {
if (!success) {
assembly {
revert(add(result, 32), mload(result))
}
}
}
function _validateSignature(UserOperation calldata userOp, bytes32 userOpHash)
internal
virtual
override
returns (uint256 validationData)
{
bytes32 hash = userOpHash.toEthSignedMessageHash();
address signer = hash.recover(userOp.signature);
if (!isValidSigner(signer)) return SIG_VALIDATION_FAILED;
return 0;
}
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
if (role == SIGNER_ROLE && factory.code.length > 0) {
AccountFactory(factory).onSignerAdded(account);
}
}
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
if (role == SIGNER_ROLE && factory.code.length > 0) {
AccountFactory(factory).onSignerAdded(account);
}
}
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
if (role == SIGNER_ROLE && factory.code.length > 0) {
AccountFactory(factory).onSignerRemoved(account);
}
}
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
if (role == SIGNER_ROLE && factory.code.length > 0) {
AccountFactory(factory).onSignerRemoved(account);
}
}
function _canSetContractURI() internal view virtual override returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
}
| 11,589,086 | [
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
5531,
17,
7996,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
95,
203,
565,
1450,
7773,
19748,
364,
1731,
1578,
31,
203,
203,
27573,
3287,
203,
203,
565,
1731,
1578,
1071,
5381,
12057,
654,
67,
16256,
273,
417,
24410,
581,
5034,
2932,
11260,
654,
67,
16256,
8863,
203,
203,
565,
1758,
1071,
11732,
3272,
31,
203,
203,
565,
467,
1622,
2148,
3238,
11732,
26076,
8924,
31,
203,
203,
10792,
11417,
16,
4378,
3926,
16,
3431,
3383,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2499,
31,
203,
203,
5666,
25165,
6216,
5471,
19,
2171,
3032,
18,
18281,
14432,
203,
5666,
315,
16644,
6447,
19,
5049,
335,
454,
18,
18281,
14432,
203,
5666,
315,
16644,
3190,
94,
881,
84,
292,
267,
17,
12202,
2413,
19,
5471,
19,
22784,
15669,
19,
7228,
19748,
18,
18281,
14432,
203,
203,
565,
6798,
1435,
3903,
8843,
429,
5024,
2618,
203,
565,
3885,
12,
45,
1622,
2148,
389,
4099,
1153,
16,
1758,
389,
6848,
13,
288,
203,
3639,
389,
8394,
4435,
8426,
5621,
203,
3639,
3272,
273,
389,
6848,
31,
203,
3639,
26076,
8924,
273,
389,
4099,
1153,
31,
203,
565,
289,
203,
203,
565,
445,
4046,
12,
2867,
389,
1886,
4446,
16,
1731,
745,
892,
13,
1071,
5024,
12562,
288,
203,
3639,
389,
8401,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
389,
1886,
4446,
1769,
203,
565,
289,
203,
203,
565,
9606,
1338,
4446,
1162,
1622,
1153,
1435,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
1758,
12,
4099,
2148,
10756,
747,
28335,
12,
5280,
67,
15468,
67,
16256,
16,
1234,
18,
2
] |
./full_match/1/0xc4FeDaF6f2B6B900f5d5F8b702aa09D9BdBFDC21/sources/contracts/CNPJ-v2.sol | ================================================== Lockable ================================================== | address private _locker;
| 16,507,386 | [
1,
20775,
631,
3488,
429,
422,
20775,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3238,
389,
739,
264,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xf9231D28B34CD77A08542f73ca87c4411B1b8B56/sources/vesper-strategies/contracts/strategies/Strategy.sol | * @notice Update swapper @param _swapper swapper address/ | function updateSwapper(IRoutedSwapper _swapper) external onlyGovernor {
require(address(_swapper) != address(0), "swapper-address-is-zero");
require(_swapper != swapper, "swapper-is-same");
emit UpdatedSwapper(swapper, _swapper);
swapper = _swapper;
}
| 4,930,767 | [
1,
1891,
7720,
457,
225,
389,
22270,
457,
7720,
457,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12521,
457,
12,
45,
4583,
329,
12521,
457,
389,
22270,
457,
13,
3903,
1338,
43,
1643,
29561,
288,
203,
3639,
2583,
12,
2867,
24899,
22270,
457,
13,
480,
1758,
12,
20,
3631,
315,
22270,
457,
17,
2867,
17,
291,
17,
7124,
8863,
203,
3639,
2583,
24899,
22270,
457,
480,
7720,
457,
16,
315,
22270,
457,
17,
291,
17,
14307,
8863,
203,
3639,
3626,
19301,
12521,
457,
12,
22270,
457,
16,
389,
22270,
457,
1769,
203,
3639,
7720,
457,
273,
389,
22270,
457,
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
] |
./full_match/250/0x1CD4f1E9336555af8398A2619E7ff2712E8F4046/sources/contracts/Qissa.sol | * Adds users to the project. @param _users - a list of User struct with a quota/ adding users to mapping | function addUsers(IQissaFactory.UserInput[] memory _users) external onlyInProduction onlyOwner {
_addUsers(_users);
}
| 13,223,197 | [
1,
3655,
3677,
358,
326,
1984,
18,
225,
389,
5577,
300,
279,
666,
434,
2177,
1958,
598,
279,
13257,
19,
6534,
3677,
358,
2874,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
6588,
12,
45,
53,
21269,
1733,
18,
29423,
8526,
3778,
389,
5577,
13,
3903,
1338,
382,
31590,
1338,
5541,
288,
203,
3639,
389,
1289,
6588,
24899,
5577,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
// from https://github.com/ConsenSys/Project-Alchemy/blob/master/contracts/BLAKE2b/BLAKE2b.sol
pragma solidity ^0.7.0;
contract Blake2bConsenSys {
uint64[8] public IV = [
0x6a09e667f3bcc908,
0xbb67ae8584caa73b,
0x3c6ef372fe94f82b,
0xa54ff53a5f1d36f1,
0x510e527fade682d1,
0x9b05688c2b3e6c1f,
0x1f83d9abfb41bd6b,
0x5be0cd19137e2179
];
uint64 constant MASK_0 = 0xFF00000000000000;
uint64 constant MASK_1 = 0x00FF000000000000;
uint64 constant MASK_2 = 0x0000FF0000000000;
uint64 constant MASK_3 = 0x000000FF00000000;
uint64 constant MASK_4 = 0x00000000FF000000;
uint64 constant MASK_5 = 0x0000000000FF0000;
uint64 constant MASK_6 = 0x000000000000FF00;
uint64 constant MASK_7 = 0x00000000000000FF;
uint64 constant SHIFT_0 = 0x0100000000000000;
uint64 constant SHIFT_1 = 0x0000010000000000;
uint64 constant SHIFT_2 = 0x0000000001000000;
uint64 constant SHIFT_3 = 0x0000000000000100;
struct Blake2bConsenSys_ctx {
uint256[4] b; //input buffer
uint64[8] h; //chained state
uint128 t; //total bytes
uint64 c; //Size of b
uint256 outlen; //diigest output size
}
// Mixing Function
function G(
uint64[16] memory v,
uint256 a,
uint256 b,
uint256 c,
uint256 d,
uint64 x,
uint64 y
) public pure {
// Dereference to decrease memory reads
uint64 va = v[a];
uint64 vb = v[b];
uint64 vc = v[c];
uint64 vd = v[d];
//Optimised mixing function
assembly {
// v[a] := (v[a] + v[b] + x) mod 2**64
va := addmod(add(va, vb), x, 0x10000000000000000)
//v[d] := (v[d] ^ v[a]) >>> 32
vd := xor(div(xor(vd, va), 0x100000000), mulmod(xor(vd, va), 0x100000000, 0x10000000000000000))
//v[c] := (v[c] + v[d]) mod 2**64
vc := addmod(vc, vd, 0x10000000000000000)
//v[b] := (v[b] ^ v[c]) >>> 24
vb := xor(div(xor(vb, vc), 0x1000000), mulmod(xor(vb, vc), 0x10000000000, 0x10000000000000000))
// v[a] := (v[a] + v[b] + y) mod 2**64
va := addmod(add(va, vb), y, 0x10000000000000000)
//v[d] := (v[d] ^ v[a]) >>> 16
vd := xor(div(xor(vd, va), 0x10000), mulmod(xor(vd, va), 0x1000000000000, 0x10000000000000000))
//v[c] := (v[c] + v[d]) mod 2**64
vc := addmod(vc, vd, 0x10000000000000000)
// v[b] := (v[b] ^ v[c]) >>> 63
vb := xor(div(xor(vb, vc), 0x8000000000000000), mulmod(xor(vb, vc), 0x2, 0x10000000000000000))
}
v[a] = va;
v[b] = vb;
v[c] = vc;
v[d] = vd;
}
function compress(Blake2bConsenSys_ctx memory ctx, bool last) internal view {
//TODO: Look into storing these as uint256[4]
uint64[16] memory v;
uint64[16] memory m;
for (uint256 i = 0; i < 8; i++) {
v[i] = ctx.h[i]; // v[:8] = h[:8]
v[i + 8] = IV[i]; // v[8:] = IV
}
//
v[12] = v[12] ^ uint64(ctx.t % 2**64); //Lower word of t
v[13] = v[13] ^ uint64(ctx.t / 2**64);
if (last) v[14] = ~v[14]; //Finalization flag
uint64 mi; //Temporary stack variable to decrease memory ops
uint256 b; // Input buffer
for (uint256 i = 0; i < 16; i++) {
//Operate 16 words at a time
uint256 k = i % 4; //Current buffer word
mi = 0;
if (k == 0) {
b = ctx.b[i / 4]; //Load relevant input into buffer
}
//Extract relevent input from buffer
assembly {
mi := and(div(b, exp(2, mul(64, sub(3, k)))), 0xFFFFFFFFFFFFFFFF)
}
//Flip endianness
m[i] = getWords(mi);
}
//Mix m
G(v, 0, 4, 8, 12, m[0], m[1]);
G(v, 1, 5, 9, 13, m[2], m[3]);
G(v, 2, 6, 10, 14, m[4], m[5]);
G(v, 3, 7, 11, 15, m[6], m[7]);
G(v, 0, 5, 10, 15, m[8], m[9]);
G(v, 1, 6, 11, 12, m[10], m[11]);
G(v, 2, 7, 8, 13, m[12], m[13]);
G(v, 3, 4, 9, 14, m[14], m[15]);
G(v, 0, 4, 8, 12, m[14], m[10]);
G(v, 1, 5, 9, 13, m[4], m[8]);
G(v, 2, 6, 10, 14, m[9], m[15]);
G(v, 3, 7, 11, 15, m[13], m[6]);
G(v, 0, 5, 10, 15, m[1], m[12]);
G(v, 1, 6, 11, 12, m[0], m[2]);
G(v, 2, 7, 8, 13, m[11], m[7]);
G(v, 3, 4, 9, 14, m[5], m[3]);
G(v, 0, 4, 8, 12, m[11], m[8]);
G(v, 1, 5, 9, 13, m[12], m[0]);
G(v, 2, 6, 10, 14, m[5], m[2]);
G(v, 3, 7, 11, 15, m[15], m[13]);
G(v, 0, 5, 10, 15, m[10], m[14]);
G(v, 1, 6, 11, 12, m[3], m[6]);
G(v, 2, 7, 8, 13, m[7], m[1]);
G(v, 3, 4, 9, 14, m[9], m[4]);
G(v, 0, 4, 8, 12, m[7], m[9]);
G(v, 1, 5, 9, 13, m[3], m[1]);
G(v, 2, 6, 10, 14, m[13], m[12]);
G(v, 3, 7, 11, 15, m[11], m[14]);
G(v, 0, 5, 10, 15, m[2], m[6]);
G(v, 1, 6, 11, 12, m[5], m[10]);
G(v, 2, 7, 8, 13, m[4], m[0]);
G(v, 3, 4, 9, 14, m[15], m[8]);
G(v, 0, 4, 8, 12, m[9], m[0]);
G(v, 1, 5, 9, 13, m[5], m[7]);
G(v, 2, 6, 10, 14, m[2], m[4]);
G(v, 3, 7, 11, 15, m[10], m[15]);
G(v, 0, 5, 10, 15, m[14], m[1]);
G(v, 1, 6, 11, 12, m[11], m[12]);
G(v, 2, 7, 8, 13, m[6], m[8]);
G(v, 3, 4, 9, 14, m[3], m[13]);
G(v, 0, 4, 8, 12, m[2], m[12]);
G(v, 1, 5, 9, 13, m[6], m[10]);
G(v, 2, 6, 10, 14, m[0], m[11]);
G(v, 3, 7, 11, 15, m[8], m[3]);
G(v, 0, 5, 10, 15, m[4], m[13]);
G(v, 1, 6, 11, 12, m[7], m[5]);
G(v, 2, 7, 8, 13, m[15], m[14]);
G(v, 3, 4, 9, 14, m[1], m[9]);
G(v, 0, 4, 8, 12, m[12], m[5]);
G(v, 1, 5, 9, 13, m[1], m[15]);
G(v, 2, 6, 10, 14, m[14], m[13]);
G(v, 3, 7, 11, 15, m[4], m[10]);
G(v, 0, 5, 10, 15, m[0], m[7]);
G(v, 1, 6, 11, 12, m[6], m[3]);
G(v, 2, 7, 8, 13, m[9], m[2]);
G(v, 3, 4, 9, 14, m[8], m[11]);
G(v, 0, 4, 8, 12, m[13], m[11]);
G(v, 1, 5, 9, 13, m[7], m[14]);
G(v, 2, 6, 10, 14, m[12], m[1]);
G(v, 3, 7, 11, 15, m[3], m[9]);
G(v, 0, 5, 10, 15, m[5], m[0]);
G(v, 1, 6, 11, 12, m[15], m[4]);
G(v, 2, 7, 8, 13, m[8], m[6]);
G(v, 3, 4, 9, 14, m[2], m[10]);
G(v, 0, 4, 8, 12, m[6], m[15]);
G(v, 1, 5, 9, 13, m[14], m[9]);
G(v, 2, 6, 10, 14, m[11], m[3]);
G(v, 3, 7, 11, 15, m[0], m[8]);
G(v, 0, 5, 10, 15, m[12], m[2]);
G(v, 1, 6, 11, 12, m[13], m[7]);
G(v, 2, 7, 8, 13, m[1], m[4]);
G(v, 3, 4, 9, 14, m[10], m[5]);
G(v, 0, 4, 8, 12, m[10], m[2]);
G(v, 1, 5, 9, 13, m[8], m[4]);
G(v, 2, 6, 10, 14, m[7], m[6]);
G(v, 3, 7, 11, 15, m[1], m[5]);
G(v, 0, 5, 10, 15, m[15], m[11]);
G(v, 1, 6, 11, 12, m[9], m[14]);
G(v, 2, 7, 8, 13, m[3], m[12]);
G(v, 3, 4, 9, 14, m[13], m[0]);
G(v, 0, 4, 8, 12, m[0], m[1]);
G(v, 1, 5, 9, 13, m[2], m[3]);
G(v, 2, 6, 10, 14, m[4], m[5]);
G(v, 3, 7, 11, 15, m[6], m[7]);
G(v, 0, 5, 10, 15, m[8], m[9]);
G(v, 1, 6, 11, 12, m[10], m[11]);
G(v, 2, 7, 8, 13, m[12], m[13]);
G(v, 3, 4, 9, 14, m[14], m[15]);
G(v, 0, 4, 8, 12, m[14], m[10]);
G(v, 1, 5, 9, 13, m[4], m[8]);
G(v, 2, 6, 10, 14, m[9], m[15]);
G(v, 3, 7, 11, 15, m[13], m[6]);
G(v, 0, 5, 10, 15, m[1], m[12]);
G(v, 1, 6, 11, 12, m[0], m[2]);
G(v, 2, 7, 8, 13, m[11], m[7]);
G(v, 3, 4, 9, 14, m[5], m[3]);
//XOR current state with both halves of v
for (uint256 i = 0; i < 8; ++i) {
ctx.h[i] = ctx.h[i] ^ v[i] ^ v[i + 8];
}
}
function init(
Blake2bConsenSys_ctx memory ctx,
uint64 outlen,
bytes memory key,
uint64[2] memory salt,
uint64[2] memory person
) internal view {
if (outlen == 0 || outlen > 64 || key.length > 64) revert();
//Initialize chained-state to IV
for (uint256 j = 0; j < 8; j++) {
ctx.h[j] = IV[j];
}
// Set up parameter block
ctx.h[0] = ctx.h[0] ^ 0x01010000 ^ shift_left(uint64(key.length), 8) ^ outlen;
ctx.h[4] = ctx.h[4] ^ salt[0];
ctx.h[5] = ctx.h[5] ^ salt[1];
ctx.h[6] = ctx.h[6] ^ person[0];
ctx.h[7] = ctx.h[7] ^ person[1];
ctx.outlen = outlen;
//Run hash once with key as input
if (key.length > 0) {
update(ctx, key);
ctx.c = 128;
}
}
function update(Blake2bConsenSys_ctx memory ctx, bytes memory input) internal view {
for (uint256 i = 0; i < input.length; i++) {
//If buffer is full, update byte counters and compress
if (ctx.c == 128) {
ctx.t += ctx.c;
compress(ctx, false);
ctx.c = 0;
}
//Update temporary counter c
uint256 c = ctx.c++;
// b -> ctx.b
uint256[4] memory b = ctx.b;
uint8 a = uint8(input[i]);
// ctx.b[c] = a
assembly {
mstore8(add(b, c), a)
}
}
}
function finalize(Blake2bConsenSys_ctx memory ctx, uint64[8] memory out) internal view {
// Add any uncounted bytes
ctx.t += ctx.c;
// Compress with finalization flag
compress(ctx, true);
//Flip little to big endian and store in output buffer
for (uint256 i = 0; i < ctx.outlen / 8; i++) {
out[i] = getWords(ctx.h[i]);
}
//Properly pad output if it doesn't fill a full word
if (ctx.outlen < 64) {
out[ctx.outlen / 8] = shift_right(getWords(ctx.h[ctx.outlen / 8]), 64 - 8 * (ctx.outlen % 8));
}
}
//Helper function for full hash function
function blake2b(
bytes memory input,
bytes memory key,
bytes memory salt,
bytes memory personalization,
uint64 outlen
) public view returns (uint64[8] memory) {
Blake2bConsenSys_ctx memory ctx;
uint64[8] memory out;
init(ctx, outlen, key, formatInput(salt), formatInput(personalization));
update(ctx, input);
finalize(ctx, out);
return out;
}
function blake2b(
bytes memory input,
bytes memory key,
uint64 outlen
) public view returns (uint64[8] memory) {
return blake2b(input, key, "", "", outlen);
}
// Utility functions
//Flips endianness of words
function getWords(uint64 a) public pure returns (uint64 b) {
return
((a & MASK_0) / SHIFT_0) ^
((a & MASK_1) / SHIFT_1) ^
((a & MASK_2) / SHIFT_2) ^
((a & MASK_3) / SHIFT_3) ^
((a & MASK_4) * SHIFT_3) ^
((a & MASK_5) * SHIFT_2) ^
((a & MASK_6) * SHIFT_1) ^
((a & MASK_7) * SHIFT_0);
}
function shift_right(uint64 a, uint256 shift) public pure returns (uint64 b) {
return uint64(a / 2**shift);
}
function shift_left(uint64 a, uint256 shift) public pure returns (uint64) {
return uint64((a * 2**shift) % (2**64));
}
//bytes -> uint64[2]
function formatInput(bytes memory input) public pure returns (uint64[2] memory output) {
for (uint256 i = 0; i < input.length; i++) {
output[i / 8] = output[i / 8] ^ shift_left(uint64(uint8(input[i])), 64 - 8 * ((i % 8) + 1));
}
output[0] = getWords(output[0]);
output[1] = getWords(output[1]);
}
function formatOutput(uint64[8] memory input) public pure returns (bytes32[2] memory) {
bytes32[2] memory result;
for (uint256 i = 0; i < 8; i++) {
result[i / 4] = result[i / 4] ^ bytes32(input[i] * 2**(64 * (3 - (i % 4))));
}
return result;
}
}
| Add any uncounted bytes Compress with finalization flagFlip little to big endian and store in output bufferProperly pad output if it doesn't fill a full word | function finalize(Blake2bConsenSys_ctx memory ctx, uint64[8] memory out) internal view {
ctx.t += ctx.c;
compress(ctx, true);
for (uint256 i = 0; i < ctx.outlen / 8; i++) {
out[i] = getWords(ctx.h[i]);
}
if (ctx.outlen < 64) {
out[ctx.outlen / 8] = shift_right(getWords(ctx.h[ctx.outlen / 8]), 64 - 8 * (ctx.outlen % 8));
}
}
| 13,017,358 | [
1,
986,
1281,
6301,
592,
329,
1731,
25698,
598,
727,
1588,
2982,
28535,
12720,
358,
5446,
14759,
471,
1707,
316,
876,
1613,
626,
457,
715,
4627,
876,
309,
518,
3302,
1404,
3636,
279,
1983,
2076,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
12409,
12,
4802,
911,
22,
70,
9054,
275,
12712,
67,
5900,
3778,
1103,
16,
2254,
1105,
63,
28,
65,
3778,
596,
13,
2713,
1476,
288,
203,
3639,
1103,
18,
88,
1011,
1103,
18,
71,
31,
203,
203,
3639,
8099,
12,
5900,
16,
638,
1769,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
1103,
18,
659,
1897,
342,
1725,
31,
277,
27245,
288,
203,
5411,
596,
63,
77,
65,
273,
336,
7363,
12,
5900,
18,
76,
63,
77,
19226,
203,
3639,
289,
203,
203,
3639,
309,
261,
5900,
18,
659,
1897,
411,
5178,
13,
288,
203,
5411,
596,
63,
5900,
18,
659,
1897,
342,
1725,
65,
273,
4654,
67,
4083,
12,
588,
7363,
12,
5900,
18,
76,
63,
5900,
18,
659,
1897,
342,
1725,
65,
3631,
5178,
300,
1725,
380,
261,
5900,
18,
659,
1897,
738,
1725,
10019,
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
] |
pragma solidity ^0.4.24;
contract SafeMath {
uint256 constant public MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function safeAdd(uint256 x, uint256 y) constant internal returns (uint256 z) {
if (x > MAX_UINT256 - y) revert();
return x + y;
}
function safeSub(uint256 x, uint256 y) constant internal returns (uint256 z) {
if (x < y) revert();
return x - y;
}
function safeMul(uint256 x, uint256 y) constant internal returns (uint256 z) {
if (y == 0) return 0;
if (x > MAX_UINT256 / y) revert();
return x * y;
}
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract ContractReceiver {
function tokenFallback(address _from, uint _value, bytes _data);
}
contract MelonBitIndex_Erc223Token is SafeMath, Owned {
//event Transfer(address indexed from, address indexed to, uint tokens);
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
mapping(address => uint) balances;
string public name = "MelonBit Market Index Erc223Token";
string public symbol = "MMX";
uint8 public decimals = 8;
uint256 public totalSupply;
//function MelonBitIndex_Erc223Token()
constructor() public
{
totalSupply = 10000000000 * 10**uint(decimals);
balances[owner] = totalSupply;
//emit Transfer(address(0), owner, totalSupply);
}
// Function to access name of token .
function name() constant returns (string _name) { return name; }
// Function to access symbol of token .
function symbol() constant returns (string _symbol) { return symbol; }
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) { return decimals; }
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) { return totalSupply; }
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) returns (bool success) {
if(isContract(_to)) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data) returns (bool success) {
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value) returns (bool success) {
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
} | Function to access decimals of token . | function decimals() constant returns (uint8 _decimals) { return decimals; }
| 6,843,178 | [
1,
2083,
358,
2006,
15105,
434,
1147,
263,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
15105,
1435,
5381,
1135,
261,
11890,
28,
389,
31734,
13,
288,
327,
15105,
31,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-10-19
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.4.24;
//-----------------------------------------------------------------------------//
// Name : MPadLaunchPad //
// Swap tokens to claim launch tokens //
// Distribution Contract //
//-----------------------------------------------------------------------------//
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IBEP20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) 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 IMainToken{
function transfer(address, uint256) public pure returns (bool);
function transferFrom(address, address, uint256) public pure returns (bool);
}
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b,"Invalid values");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0,"Invalid values");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a,"Invalid values");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a,"Invalid values");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0,"Invalid values");
return a % b;
}
}
contract MultiPadLaunchApp is IBEP20 {
using SafeMath for uint256;
IMainToken iMainToken;
//variable declaration
address private _owner;
string private _name;
string private _symbol;
uint8 private _decimals = 18;
uint256 private _totalSupply;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
// Special business use case variables
mapping (address => bool) _whitelistedAddress;
mapping (address => uint256) _recordSale;
mapping (address => bool) _addressLocked;
mapping (address => uint256) _finalSoldAmount;
mapping (address => mapping(uint256 => bool)) reEntrance;
mapping (address => uint256) specialAddBal;
mapping (address => uint256) _contributionBNB;
mapping (address => mapping(uint256 => uint256)) _claimedByUser;
mapping (address =>mapping(uint256 => uint256))_thisSaleContribution;
mapping (address => uint) _multiplier;
address[] private _whitelistedUserAddresses;
uint256 private saleStartTime;
uint256 private saleEndTime;
uint256 private saleMinimumAmount;
uint256 private saleMaximumAmount;
uint256 private saleId = 0;
uint256 private tokenPrice;
uint256 private deploymentTime;
uint256 private pricePerToken;
uint256 private hardCap;
uint256 private decimalBalancer = 1000000000;
uint256 private IDOAvailable;
address private tokenContractAddress;
bool whitelistFlag = true;
address private IDOAddress;
string private _baseName;
uint256 private _claimTime1;
constructor (string memory name, string memory symbol, uint256 totalSupply, address owner, uint256 _totalDummySupply) public {
_name = name;
_symbol = symbol;
_totalSupply = totalSupply*(10**uint256(_decimals));
_balances[owner] = _totalSupply;
_owner = owner;
deploymentTime = block.timestamp;
_transfer(_owner,address(this),_totalDummySupply*(10**uint256(_decimals)));
}
function setTokenAddress(address _ITokenContract) onlyOwner external returns(bool){
tokenContractAddress = _ITokenContract;
iMainToken = IMainToken(_ITokenContract);
}
/* ----------------------------------------------------------------------------
* View only functions
* ----------------------------------------------------------------------------
*/
/**
* @return the name of the token.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @return the name of the token.
*/
function setBaseName(string baseName) external onlyOwner returns (bool) {
_baseName = baseName;
return true;
}
/**
* @return the name of the token.
*/
function baseName() external view returns (string memory) {
return _baseName;
}
/**
* @return the symbol of the token.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Total number of tokens in existence.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @return the number of decimals of the token.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/* ----------------------------------------------------------------------------
* Transfer, allow and burn functions
* ----------------------------------------------------------------------------
*/
/**
* @dev Transfer token for a specified addresses.
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0),"Invalid to address");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/*----------------------------------------------------------------------------
* Functions for owner
*----------------------------------------------------------------------------
*/
/**
* @dev get address of smart contract owner
* @return address of owner
*/
function getowner() external view returns (address) {
return _owner;
}
/**
* @dev modifier to check if the message sender is owner
*/
modifier onlyOwner() {
require(isOwner(),"You are not authenticate to make this transfer");
_;
}
/**
* @dev Internal function for modifier
*/
function isOwner() internal view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Transfer ownership of the smart contract. For owner only
* @return request status
*/
function transferOwnership(address newOwner) external onlyOwner returns (bool){
require(newOwner != address(0), "Owner address cant be zero");
_owner = newOwner;
return true;
}
/* ----------------------------------------------------------------------------
* Functions for Additional Business Logic For Owner Functions
* ----------------------------------------------------------------------------
*/
/**
* @dev Whitelist Addresses for further transactions
* @param _userAddresses Array of user addresses
*/
function whitelistUserAdress(address[] _userAddresses, uint[] _multiplierAmount) external onlyOwner returns(bool){
uint256 count = _userAddresses.length;
require(count < 201, "Array Overflow"); //Max 200 enteries at a time
for (uint256 i = 0; i < count; i++){
_whitelistedUserAddresses.push(_userAddresses[i]);
_whitelistedAddress[_userAddresses[i]] = true;
_multiplier[_userAddresses[i]] = _multiplierAmount[i];
}
return true;
}
//Get the multiplier details
function getMultiplierbyAddress(address _userAddress) external view returns(uint256){
return _multiplier[_userAddress];
}
/**
* @dev get the list of whitelisted addresses
*/
function getWhitelistUserAdress() external view returns(address[] memory){
return _whitelistedUserAddresses;
}
/**
* @dev Set sale parameters for users to buy new tokens
* @param _startTime Start time of the sale
* @param _endTime End time of the sale
* @param _minimumAmount Minimum accepted amount
* @param _maximumAmount Maximum accepted amount
*/
function setSaleParameter(
uint256 _startTime,
uint256 _endTime,
uint256 _minimumAmount,
uint256 _maximumAmount,
bool _whitelistFlag
) external onlyOwner returns(bool){
require(_startTime > 0 && _endTime > 0 && _minimumAmount > 0 && _maximumAmount > 0, "Invalid Values");
saleStartTime = _startTime;
saleEndTime = _endTime;
saleMinimumAmount = _minimumAmount;
saleMaximumAmount = _maximumAmount;
saleId = saleId.add(1);
whitelistFlag = _whitelistFlag;
return true;
}
/**
* @dev Get Sale Details Description
*/
function getSaleParameter(address _userAddress) external view returns(
uint256 _startTime,
uint256 _endTime,
uint256 _minimumAmount,
uint256 _maximumAmount,
uint256 _saleId,
bool _whitelistFlag
){
if(whitelistFlag == true && _whitelistedAddress[_userAddress] == true){
_maximumAmount = saleMaximumAmount.mul(_multiplier[_userAddress]);
}
else{
_maximumAmount = saleMaximumAmount;
}
_startTime = saleStartTime;
_endTime = saleEndTime;
_minimumAmount = saleMinimumAmount;
_saleId = saleId;
_whitelistFlag = whitelistFlag;
}
/**
* @dev Owner can set token price
* @param _tokenPrice price of 1 Token
*/
function setTokenPrice(
uint256 _tokenPrice
) external onlyOwner returns(bool){
tokenPrice = _tokenPrice;
return true;
}
/**
* @dev Get token price
*/
function getTokenPrice() external view returns(uint256){
return tokenPrice;
}
/* ----------------------------------------------------------------------------
* Functions for Additional Business Logic For Users
* ----------------------------------------------------------------------------
*/
modifier checkSaleValidations(address _userAddress, uint256 _value){
if(whitelistFlag == true){
require(_whitelistedAddress[_userAddress] == true, "Address not Whitelisted" );
require(_value <= saleMaximumAmount.mul(_multiplier[_userAddress]), "Total amount should be less than maximum limit");
require(_thisSaleContribution[_userAddress][saleId].add(_value) <= saleMaximumAmount.mul(_multiplier[_userAddress]), "Total amount should be less than maximum limit");
}
else{
require(_thisSaleContribution[_userAddress][saleId].add(_value) <= saleMaximumAmount, "Total amount should be less than maximum limit");
}
require(saleStartTime < block.timestamp , "Sale not started");
require(saleEndTime > block.timestamp, "Sale Ended");
require(_contributionBNB[_userAddress].add(_value) >= saleMinimumAmount, "Total amount should be more than minimum limit");
require(_value <= IDOAvailable, "Hard Cap Reached");
_;
}
//Check the expected amount per bnb
function checkTokensExpected(uint256 _value) view external returns(uint256){
return _value.mul(tokenPrice).div(decimalBalancer);
}
/*
* @dev Get Purchaseable amount
*/
function getPurchaseableTokens() external view returns(uint256){
return hardCap;
}
/*
* @dev Buy New tokens from the sale
*/
function buyTokens() payable external returns(bool){
return true;
}
/*
* @dev Internal function to achieve
*/
function _trasferInLockingState(
address[] userAddress,
uint256[] amountTransfer,
uint256[] bnb
) external onlyOwner returns(bool){
uint256 count = userAddress.length;
require(count < 201, "Array Overflow"); //Max 200 enteries at a time
for (uint256 i = 0; i < count; i++){
uint256 _bnb = bnb[i];
address _userAddress = userAddress[i];
uint256 _amountTransfer = amountTransfer[i];
_recordSale[_userAddress] = _amountTransfer;
_finalSoldAmount[_userAddress] = _amountTransfer;
_contributionBNB[_userAddress] = _bnb;
_thisSaleContribution[_userAddress][saleId] = _thisSaleContribution[_userAddress][saleId].add(_bnb);
IDOAvailable = IDOAvailable.sub(_amountTransfer);
}
return true;
}
/*
* @dev Owner can set hard cap for IDO
*/
function setIDOavailable(uint256 _IDOHardCap) external onlyOwner returns(bool){
require(_IDOHardCap <= balanceOf(address(this)) && _IDOHardCap > 0, "Value should not be more than IDO balance and greater than 0" );
hardCap = _IDOHardCap;
IDOAvailable = _IDOHardCap;
return true;
}
/*
* @dev Claim Purchased token by lock number
*/
function claimPurchasedTokens(uint256 _lockNumber) external validateClaim(msg.sender,_lockNumber) returns (bool){
uint256 calculation = (_finalSoldAmount[msg.sender]).div(2);
iMainToken.transfer(msg.sender,calculation);
_recordSale[msg.sender] = _recordSale[msg.sender].sub(calculation);
reEntrance[msg.sender][_lockNumber] = true;
_claimedByUser[msg.sender][_lockNumber] = calculation;
}
//validate claim tokens
modifier validateClaim(address _userAddress, uint256 _lockNumber)
{
require(_recordSale[_userAddress] > 0, "Not sufficient purchase Balance");
require(_lockNumber == 1 || _lockNumber == 2, "Invalid Lock Number");
if(_lockNumber == 1){ //Users will be able to withdraw tokens only after 1.5 hours of end time
require(block.timestamp > saleEndTime + _claimTime1 && reEntrance[_userAddress][_lockNumber] != true, "Insufficient Unlocked Tokens");
}
if(_lockNumber == 2){ // 1 month
require(block.timestamp > saleEndTime + _claimTime1 + 2629743 && reEntrance[_userAddress][_lockNumber] != true , "Insufficient Unlocked Tokens");
}
_;
}
/*
* @dev Check if the user address is whitelisted or not
*/
function checkWhitelistedAddress(address _userAddress) view external returns(bool){
require(_userAddress != address(0), "addresses should not be 0");
return _whitelistedAddress[_userAddress];
}
/*
* @dev Check all locking addresses
*/
modifier checkLockedAddresses(address _lockedAddresses){
require(_addressLocked[_lockedAddresses] != true, "Locking Address");
_;
}
/*
* @dev Admin can withdraw the bnb
*/
function withdrawCurrency(uint256 _amount) external onlyOwner returns(bool){
msg.sender.transfer(_amount);
return true;
}
/*
* @dev Get user tokens by address
*/
function getUserTokensByAdd(address _userAddress) external view returns(uint256 _div1, uint256 _div2, uint256 _div3, uint256 _div4, uint256 _div5){
uint256 division = _finalSoldAmount[_userAddress].div(2);
_div1 = division;
_div2 = division;
_div3 = 0;
_div4 = 0;
_div5 = 0;
if(reEntrance[_userAddress][1] == true){
_div1 = 0;
}
if(reEntrance[_userAddress][2] == true){
_div2 = 0;
}
if(reEntrance[_userAddress][3] == true){
_div3 = 0;
}
if(reEntrance[_userAddress][4] == true){
_div4 = 0;
}
if(reEntrance[_userAddress][5] == true){
_div5 = 0;
}
return(_div1,_div2,_div3,_div4,_div5);
}
/*
* @dev Get contract BNb balance to display
*/
function checkContractBNBBalance() external view returns(uint256){
return address(this).balance;
}
//get sold status
function getSoldStatus() external view returns(uint256 _totalAvailable, uint256 _currentAvailable){
_totalAvailable = hardCap;
_currentAvailable = IDOAvailable;
}
function getAmountPurchased(address _userAddress) external view returns(uint256 _contribution, uint256 _allocation){
_contribution = _contributionBNB[_userAddress];
_allocation = _finalSoldAmount[_userAddress];
}
//check contract block.timestamp time
function checkContractTime() external view returns(uint256){
return block.timestamp;
}
function getClaimDates() view external returns(uint256 _d1, uint256 _d2, uint256 _d3, uint256 _d4, uint256 _d5){
_d1 = saleEndTime + _claimTime1;
_d2 = saleEndTime + _claimTime1 + 2629743;
_d3 = 0;
_d4 = 0;
_d5 = 0;
return(_d1, _d2, _d3, _d4,_d5);
}
/*
* @dev Get claimed tokens by user address
*/
function getClaimedTokensHistory(address _userAddress) view external returns(uint256 r1,uint256 r2, uint256 r3, uint256 r4, uint256 r5){
r1 = _claimedByUser[_userAddress][1];
r2 = _claimedByUser[_userAddress][2];
r3 = 0;
r4 = 0;
r5 = 0;
return(r1, r2, r3, r4, r5);
}
/*
* @dev Set bnb price to display per token
*/
function setViewPricePerToken(uint256 _price) external onlyOwner returns(bool){
pricePerToken = _price;
return true;
}
/*
* @dev Get BNB price per token to display
*/
function getViewPricePerToken() view external returns(uint256){
return pricePerToken;
}
function setclaimTime1(uint256 claimTime1) external onlyOwner returns(bool){
_claimTime1 = claimTime1;
return true;
}
function getclaimTime1() view external returns(uint256){
return _claimTime1;
}
function withdrawPeningTokens(uint256 _amount) external view onlyOwner returns(bool){
iMainToken.transfer(msg.sender, _amount);
return true;
}
} | @dev Admin can withdraw the bnb/ | function withdrawCurrency(uint256 _amount) external onlyOwner returns(bool){
msg.sender.transfer(_amount);
return true;
}
| 10,974,029 | [
1,
4446,
848,
598,
9446,
326,
324,
6423,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
7623,
12,
11890,
5034,
389,
8949,
13,
3903,
1338,
5541,
1135,
12,
6430,
15329,
203,
3639,
1234,
18,
15330,
18,
13866,
24899,
8949,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
// ----------------------------------------------------------------------------
// 'FujiDoge' token contract
//
// Deployed to : 0xb36Ff93dC13113985Eb1Bc4f882f17Fa0Ef3d8D8
// Symbol : FDOGE
// Name : FujiDoge
// Total supply: 1000000000000000
// Decimals : 18
//
//Micro low cap.
//
// (c) by Matic Dev. and Intern
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract FujiDoge is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function FujiDoge() public {
symbol = "FDOGE";
name = "FujiDoge";
decimals = 18;
_totalSupply = 1000000000000000000000000000000000000000;
balances[0xb36Ff93dC13113985Eb1Bc4f882f17Fa0Ef3d8D8] = _totalSupply;
Transfer(address(0), 0xb36Ff93dC13113985Eb1Bc4f882f17Fa0Ef3d8D8, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract FujiDoge is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function FujiDoge() public {
symbol = "FDOGE";
name = "FujiDoge";
decimals = 18;
_totalSupply = 1000000000000000000000000000000000000000;
balances[0xb36Ff93dC13113985Eb1Bc4f882f17Fa0Ef3d8D8] = _totalSupply;
Transfer(address(0), 0xb36Ff93dC13113985Eb1Bc4f882f17Fa0Ef3d8D8, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 13,888,406 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
478,
11501,
77,
40,
717,
73,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
445,
478,
11501,
77,
40,
717,
73,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
42,
3191,
7113,
14432,
203,
3639,
508,
273,
315,
42,
11501,
77,
40,
717,
73,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
2130,
12648,
12648,
12648,
12648,
11706,
31,
203,
3639,
324,
26488,
63,
20,
6114,
5718,
42,
74,
11180,
72,
39,
3437,
2499,
5520,
7140,
41,
70,
21,
38,
71,
24,
74,
5482,
22,
74,
4033,
29634,
20,
41,
74,
23,
72,
28,
40,
28,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
12279,
12,
2867,
12,
20,
3631,
374,
6114,
5718,
42,
74,
11180,
72,
39,
3437,
2499,
5520,
7140,
41,
70,
21,
38,
71,
24,
74,
5482,
22,
74,
4033,
29634,
20,
41,
74,
23,
72,
28,
40,
28,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
5381,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
225,
300,
324,
26488,
63,
2867,
12,
20,
13,
2
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./AllocationPool.sol";
import "./LinearPool.sol";
contract StakingPool is
Initializable,
OwnableUpgradeable,
LinearPool,
AllocationPool
{
/**
* @notice Initialize the contract, get called in the first time deploy
* @param _rewardToken the reward token for the allocation pool and the accepted token for the linear pool
* @param _rewardPerBlock the number of reward tokens that got unlocked each block
* @param _startBlock the number of block when farming start
*/
function __StakingPool_init(
IERC20 _rewardToken,
uint128 _rewardPerBlock,
uint64 _startBlock
) external initializer {
__Ownable_init();
__AllocationPool_init(_rewardToken, _rewardPerBlock, _startBlock);
__LinearPool_init(_rewardToken);
}
/**
* @notice Withdraw from allocation pool and deposit to linear pool
* @param _allocPoolId id of the allocation pool
* @param _linearPoolId id of the linear pool
* @param _amount amount to convert
* @param _harvestAllocReward whether the user want to claim the rewards from the allocation pool or not
*/
function fromAllocToLinear(
uint256 _allocPoolId,
uint256 _linearPoolId,
uint128 _amount,
bool _harvestAllocReward
)
external
allocValidatePoolById(_allocPoolId)
linearValidatePoolById(_linearPoolId)
{
address account = msg.sender;
AllocPoolInfo storage allocPool = allocPoolInfo[_allocPoolId];
require(
allocPool.lpToken == linearAcceptedToken,
"AllocStakingPool: invalid allocation pool"
);
_allocWithdraw(_allocPoolId, _amount, _harvestAllocReward);
emit AllocWithdraw(account, _allocPoolId, _amount);
_linearDeposit(_linearPoolId, _amount, account);
emit LinearDeposit(_linearPoolId, account, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_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);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract AllocationPool is Initializable, OwnableUpgradeable {
using SafeERC20 for IERC20;
using SafeCastUpgradeable for uint256;
uint64 private constant ACCUMULATED_MULTIPLIER = 1e12;
uint64 public constant ALLOC_MAXIMUM_DELAY_DURATION = 35 days; // maximum 35 days delay
// Info of each user.
struct AllocUserInfo {
uint128 amount; // How many LP tokens the user has provided.
uint128 rewardDebt; // Reward debt. See explanation below.
uint128 pendingReward; // Reward but not harvest
//
// pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct AllocPoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint128 lpSupply; // Total lp tokens deposited to this pool.
uint64 allocPoint; // How many allocation points assigned to this pool. Rewards to distribute per block.
uint64 lastRewardBlock; // Last block number that rewards distribution occurs.
uint128 accRewardPerShare; // Accumulated rewards per share, times 1e12. See below.
uint128 delayDuration; // The duration user need to wait when withdraw.
}
struct AllocPendingWithdrawal {
uint128 amount;
uint128 applicableAt;
}
// The reward token!
IERC20 public allocRewardToken;
// Total rewards for each block.
uint128 public allocRewardPerBlock;
// The reward distribution address
address public allocRewardDistributor;
// Allow emergency withdraw feature
bool public allocAllowEmergencyWithdraw;
// Info of each pool.
AllocPoolInfo[] public allocPoolInfo;
// A record status of LP pool.
mapping(IERC20 => bool) public allocIsAdded;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => AllocUserInfo)) public allocUserInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint64 public totalAllocPoint;
// The block number when rewards mining starts.
uint64 public allocStartBlockNumber;
// The block number when rewards mining ends.
uint64 public allocEndBlockNumber;
// Info of pending withdrawals.
mapping(uint256 => mapping(address => AllocPendingWithdrawal))
public allocPendingWithdrawals;
event AllocPoolCreated(
uint256 indexed pid,
address indexed token,
uint256 allocPoint
);
event AllocDeposit(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event AllocWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event AllocPendingWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event AllocEmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event AllocRewardsHarvested(
address indexed user,
uint256 indexed pid,
uint256 amount
);
/**
* @notice Initialize the contract, get called in the first time deploy
* @param _rewardToken the reward token address
* @param _rewardPerBlock the number of reward tokens that got unlocked each block
* @param _startBlock the block number when farming start
*/
function __AllocationPool_init(
IERC20 _rewardToken,
uint128 _rewardPerBlock,
uint64 _startBlock
) public initializer {
__Ownable_init();
require(
address(_rewardToken) != address(0),
"AllocStakingPool: invalid reward token address"
);
allocRewardToken = _rewardToken;
allocRewardPerBlock = _rewardPerBlock;
allocStartBlockNumber = _startBlock;
totalAllocPoint = 0;
}
/**
* @notice Validate pool by pool ID
* @param _pid id of the pool
*/
modifier allocValidatePoolById(uint256 _pid) {
require(
_pid < allocPoolInfo.length,
"AllocStakingPool: pool are not exist"
);
_;
}
/**
* @notice Return total number of pools
*/
function allocPoolLength() external view returns (uint256) {
return allocPoolInfo.length;
}
/**
* @notice Add a new lp to the pool. Can only be called by the owner.
* @param _allocPoint the allocation point of the pool, used when calculating total reward the whole pool will receive each block
* @param _lpToken the token which this pool will accept
* @param _delayDuration the time user need to wait when withdraw
*/
function allocAddPool(
uint64 _allocPoint,
IERC20 _lpToken,
uint128 _delayDuration
) external onlyOwner {
require(
!allocIsAdded[_lpToken],
"AllocStakingPool: pool already is added"
);
require(
_delayDuration <= ALLOC_MAXIMUM_DELAY_DURATION,
"AllocStakingPool: delay duration is too long"
);
allocMassUpdatePools();
uint64 lastRewardBlock = block.number > allocStartBlockNumber
? block.number.toUint64()
: allocStartBlockNumber;
totalAllocPoint = totalAllocPoint + _allocPoint;
allocPoolInfo.push(
AllocPoolInfo({
lpToken: _lpToken,
lpSupply: 0,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accRewardPerShare: 0,
delayDuration: _delayDuration
})
);
allocIsAdded[_lpToken] = true;
emit AllocPoolCreated(
allocPoolInfo.length - 1,
address(_lpToken),
_allocPoint
);
}
/**
* @notice Update the given pool's reward allocation point. Can only be called by the owner.
* @param _pid id of the pool
* @param _allocPoint the allocation point of the pool, used when calculating total reward the whole pool will receive each block
* @param _delayDuration the time user need to wait when withdraw
*/
function allocSetPool(
uint256 _pid,
uint64 _allocPoint,
uint128 _delayDuration
) external onlyOwner allocValidatePoolById(_pid) {
require(
_delayDuration <= ALLOC_MAXIMUM_DELAY_DURATION,
"AllocStakingPool: delay duration is too long"
);
allocMassUpdatePools();
totalAllocPoint =
totalAllocPoint -
allocPoolInfo[_pid].allocPoint +
_allocPoint;
allocPoolInfo[_pid].allocPoint = _allocPoint;
allocPoolInfo[_pid].delayDuration = _delayDuration;
}
/**
* @notice Set the reward distributor. Can only be called by the owner.
* @param _allocRewardDistributor the reward distributor
*/
function allocSetRewardDistributor(address _allocRewardDistributor)
external
onlyOwner
{
require(
_allocRewardDistributor != address(0),
"AllocStakingPool: invalid reward distributor"
);
allocRewardDistributor = _allocRewardDistributor;
}
/**
* @notice Set the end block number. Can only be called by the owner.
*/
function allocSetEndBlock(uint64 _endBlockNumber) external onlyOwner {
require(
_endBlockNumber > block.number,
"AllocStakingPool: invalid reward distributor"
);
allocEndBlockNumber = _endBlockNumber;
}
/**
* @notice Return time multiplier over the given _from to _to block.
* @param _from the number of starting block
* @param _to the number of ending block
*/
function allocTimeMultiplier(uint128 _from, uint128 _to)
public
view
returns (uint128)
{
if (allocEndBlockNumber > 0 && _to > allocEndBlockNumber) {
return
allocEndBlockNumber > _from ? allocEndBlockNumber - _from : 0;
}
return _to - _from;
}
/**
* @notice Update number of reward per block
* @param _rewardPerBlock the number of reward tokens that got unlocked each block
*/
function allocSetRewardPerBlock(uint128 _rewardPerBlock)
external
onlyOwner
{
allocMassUpdatePools();
allocRewardPerBlock = _rewardPerBlock;
}
/**
* @notice View function to see pending rewards on frontend.
* @param _pid id of the pool
* @param _user the address of the user
*/
function allocPendingReward(uint256 _pid, address _user)
public
view
allocValidatePoolById(_pid)
returns (uint128)
{
AllocPoolInfo storage pool = allocPoolInfo[_pid];
AllocUserInfo storage user = allocUserInfo[_pid][_user];
uint128 accRewardPerShare = pool.accRewardPerShare;
uint128 lpSupply = pool.lpSupply;
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint128 multiplier = allocTimeMultiplier(
pool.lastRewardBlock,
block.number.toUint128()
);
uint128 poolReward = (multiplier *
allocRewardPerBlock *
pool.allocPoint) / totalAllocPoint;
accRewardPerShare =
accRewardPerShare +
((poolReward * ACCUMULATED_MULTIPLIER) / lpSupply);
}
return
user.pendingReward +
(((user.amount * accRewardPerShare) / ACCUMULATED_MULTIPLIER) -
user.rewardDebt);
}
/**
* @notice Update reward vairables for all pools. Be careful of gas spending!
*/
function allocMassUpdatePools() public {
uint256 length = allocPoolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
allocUpdatePool(pid);
}
}
/**
* @notice Update reward variables of the given pool to be up-to-date.
* @param _pid id of the pool
*/
function allocUpdatePool(uint256 _pid) public allocValidatePoolById(_pid) {
AllocPoolInfo storage pool = allocPoolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpSupply;
if (lpSupply == 0) {
pool.lastRewardBlock = block.number.toUint64();
return;
}
uint256 multiplier = allocTimeMultiplier(
pool.lastRewardBlock,
block.number.toUint128()
);
uint256 poolReward = (multiplier *
allocRewardPerBlock *
pool.allocPoint) / totalAllocPoint;
pool.accRewardPerShare = (pool.accRewardPerShare +
((poolReward * ACCUMULATED_MULTIPLIER) / lpSupply)).toUint128();
pool.lastRewardBlock = block.number.toUint64();
}
/**
* @notice Deposit LP tokens to the farm for reward allocation.
* @param _pid id of the pool
* @param _amount amount to deposit
*/
function allocDeposit(uint256 _pid, uint128 _amount)
external
allocValidatePoolById(_pid)
{
AllocPoolInfo storage pool = allocPoolInfo[_pid];
AllocUserInfo storage user = allocUserInfo[_pid][msg.sender];
allocUpdatePool(_pid);
uint128 pending = ((user.amount * pool.accRewardPerShare) /
ACCUMULATED_MULTIPLIER) - user.rewardDebt;
user.pendingReward = user.pendingReward + pending;
user.amount = user.amount + _amount;
user.rewardDebt =
(user.amount * pool.accRewardPerShare) /
ACCUMULATED_MULTIPLIER;
pool.lpSupply = pool.lpSupply + _amount;
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
emit AllocDeposit(msg.sender, _pid, _amount);
}
/**
* @notice Withdraw LP tokens from Pool.
* @param _pid id of the pool
* @param _amount amount to withdraw
* @param _harvestReward whether the user want to claim the rewards or not
*/
function allocWithdraw(
uint256 _pid,
uint128 _amount,
bool _harvestReward
) external allocValidatePoolById(_pid) {
_allocWithdraw(_pid, _amount, _harvestReward);
AllocPoolInfo storage pool = allocPoolInfo[_pid];
if (pool.delayDuration == 0) {
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit AllocWithdraw(msg.sender, _pid, _amount);
return;
}
AllocPendingWithdrawal
storage pendingWithdraw = allocPendingWithdrawals[_pid][msg.sender];
pendingWithdraw.amount = pendingWithdraw.amount + _amount;
pendingWithdraw.applicableAt =
block.timestamp.toUint128() +
pool.delayDuration;
}
/**
* @notice Claim pending withdrawal
* @param _pid id of the pool
*/
function allocClaimPendingWithdraw(uint256 _pid)
external
allocValidatePoolById(_pid)
{
AllocPoolInfo storage pool = allocPoolInfo[_pid];
AllocPendingWithdrawal
storage pendingWithdraw = allocPendingWithdrawals[_pid][msg.sender];
uint256 amount = pendingWithdraw.amount;
require(amount > 0, "AllocStakingPool: nothing is currently pending");
require(
pendingWithdraw.applicableAt <= block.timestamp,
"AllocStakingPool: not released yet"
);
delete allocPendingWithdrawals[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit AllocWithdraw(msg.sender, _pid, amount);
}
/**
* @notice Update allowance for emergency withdraw
* @param _shouldAllow should allow emergency withdraw or not
*/
function allocSetAllowEmergencyWithdraw(bool _shouldAllow)
external
onlyOwner
{
allocAllowEmergencyWithdraw = _shouldAllow;
}
/**
* @notice Withdraw without caring about rewards. EMERGENCY ONLY.
* @param _pid id of the pool
*/
function allocEmergencyWithdraw(uint256 _pid)
external
allocValidatePoolById(_pid)
{
require(
allocAllowEmergencyWithdraw,
"AllocStakingPool: emergency withdrawal is not allowed yet"
);
AllocPoolInfo storage pool = allocPoolInfo[_pid];
AllocUserInfo storage user = allocUserInfo[_pid][msg.sender];
uint128 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpSupply = pool.lpSupply - amount;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit AllocEmergencyWithdraw(msg.sender, _pid, amount);
}
/**
* @notice Compound rewards to reward pool
* @param _rewardPoolId id of the reward pool
*/
function allocCompoundReward(uint256 _rewardPoolId)
external
allocValidatePoolById(_rewardPoolId)
{
AllocPoolInfo storage pool = allocPoolInfo[_rewardPoolId];
AllocUserInfo storage user = allocUserInfo[_rewardPoolId][msg.sender];
require(
pool.lpToken == allocRewardToken,
"AllocStakingPool: invalid reward pool"
);
uint128 totalPending = allocPendingReward(_rewardPoolId, msg.sender);
require(totalPending > 0, "AllocStakingPool: invalid reward amount");
user.pendingReward = 0;
allocSafeRewardTransfer(address(this), totalPending);
emit AllocRewardsHarvested(msg.sender, _rewardPoolId, totalPending);
allocUpdatePool(_rewardPoolId);
user.amount = user.amount + totalPending;
user.rewardDebt =
(user.amount * pool.accRewardPerShare) /
ACCUMULATED_MULTIPLIER;
pool.lpSupply = pool.lpSupply + totalPending;
emit AllocDeposit(msg.sender, _rewardPoolId, totalPending);
}
/**
* @notice Harvest proceeds msg.sender
* @param _pid id of the pool
*/
function allocClaimReward(uint256 _pid)
public
allocValidatePoolById(_pid)
returns (uint128)
{
allocUpdatePool(_pid);
AllocPoolInfo storage pool = allocPoolInfo[_pid];
AllocUserInfo storage user = allocUserInfo[_pid][msg.sender];
uint128 totalPending = allocPendingReward(_pid, msg.sender);
user.pendingReward = 0;
user.rewardDebt =
(user.amount * pool.accRewardPerShare) /
(ACCUMULATED_MULTIPLIER);
if (totalPending > 0) {
allocSafeRewardTransfer(msg.sender, totalPending);
}
emit AllocRewardsHarvested(msg.sender, _pid, totalPending);
return totalPending;
}
/**
* @notice Harvest proceeds of all pools for msg.sender
* @param _pids ids of the pools
*/
function allocClaimAll(uint256[] memory _pids) external {
uint256 length = _pids.length;
for (uint256 pid = 0; pid < length; ++pid) {
allocClaimReward(pid);
}
}
/**
* @notice Withdraw LP tokens from Pool.
* @param _pid id of the pool
* @param _amount amount to withdraw
* @param _harvestReward whether the user want to claim the rewards or not
*/
function _allocWithdraw(
uint256 _pid,
uint128 _amount,
bool _harvestReward
) internal {
AllocPoolInfo storage pool = allocPoolInfo[_pid];
AllocUserInfo storage user = allocUserInfo[_pid][msg.sender];
require(user.amount >= _amount, "AllocStakingPool: invalid amount");
if (_harvestReward || user.amount == _amount) {
allocClaimReward(_pid);
} else {
allocUpdatePool(_pid);
uint128 pending = ((user.amount * pool.accRewardPerShare) /
ACCUMULATED_MULTIPLIER) - user.rewardDebt;
if (pending > 0) {
user.pendingReward = user.pendingReward + pending;
}
}
user.amount -= _amount;
user.rewardDebt =
(user.amount * pool.accRewardPerShare) /
ACCUMULATED_MULTIPLIER;
pool.lpSupply = pool.lpSupply - _amount;
}
/**
* @notice Safe reward transfer function, just in case if reward distributor dose not have enough reward tokens.
* @param _to address of the receiver
* @param _amount amount of the reward token
*/
function allocSafeRewardTransfer(address _to, uint128 _amount) internal {
uint256 bal = allocRewardToken.balanceOf(allocRewardDistributor);
require(_amount <= bal, "AllocStakingPool: not enough reward token");
allocRewardToken.safeTransferFrom(allocRewardDistributor, _to, _amount);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
contract LinearPool is
Initializable,
OwnableUpgradeable,
ReentrancyGuardUpgradeable
{
using SafeERC20 for IERC20;
using SafeCastUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
uint32 private constant ONE_YEAR_IN_SECONDS = 365 days;
uint64 public constant LINEAR_MAXIMUM_DELAY_DURATION = 35 days; // maximum 35 days delay
// The accepted token
IERC20 public linearAcceptedToken;
// The reward distribution address
address public linearRewardDistributor;
// Info of each pool
LinearPoolInfo[] public linearPoolInfo;
// Info of each user that stakes in pools
mapping(uint256 => mapping(address => LinearStakingData))
public linearStakingData;
// Info of pending withdrawals.
mapping(uint256 => mapping(address => LinearPendingWithdrawal))
public linearPendingWithdrawals;
// The flexible lock duration. Users who stake in the flexible pool will be affected by this
uint128 public linearFlexLockDuration;
// Allow emergency withdraw feature
bool public linearAllowEmergencyWithdraw;
event LinearPoolCreated(uint256 indexed poolId, uint256 APR);
event LinearDeposit(
uint256 indexed poolId,
address indexed account,
uint256 amount
);
event LinearWithdraw(
uint256 indexed poolId,
address indexed account,
uint256 amount
);
event LinearRewardsHarvested(
uint256 indexed poolId,
address indexed account,
uint256 reward
);
event LinearPendingWithdraw(
uint256 indexed poolId,
address indexed account,
uint256 amount
);
event LinearEmergencyWithdraw(
uint256 indexed poolId,
address indexed account,
uint256 amount
);
struct LinearPoolInfo {
uint128 cap;
uint128 totalStaked;
uint128 minInvestment;
uint128 maxInvestment;
uint64 APR;
uint128 lockDuration;
uint128 delayDuration;
uint128 startJoinTime;
uint128 endJoinTime;
}
struct LinearStakingData {
uint128 balance;
uint128 joinTime;
uint128 updatedTime;
uint128 reward;
}
struct LinearPendingWithdrawal {
uint128 amount;
uint128 applicableAt;
}
/**
* @notice Initialize the contract, get called in the first time deploy
* @param _acceptedToken the token that the pools will use as staking and reward token
*/
function __LinearPool_init(IERC20 _acceptedToken) public initializer {
__Ownable_init();
linearAcceptedToken = _acceptedToken;
}
/**
* @notice Validate pool by pool ID
* @param _poolId id of the pool
*/
modifier linearValidatePoolById(uint256 _poolId) {
require(
_poolId < linearPoolInfo.length,
"LinearStakingPool: Pool are not exist"
);
_;
}
/**
* @notice Return total number of pools
*/
function linearPoolLength() external view returns (uint256) {
return linearPoolInfo.length;
}
/**
* @notice Return total tokens staked in a pool
* @param _poolId id of the pool
*/
function linearTotalStaked(uint256 _poolId)
external
view
linearValidatePoolById(_poolId)
returns (uint256)
{
return linearPoolInfo[_poolId].totalStaked;
}
/**
* @notice Add a new pool with different APR and conditions. Can only be called by the owner.
* @param _cap the maximum number of staking tokens the pool will receive. If this limit is reached, users can not deposit into this pool.
* @param _minInvestment the minimum investment amount users need to use in order to join the pool.
* @param _maxInvestment the maximum investment amount users can deposit to join the pool.
* @param _APR the APR rate of the pool.
* @param _lockDuration the duration users need to wait before being able to withdraw and claim the rewards.
* @param _delayDuration the duration users need to wait to receive the principal amount, after unstaking from the pool.
* @param _startJoinTime the time when users can start to join the pool
* @param _endJoinTime the time when users can no longer join the pool
*/
function linearAddPool(
uint128 _cap,
uint128 _minInvestment,
uint128 _maxInvestment,
uint64 _APR,
uint128 _lockDuration,
uint128 _delayDuration,
uint128 _startJoinTime,
uint128 _endJoinTime
) external onlyOwner {
require(
_endJoinTime >= block.timestamp && _endJoinTime > _startJoinTime,
"LinearStakingPool: invalid end join time"
);
require(
_delayDuration <= LINEAR_MAXIMUM_DELAY_DURATION,
"LinearStakingPool: delay duration is too long"
);
linearPoolInfo.push(
LinearPoolInfo({
cap: _cap,
totalStaked: 0,
minInvestment: _minInvestment,
maxInvestment: _maxInvestment,
APR: _APR,
lockDuration: _lockDuration,
delayDuration: _delayDuration,
startJoinTime: _startJoinTime,
endJoinTime: _endJoinTime
})
);
emit LinearPoolCreated(linearPoolInfo.length - 1, _APR);
}
/**
* @notice Update the given pool's info. Can only be called by the owner.
* @param _poolId id of the pool
* @param _cap the maximum number of staking tokens the pool will receive. If this limit is reached, users can not deposit into this pool.
* @param _minInvestment minimum investment users need to use in order to join the pool.
* @param _maxInvestment the maximum investment amount users can deposit to join the pool.
* @param _APR the APR rate of the pool.
* @param _endJoinTime the time when users can no longer join the pool
*/
function linearSetPool(
uint128 _poolId,
uint128 _cap,
uint128 _minInvestment,
uint128 _maxInvestment,
uint64 _APR,
uint128 _endJoinTime
) external onlyOwner linearValidatePoolById(_poolId) {
LinearPoolInfo storage pool = linearPoolInfo[_poolId];
require(
_endJoinTime >= block.timestamp &&
_endJoinTime > pool.startJoinTime,
"LinearStakingPool: invalid end join time"
);
linearPoolInfo[_poolId].cap = _cap;
linearPoolInfo[_poolId].minInvestment = _minInvestment;
linearPoolInfo[_poolId].maxInvestment = _maxInvestment;
linearPoolInfo[_poolId].APR = _APR;
linearPoolInfo[_poolId].endJoinTime = _endJoinTime;
}
/**
* @notice Set the flexible lock time. This will affects the flexible pool. Can only be called by the owner.
* @param _flexLockDuration the minimum lock duration
*/
function linearSetFlexLockDuration(uint128 _flexLockDuration)
external
onlyOwner
{
require(
_flexLockDuration <= LINEAR_MAXIMUM_DELAY_DURATION,
"LinearStakingPool: flexible lock duration is too long"
);
linearFlexLockDuration = _flexLockDuration;
}
/**
* @notice Set the reward distributor. Can only be called by the owner.
* @param _linearRewardDistributor the reward distributor
*/
function linearSetRewardDistributor(address _linearRewardDistributor)
external
onlyOwner
{
require(
_linearRewardDistributor != address(0),
"LinearStakingPool: invalid reward distributor"
);
linearRewardDistributor = _linearRewardDistributor;
}
/**
* @notice Deposit token to earn rewards
* @param _poolId id of the pool
* @param _amount amount of token to deposit
*/
function linearDeposit(uint256 _poolId, uint128 _amount)
external
nonReentrant
linearValidatePoolById(_poolId)
{
address account = msg.sender;
_linearDeposit(_poolId, _amount, account);
linearAcceptedToken.safeTransferFrom(account, address(this), _amount);
emit LinearDeposit(_poolId, account, _amount);
}
/**
* @notice Withdraw token from a pool
* @param _poolId id of the pool
* @param _amount amount to withdraw
*/
function linearWithdraw(uint256 _poolId, uint128 _amount)
external
nonReentrant
linearValidatePoolById(_poolId)
{
address account = msg.sender;
LinearPoolInfo storage pool = linearPoolInfo[_poolId];
LinearStakingData storage stakingData = linearStakingData[_poolId][
account
];
uint128 lockDuration = pool.lockDuration > 0
? pool.lockDuration
: linearFlexLockDuration;
require(
block.timestamp >= stakingData.joinTime + lockDuration,
"LinearStakingPool: still locked"
);
require(
stakingData.balance >= _amount,
"LinearStakingPool: invalid withdraw amount"
);
_linearHarvest(_poolId, account);
if (stakingData.reward > 0) {
require(
linearRewardDistributor != address(0),
"LinearStakingPool: invalid reward distributor"
);
uint128 reward = stakingData.reward;
stakingData.reward = 0;
linearAcceptedToken.safeTransferFrom(
linearRewardDistributor,
account,
reward
);
emit LinearRewardsHarvested(_poolId, account, reward);
}
stakingData.balance -= _amount;
if (pool.delayDuration == 0) {
linearAcceptedToken.safeTransfer(account, _amount);
emit LinearWithdraw(_poolId, account, _amount);
return;
}
LinearPendingWithdrawal storage pending = linearPendingWithdrawals[
_poolId
][account];
pending.amount += _amount;
pending.applicableAt = block.timestamp.toUint128() + pool.delayDuration;
}
/**
* @notice Claim pending withdrawal
* @param _poolId id of the pool
*/
function linearClaimPendingWithdraw(uint256 _poolId)
external
nonReentrant
linearValidatePoolById(_poolId)
{
address account = msg.sender;
LinearPendingWithdrawal storage pending = linearPendingWithdrawals[
_poolId
][account];
uint128 amount = pending.amount;
require(amount > 0, "LinearStakingPool: nothing is currently pending");
require(
pending.applicableAt <= block.timestamp,
"LinearStakingPool: not released yet"
);
delete linearPendingWithdrawals[_poolId][account];
linearAcceptedToken.safeTransfer(account, amount);
emit LinearWithdraw(_poolId, account, amount);
}
/**
* @notice Claim reward token from a pool
* @param _poolId id of the pool
*/
function linearClaimReward(uint256 _poolId)
external
nonReentrant
linearValidatePoolById(_poolId)
{
address account = msg.sender;
LinearStakingData storage stakingData = linearStakingData[_poolId][
account
];
_linearHarvest(_poolId, account);
if (stakingData.reward > 0) {
require(
linearRewardDistributor != address(0),
"LinearStakingPool: invalid reward distributor"
);
uint128 reward = stakingData.reward;
stakingData.reward = 0;
linearAcceptedToken.safeTransferFrom(
linearRewardDistributor,
account,
reward
);
emit LinearRewardsHarvested(_poolId, account, reward);
}
}
/**
* @notice Gets number of reward tokens of a user from a pool
* @param _poolId id of the pool
* @param _account address of a user
* @return reward earned reward of a user
*/
function linearPendingReward(uint256 _poolId, address _account)
public
view
linearValidatePoolById(_poolId)
returns (uint128 reward)
{
LinearPoolInfo storage pool = linearPoolInfo[_poolId];
LinearStakingData storage stakingData = linearStakingData[_poolId][
_account
];
uint128 startTime = stakingData.updatedTime > 0
? stakingData.updatedTime
: block.timestamp.toUint128();
uint128 endTime = block.timestamp.toUint128();
if (
pool.lockDuration > 0 &&
stakingData.joinTime + pool.lockDuration < block.timestamp
) {
endTime = stakingData.joinTime + pool.lockDuration;
}
uint128 stakedTimeInSeconds = endTime > startTime
? endTime - startTime
: 0;
uint128 pendingReward = ((stakingData.balance *
stakedTimeInSeconds *
pool.APR) / ONE_YEAR_IN_SECONDS) / 100;
reward = stakingData.reward + pendingReward;
}
/**
* @notice Gets number of deposited tokens in a pool
* @param _poolId id of the pool
* @param _account address of a user
* @return total token deposited in a pool by a user
*/
function linearBalanceOf(uint256 _poolId, address _account)
external
view
linearValidatePoolById(_poolId)
returns (uint128)
{
return linearStakingData[_poolId][_account].balance;
}
/**
* @notice Update allowance for emergency withdraw
* @param _shouldAllow should allow emergency withdraw or not
*/
function linearSetAllowEmergencyWithdraw(bool _shouldAllow)
external
onlyOwner
{
linearAllowEmergencyWithdraw = _shouldAllow;
}
/**
* @notice Withdraw without caring about rewards. EMERGENCY ONLY.
* @param _poolId id of the pool
*/
function linearEmergencyWithdraw(uint256 _poolId)
external
nonReentrant
linearValidatePoolById(_poolId)
{
require(
linearAllowEmergencyWithdraw,
"LinearStakingPool: emergency withdrawal is not allowed yet"
);
address account = msg.sender;
LinearStakingData storage stakingData = linearStakingData[_poolId][
account
];
require(
stakingData.balance > 0,
"LinearStakingPool: nothing to withdraw"
);
uint128 amount = stakingData.balance;
stakingData.balance = 0;
stakingData.reward = 0;
stakingData.updatedTime = block.timestamp.toUint128();
linearAcceptedToken.safeTransfer(account, amount);
emit LinearEmergencyWithdraw(_poolId, account, amount);
}
function _linearDeposit(
uint256 _poolId,
uint128 _amount,
address account
) internal {
LinearPoolInfo storage pool = linearPoolInfo[_poolId];
LinearStakingData storage stakingData = linearStakingData[_poolId][
account
];
require(
block.timestamp >= pool.startJoinTime,
"LinearStakingPool: pool is not started yet"
);
require(
block.timestamp <= pool.endJoinTime,
"LinearStakingPool: pool is already closed"
);
require(
stakingData.balance + _amount >= pool.minInvestment,
"LinearStakingPool: insufficient amount"
);
if (pool.maxInvestment > 0) {
require(
stakingData.balance + _amount <= pool.maxInvestment,
"LinearStakingPool: too large amount"
);
}
if (pool.cap > 0) {
require(
pool.totalStaked + _amount <= pool.cap,
"LinearStakingPool: pool is full"
);
}
_linearHarvest(_poolId, account);
stakingData.balance += _amount;
stakingData.joinTime = block.timestamp.toUint128();
pool.totalStaked += _amount;
}
function _linearHarvest(uint256 _poolId, address _account) private {
LinearStakingData storage stakingData = linearStakingData[_poolId][
_account
];
stakingData.reward = linearPendingReward(_poolId, _account);
stakingData.updatedTime = block.timestamp.toUint128();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCastUpgradeable {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
| * @notice Withdraw LP tokens from Pool. @param _pid id of the pool @param _amount amount to withdraw @param _harvestReward whether the user want to claim the rewards or not/ | function allocWithdraw(
uint256 _pid,
uint128 _amount,
bool _harvestReward
) external allocValidatePoolById(_pid) {
_allocWithdraw(_pid, _amount, _harvestReward);
AllocPoolInfo storage pool = allocPoolInfo[_pid];
if (pool.delayDuration == 0) {
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit AllocWithdraw(msg.sender, _pid, _amount);
return;
}
AllocPendingWithdrawal
storage pendingWithdraw = allocPendingWithdrawals[_pid][msg.sender];
pendingWithdraw.amount = pendingWithdraw.amount + _amount;
pendingWithdraw.applicableAt =
block.timestamp.toUint128() +
pool.delayDuration;
}
| 11,892,676 | [
1,
1190,
9446,
511,
52,
2430,
628,
8828,
18,
225,
389,
6610,
612,
434,
326,
2845,
225,
389,
8949,
3844,
358,
598,
9446,
225,
389,
30250,
26923,
17631,
1060,
2856,
326,
729,
2545,
358,
7516,
326,
283,
6397,
578,
486,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4767,
1190,
9446,
12,
203,
3639,
2254,
5034,
389,
6610,
16,
203,
3639,
2254,
10392,
389,
8949,
16,
203,
3639,
1426,
389,
30250,
26923,
17631,
1060,
203,
565,
262,
3903,
4767,
4270,
2864,
5132,
24899,
6610,
13,
288,
203,
3639,
389,
9853,
1190,
9446,
24899,
6610,
16,
389,
8949,
16,
389,
30250,
26923,
17631,
1060,
1769,
203,
203,
3639,
12830,
2864,
966,
2502,
2845,
273,
4767,
2864,
966,
63,
67,
6610,
15533,
203,
203,
3639,
309,
261,
6011,
18,
10790,
5326,
422,
374,
13,
288,
203,
5411,
2845,
18,
9953,
1345,
18,
4626,
5912,
12,
2867,
12,
3576,
18,
15330,
3631,
389,
8949,
1769,
203,
5411,
3626,
12830,
1190,
9446,
12,
3576,
18,
15330,
16,
389,
6610,
16,
389,
8949,
1769,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
12830,
8579,
1190,
9446,
287,
203,
5411,
2502,
4634,
1190,
9446,
273,
4767,
8579,
1190,
9446,
1031,
63,
67,
6610,
6362,
3576,
18,
15330,
15533,
203,
3639,
4634,
1190,
9446,
18,
8949,
273,
4634,
1190,
9446,
18,
8949,
397,
389,
8949,
31,
203,
3639,
4634,
1190,
9446,
18,
438,
10120,
861,
273,
203,
5411,
1203,
18,
5508,
18,
869,
5487,
10392,
1435,
397,
203,
5411,
2845,
18,
10790,
5326,
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
] |
./full_match/80001/0x93606Db8e1340eBa115633Cc8a031D379D7638C6/sources/contracts/dev/vendor/openzeppelin-solidity/v.4.8.0/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 {
function toUint248(uint256 value) internal pure returns (uint248) {
require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
return uint248(value);
}
function toUint240(uint256 value) internal pure returns (uint240) {
require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
return uint240(value);
}
function toUint232(uint256 value) internal pure returns (uint232) {
require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
return uint232(value);
}
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
function toUint216(uint256 value) internal pure returns (uint216) {
require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
return uint216(value);
}
function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
function toUint200(uint256 value) internal pure returns (uint200) {
require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
return uint200(value);
}
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
return uint192(value);
}
function toUint184(uint256 value) internal pure returns (uint184) {
require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
return uint184(value);
}
function toUint176(uint256 value) internal pure returns (uint176) {
require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
return uint176(value);
}
function toUint168(uint256 value) internal pure returns (uint168) {
require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
return uint168(value);
}
function toUint160(uint256 value) internal pure returns (uint160) {
require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
return uint160(value);
}
function toUint152(uint256 value) internal pure returns (uint152) {
require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
return uint152(value);
}
function toUint144(uint256 value) internal pure returns (uint144) {
require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
return uint144(value);
}
function toUint136(uint256 value) internal pure returns (uint136) {
require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
return uint136(value);
}
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
function toUint120(uint256 value) internal pure returns (uint120) {
require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
return uint120(value);
}
function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
function toUint104(uint256 value) internal pure returns (uint104) {
require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
return uint104(value);
}
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
function toUint80(uint256 value) internal pure returns (uint80) {
require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
return uint80(value);
}
function toUint72(uint256 value) internal pure returns (uint72) {
require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
return uint72(value);
}
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
function toUint56(uint256 value) internal pure returns (uint56) {
require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
return uint56(value);
}
function toUint48(uint256 value) internal pure returns (uint48) {
require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
return uint48(value);
}
function toUint40(uint256 value) internal pure returns (uint40) {
require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
return uint40(value);
}
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
function toUint24(uint256 value) internal pure returns (uint24) {
require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
return uint24(value);
}
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
}
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
}
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
}
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
}
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
}
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
}
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
}
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
}
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
}
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
}
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
}
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
}
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
}
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
}
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
}
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
}
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
}
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
}
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
}
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
}
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
}
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
}
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
}
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
}
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
}
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
}
function toInt256(uint256 value) internal pure returns (int256) {
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
| 5,640,037 | [
1,
24114,
1879,
348,
7953,
560,
1807,
2254,
5619,
19,
474,
5619,
27660,
12213,
598,
3096,
9391,
4271,
18,
10077,
4155,
310,
628,
2254,
5034,
19,
474,
5034,
316,
348,
7953,
560,
1552,
486,
15226,
603,
9391,
18,
1220,
848,
17997,
563,
316,
640,
30458,
15233,
8773,
578,
22398,
16,
3241,
21701,
11234,
6750,
716,
9391,
87,
1002,
1334,
18,
1375,
9890,
9735,
68,
3127,
3485,
333,
509,
89,
608,
635,
15226,
310,
326,
2492,
1347,
4123,
392,
1674,
9391,
87,
18,
11637,
333,
5313,
3560,
434,
326,
22893,
5295,
19229,
4174,
392,
7278,
667,
434,
22398,
16,
1427,
518,
1807,
14553,
358,
999,
518,
3712,
18,
4480,
506,
8224,
598,
288,
9890,
10477,
97,
471,
288,
12294,
9890,
10477,
97,
358,
2133,
518,
358,
10648,
1953,
16,
635,
14928,
777,
4233,
603,
1375,
11890,
5034,
68,
471,
1375,
474,
5034,
68,
471,
1508,
2588,
4155,
310,
18,
19,
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,
12083,
14060,
9735,
288,
203,
203,
225,
445,
358,
5487,
3247,
28,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
11890,
3247,
28,
13,
288,
203,
565,
2583,
12,
1132,
1648,
618,
12,
11890,
3247,
28,
2934,
1896,
16,
315,
9890,
9735,
30,
460,
3302,
1404,
4845,
316,
4248,
28,
4125,
8863,
203,
565,
327,
2254,
3247,
28,
12,
1132,
1769,
203,
225,
289,
203,
203,
225,
445,
358,
5487,
28784,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
11890,
28784,
13,
288,
203,
565,
2583,
12,
1132,
1648,
618,
12,
11890,
28784,
2934,
1896,
16,
315,
9890,
9735,
30,
460,
3302,
1404,
4845,
316,
27610,
4125,
8863,
203,
565,
327,
2254,
28784,
12,
1132,
1769,
203,
225,
289,
203,
203,
225,
445,
358,
5487,
22,
1578,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
11890,
22,
1578,
13,
288,
203,
565,
2583,
12,
1132,
1648,
618,
12,
11890,
22,
1578,
2934,
1896,
16,
315,
9890,
9735,
30,
460,
3302,
1404,
4845,
316,
576,
1578,
4125,
8863,
203,
565,
327,
2254,
22,
1578,
12,
1132,
1769,
203,
225,
289,
203,
203,
225,
445,
358,
5487,
23622,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
11890,
23622,
13,
288,
203,
565,
2583,
12,
1132,
1648,
618,
12,
11890,
23622,
2934,
1896,
16,
315,
9890,
9735,
30,
460,
3302,
1404,
4845,
316,
576,
3247,
4125,
8863,
203,
565,
327,
2254,
23622,
12,
1132,
1769,
203,
225,
289,
203,
203,
225,
445,
358,
5487,
22,
2313,
12,
11890,
5034,
460,
13,
2713,
16618,
2
] |
pragma solidity =0.5.16;
// SPDX-License-Identifier: MIT
interface IMaidCoin {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function INITIAL_SUPPLY() external pure returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 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 (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
}
// SPDX-License-Identifier: MIT
interface IUniswapV2ERC20 {
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;
}
// SPDX-License-Identifier: MIT
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// SPDX-License-Identifier: MIT
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using SafeMath for uint;
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor(string memory _name, string memory _symbol) public {
name = _name;
symbol = _symbol;
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// SPDX-License-Identifier: MIT
/**
* @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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _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;
}
}
// SPDX-License-Identifier: MIT
contract MaidCoin is IMaidCoin, Ownable, UniswapV2ERC20("MaidCoin", "$MAID") {
uint256 public constant INITIAL_SUPPLY = 60000 * 1e18;
constructor() public {
_mint(msg.sender, INITIAL_SUPPLY);
}
function mint(address to, uint256 amount) external onlyOwner {
_mint(to, amount);
}
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
} | SPDX-License-Identifier: MIT | interface IUniswapV2ERC20 {
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;
}
| 356,655 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
467,
984,
291,
91,
438,
58,
22,
654,
39,
3462,
288,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
460,
1769,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
460,
1769,
203,
203,
565,
445,
508,
1435,
3903,
16618,
1135,
261,
1080,
3778,
1769,
203,
565,
445,
3273,
1435,
3903,
16618,
1135,
261,
1080,
3778,
1769,
203,
565,
445,
15105,
1435,
3903,
16618,
1135,
261,
11890,
28,
1769,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
1769,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
1769,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
460,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
7412,
12,
2867,
358,
16,
2254,
460,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
460,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
27025,
67,
4550,
1435,
3903,
1476,
1135,
261,
3890,
1578,
1769,
203,
565,
445,
10950,
6068,
67,
2399,
15920,
1435,
3903,
16618,
1135,
261,
3890,
1578,
1769,
203,
565,
445,
1661,
764,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
1769,
203,
203,
565,
445,
21447,
12,
2867,
3410,
16,
1758,
17571,
264,
16,
2254,
460,
16,
2254,
14096,
16,
2254,
28,
331,
2
] |
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./SafeMath.sol";
import "./Events.sol";
import "./Ownable.sol";
import "./Upgradeable.sol";
import "./UpgradeableMaster.sol";
/// @title Upgrade Gatekeeper Contract
/// @author Matter Labs
contract UpgradeGatekeeper is UpgradeEvents, Ownable {
using SafeMath for uint256;
/// @notice Array of addresses of upgradeable contracts managed by the gatekeeper
Upgradeable[] public managedContracts;
/// @notice Upgrade mode statuses
enum UpgradeStatus {Idle, NoticePeriod, Preparation}
UpgradeStatus public upgradeStatus;
/// @notice Notice period finish timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint256 public noticePeriodFinishTimestamp;
/// @notice Addresses of the next versions of the contracts to be upgraded (if element of this array is equal to zero address it means that appropriate upgradeable contract wouldn't be upgraded this time)
/// @dev Will be empty in case of not active upgrade mode
address[] public nextTargets;
/// @notice Version id of contracts
uint256 public versionId;
/// @notice Contract which defines notice period duration and allows finish upgrade during preparation of it
UpgradeableMaster public mainContract;
/// @notice Contract constructor
/// @param _mainContract Contract which defines notice period duration and allows finish upgrade during preparation of it
/// @dev Calls Ownable contract constructor
constructor(UpgradeableMaster _mainContract) Ownable(msg.sender) {
mainContract = _mainContract;
versionId = 0;
}
/// @notice Adds a new upgradeable contract to the list of contracts managed by the gatekeeper
/// @param addr Address of upgradeable contract to add
function addUpgradeable(address addr) external {
requireMaster(msg.sender);
require(upgradeStatus == UpgradeStatus.Idle, "apc11"); /// apc11 - upgradeable contract can't be added during upgrade
managedContracts.push(Upgradeable(addr));
emit NewUpgradable(versionId, addr);
}
/// @notice Starts upgrade (activates notice period)
/// @param newTargets New managed contracts targets (if element of this array is equal to zero address it means that appropriate upgradeable contract wouldn't be upgraded this time)
function startUpgrade(address[] calldata newTargets) external {
requireMaster(msg.sender);
require(upgradeStatus == UpgradeStatus.Idle, "spu11"); // spu11 - unable to activate active upgrade mode
require(newTargets.length == managedContracts.length, "spu12"); // spu12 - number of new targets must be equal to the number of managed contracts
uint256 noticePeriod = mainContract.getNoticePeriod();
mainContract.upgradeNoticePeriodStarted();
upgradeStatus = UpgradeStatus.NoticePeriod;
noticePeriodFinishTimestamp = block.timestamp.add(noticePeriod);
nextTargets = newTargets;
emit NoticePeriodStart(versionId, newTargets, noticePeriod);
}
/// @notice Cancels upgrade
function cancelUpgrade() external {
requireMaster(msg.sender);
require(upgradeStatus != UpgradeStatus.Idle, "cpu11"); // cpu11 - unable to cancel not active upgrade mode
mainContract.upgradeCanceled();
upgradeStatus = UpgradeStatus.Idle;
noticePeriodFinishTimestamp = 0;
delete nextTargets;
emit UpgradeCancel(versionId);
}
/// @notice Activates preparation status
/// @return Bool flag indicating that preparation status has been successfully activated
function startPreparation() external returns (bool) {
requireMaster(msg.sender);
require(upgradeStatus == UpgradeStatus.NoticePeriod, "ugp11"); // ugp11 - unable to activate preparation status in case of not active notice period status
if (block.timestamp >= noticePeriodFinishTimestamp) {
upgradeStatus = UpgradeStatus.Preparation;
mainContract.upgradePreparationStarted();
emit PreparationStart(versionId);
return true;
} else {
return false;
}
}
/// @notice Finishes upgrade
/// @param targetsUpgradeParameters New targets upgrade parameters per each upgradeable contract
function finishUpgrade(bytes[] calldata targetsUpgradeParameters) external {
requireMaster(msg.sender);
require(upgradeStatus == UpgradeStatus.Preparation, "fpu11"); // fpu11 - unable to finish upgrade without preparation status active
require(targetsUpgradeParameters.length == managedContracts.length, "fpu12"); // fpu12 - number of new targets upgrade parameters must be equal to the number of managed contracts
require(mainContract.isReadyForUpgrade(), "fpu13"); // fpu13 - main contract is not ready for upgrade
mainContract.upgradeFinishes();
for (uint64 i = 0; i < managedContracts.length; i++) {
address newTarget = nextTargets[i];
if (newTarget != address(0)) {
managedContracts[i].upgradeTarget(newTarget, targetsUpgradeParameters[i]);
}
}
versionId++;
emit UpgradeComplete(versionId, nextTargets);
upgradeStatus = UpgradeStatus.Idle;
noticePeriodFinishTimestamp = 0;
delete nextTargets;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.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, "14");
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, "v");
}
/**
* @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, "15");
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, "x");
}
/**
* @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, "y");
}
/**
* @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.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Upgradeable.sol";
import "./Operations.sol";
/// @title zkSync events
/// @author Matter Labs
/// @author Stars Labs
interface Events {
/// @notice Event emitted when a block is committed
event BlockCommit(uint32 indexed blockNumber);
event BlockVerification(uint32 indexed blockNumber);
/// @notice Event emitted when user funds are withdrawn from the zkSync contract
event Withdrawal(uint16 indexed tokenId, uint128 amount);
event OnchainWithdrawal(
address indexed owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Event emitted when user send a transaction to deposit her funds
event OnchainDeposit(
address indexed sender,
uint16 indexed tokenId,
uint128 amount,
address indexed owner
);
event OnchainCreatePair(
uint16 indexed tokenAId,
uint16 indexed tokenBId,
uint16 indexed pairId,
address pair
);
/// @notice Event emitted when blocks are reverted
event BlocksRevert(uint32 totalBlocksVerified, uint32 totalBlocksCommitted);
/// @notice Exodus mode entered event
event ExodusMode();
/// @notice New priority request event. Emitted when a request is placed into mapping
event NewPriorityRequest(
address sender,
uint64 serialId,
Operations.OpType opType,
bytes pubData,
uint256 expirationBlock
);
/// @notice Deposit committed event.
event DepositCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Full exit committed event.
event FullExitCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
event CreatePairCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
uint16 tokenAId,
uint16 tokenBId,
uint16 indexed tokenPairId,
address pair
);
/// @notice Notice period changed
event NoticePeriodChange(uint256 newNoticePeriod);
}
/// @title Upgrade events
/// @author Matter Labs
interface UpgradeEvents {
/// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts
event NewUpgradable(uint256 indexed versionId, address indexed upgradeable);
/// @notice Upgrade mode enter event
event NoticePeriodStart(
uint256 indexed versionId,
address[] newTargets,
uint256 noticePeriod // notice period (in seconds)
);
/// @notice Upgrade mode cancel event
event UpgradeCancel(uint256 indexed versionId);
/// @notice Upgrade mode preparation status event
event PreparationStart(uint256 indexed versionId);
/// @notice Upgrade mode complete event
event UpgradeComplete(uint256 indexed versionId, address[] newTargets);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Ownable Contract
/// @author Matter Labs
// NO CHANGE
contract Ownable {
/// @dev Storage position of the masters address (keccak256('eip1967.proxy.admin') - 1)
bytes32 private constant masterPosition = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/// @notice Contract constructor
/// @dev Sets msg sender address as masters address
/// @param masterAddress Master address
constructor(address masterAddress) {
setMaster(masterAddress);
}
/// @notice Check if specified address is master
/// @param _address Address to check
function requireMaster(address _address) internal view {
require(_address == getMaster(), "1c"); // oro11 - only by master
}
/// @notice Returns contract masters address
/// @return master Master's address
function getMaster() public view returns (address master) {
bytes32 position = masterPosition;
assembly {
master := sload(position)
}
}
/// @dev Sets new masters address
/// @param _newMaster New master's address
function setMaster(address _newMaster) internal {
bytes32 position = masterPosition;
assembly {
sstore(position, _newMaster)
}
}
/// @notice Transfer mastership of the contract to new master
/// @param _newMaster New masters address
function transferMastership(address _newMaster) external {
requireMaster(msg.sender);
require(_newMaster != address(0), "1d"); // otp11 - new masters address can't be zero address
setMaster(_newMaster);
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Interface of the upgradeable contract
/// @author Matter Labs
interface Upgradeable {
/// @notice Upgrades target of upgradeable contract
/// @param newTarget New target
/// @param newTargetInitializationParameters New target initialization parameters
function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)
/// @author Matter Labs
interface UpgradeableMaster {
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint256);
/// @notice Notifies contract that notice period started
function upgradeNoticePeriodStarted() external;
/// @notice Notifies contract that upgrade preparation status is activated
function upgradePreparationStarted() external;
/// @notice Notifies contract that upgrade canceled
function upgradeCanceled() external;
/// @notice Notifies contract that upgrade finishes
function upgradeFinishes() external;
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool);
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Bytes.sol";
import "./Utils.sol";
/// @title zkSync operations tools
/// @author Matter Labs
/// @author Stars Labs
library Operations {
/// @notice zkSync circuit operation type
enum OpType {
Noop, //0
Deposit,
TransferToNew,
Withdraw,
Transfer,
FullExit, //5
ChangePubKey,
MiningMaintenance,
ClaimBonus,
CreatePair,
AddLiquidity,//10
RemoveLiquidity,
Swap
}
// Byte lengths
uint8 constant OP_TYPE_BYTES = 1;
uint8 constant TOKEN_BYTES = 2;
uint8 constant PUBKEY_BYTES = 32;
uint8 constant NONCE_BYTES = 4;
uint8 constant PUBKEY_HASH_BYTES = 20;
uint8 constant ADDRESS_BYTES = 20;
/// @dev Packed fee bytes lengths
uint8 constant FEE_BYTES = 2;
/// @dev zkSync account id bytes lengths
uint8 constant ACCOUNT_ID_BYTES = 4;
uint8 constant AMOUNT_BYTES = 16;
/// @dev Signature (for example full exit signature) bytes length
uint8 constant SIGNATURE_BYTES = 64;
// Deposit pubdata
struct Deposit {
// uint8 opType
uint32 accountId;
uint16 tokenId;
uint128 amount;
address owner;
uint32 pairAccountId;
}
// NEW ADD ACCOUNT_ID_BYTES
uint256 public constant PACKED_DEPOSIT_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES + ACCOUNT_ID_BYTES;
/// Deserialize deposit pubdata
function readDepositPubdata(bytes memory _data) internal pure returns (Deposit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "N"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
// NEW ADD pairAccountId
function writeDepositPubdataForPriorityQueue(Deposit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
uint8(OpType.Deposit),
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
op.owner, // owner
bytes4(0) // pairAccountId
);
}
/// @notice Write deposit pubdata for priority queue check.
function checkDepositInPriorityQueue(Deposit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeDepositPubdataForPriorityQueue(op)) == hashedPubdata;
}
// FullExit pubdata
struct FullExit {
// uint8 opType
uint32 accountId;
address owner;
uint16 tokenId;
uint128 amount;
uint32 pairAccountId;
}
// NEW ADD ACCOUNT_ID_BYTES
uint256 public constant PACKED_FULL_EXIT_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ACCOUNT_ID_BYTES;
function readFullExitPubdata(bytes memory _data) internal pure returns (FullExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
// NEW ADD pairAccountId
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "O"); // reading invalid full exit pubdata size
}
function writeFullExitPubdataForPriorityQueue(FullExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
uint8(OpType.FullExit),
op.accountId, // accountId
op.owner, // owner
op.tokenId, // tokenId
uint128(0), // amount -- ignored
// NEW ADD pairAccountId
uint32(0) // pairAccountId -- ignored
);
}
function checkFullExitInPriorityQueue(FullExit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeFullExitPubdataForPriorityQueue(op)) == hashedPubdata;
}
// Withdraw pubdata
struct Withdraw {
//uint8 opType; -- present in pubdata, ignored at serialization
// NEW ADD
uint32 accountId;
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address owner;
// NEW ADD
uint32 pairAccountId;
}
function readWithdrawPubdata(bytes memory _data) internal pure returns (Withdraw memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
// CHANGE uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES;
uint256 offset = OP_TYPE_BYTES; // opType
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
offset += FEE_BYTES; // fee (ignored)
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
// NEW ADD
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
}
// ForcedExit pubdata
struct ForcedExit {
//uint8 opType; -- present in pubdata, ignored at serialization
//uint32 initiatorAccountId; -- present in pubdata, ignored at serialization
//uint32 targetAccountId; -- present in pubdata, ignored at serialization
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address target;
}
function readForcedExitPubdata(bytes memory _data) internal pure returns (ForcedExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES * 2; // opType + initiatorAccountId + targetAccountId (ignored)
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
offset += FEE_BYTES; // fee (ignored)
(offset, parsed.target) = Bytes.readAddress(_data, offset); // target
}
// ChangePubKey
enum ChangePubkeyType {ECRECOVER, CREATE2, OldECRECOVER}
struct ChangePubKey {
// uint8 opType; -- present in pubdata, ignored at serialization
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
//uint16 tokenId; -- present in pubdata, ignored at serialization
//uint16 fee; -- present in pubdata, ignored at serialization
}
function readChangePubKeyPubdata(bytes memory _data) internal pure returns (ChangePubKey memory parsed) {
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce
}
// CreatePair pubdata
// NEW ADD
struct CreatePair {
// uint8 opType; -- present in pubdata, ignored at serialization
uint32 accountId;
uint16 tokenA;
uint16 tokenB;
uint16 tokenPair;
address pair;
}
// NEW ADD
uint256 public constant PACKED_CREATE_PAIR_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES;
// NEW ADD
function readCreatePairPubdata(bytes memory _data) internal pure returns (CreatePair memory parsed)
{
uint256 offset = OP_TYPE_BYTES; // opType
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId
(offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId
(offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId
(offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId
require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size
}
// NEW ADD
function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
OpType.CreatePair,
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenA, // tokenAId
op.tokenB, // tokenBId
op.tokenPair, // pairId
op.pair // pair account
);
}
function checkCreatePairInPriorityQueue(CreatePair memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeCreatePairPubdata(op)) == hashedPubdata;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
// Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word)
// implements the following algorithm:
// f(bytes memory input, uint offset) -> X out
// where byte representation of out is N bytes from input at the given offset
// 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N]
// W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N
// 2) We load W from memory into out, last N bytes of W are placed into out
library Bytes {
function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 16);
}
// Copies 'len' lower bytes from 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'.
function toBytesFromUIntTruncated(uint256 self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "Q");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint256 data = self << ((32 - byteLength) * 8);
assembly {
mstore(
add(bts, 32), // BYTES_HEADER_SIZE
data
)
}
}
// Copies 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length '20'.
function toBytesFromAddress(address self) internal pure returns (bytes memory bts) {
bts = toBytesFromUIntTruncated(uint256(self), 20);
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) {
uint256 offset = _start + 20;
require(self.length >= offset, "R");
assembly {
addr := mload(add(self, offset))
}
}
// Reasoning about why this function works is similar to that of other similar functions, except NOTE below.
// NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) {
require(self.length >= (_start + 20), "S");
assembly {
r := mload(add(add(self, 0x20), _start))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x2)
function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) {
uint256 offset = _start + 0x2;
require(_bytes.length >= offset, "T");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x3)
function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) {
uint256 offset = _start + 0x3;
require(_bytes.length >= offset, "U");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x4)
function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) {
uint256 offset = _start + 0x4;
require(_bytes.length >= offset, "V");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x10)
function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) {
uint256 offset = _start + 0x10;
require(_bytes.length >= offset, "W");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x14)
function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) {
uint256 offset = _start + 0x14;
require(_bytes.length >= offset, "X");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "Y");
assembly {
r := mload(add(_bytes, offset))
}
}
// Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228
// Get slice from bytes arrays
// Returns the newly created 'bytes memory'
// NOTE: theoretically possible overflow of (_start + _length)
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_bytes.length >= (_start + _length), "Z"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
assembly {
let slice_curr := add(tempBytes, 0x20)
let slice_end := add(slice_curr, _length)
for {
let array_current := add(_bytes, add(_start, 0x20))
} lt(slice_curr, slice_end) {
slice_curr := add(slice_curr, 0x20)
array_current := add(array_current, 0x20)
} {
mstore(slice_curr, mload(array_current))
}
}
}
return tempBytes;
}
/// Reads byte stream
/// @return new_offset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(
bytes memory _data,
uint256 _offset,
uint256 _length
) internal pure returns (uint256 new_offset, bytes memory data) {
data = slice(_data, _offset, _length);
new_offset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bool r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint8 r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint16 r) {
new_offset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint32 r) {
new_offset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint128 r) {
new_offset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint160 r) {
new_offset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, address r) {
new_offset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bytes20 r) {
new_offset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bytes32 r) {
new_offset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
/// Trim bytes into single word
function trim(bytes memory _data, uint256 _new_length) internal pure returns (uint256 r) {
require(_new_length <= 0x20, "10"); // new_length is longer than word
require(_data.length >= _new_length, "11"); // data is to short
uint256 a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _new_length) * 8);
}
// Helper function for hex conversion.
function halfByteToHex(bytes1 _byte) internal pure returns (bytes1 _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return bytes1(uint8(0x66656463626139383736353433323130 >> (uint8(_byte) * 8)));
}
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) {
bytes memory outStringBytes = new bytes(_input.length * 2);
// code in `assembly` construction is equivalent of the next code:
// for (uint i = 0; i < _input.length; ++i) {
// outStringBytes[i*2] = halfByteToHex(_input[i] >> 4);
// outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f);
// }
assembly {
let input_curr := add(_input, 0x20)
let input_end := add(input_curr, mload(_input))
for {
let out_curr := add(outStringBytes, 0x20)
} lt(input_curr, input_end) {
input_curr := add(input_curr, 0x01)
out_curr := add(out_curr, 0x02)
} {
let curr_input_byte := shr(0xf8, mload(input_curr))
// here outStringByte from each half of input byte calculates by the next:
//
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
// outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8)))
mstore(
out_curr,
shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
mstore(
add(out_curr, 0x01),
shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
}
}
return outStringBytes;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./IERC20.sol";
import "./Bytes.sol";
library Utils {
/// @notice Returns lesser of two values
function minU32(uint32 a, uint32 b) internal pure returns (uint32) {
return a < b ? a : b;
}
/// @notice Returns lesser of two values
function minU64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
/// @notice Sends tokens
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transfer` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendERC20(
IERC20 _token,
address _to,
uint256 _amount
) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) =
address(_token).call(abi.encodeWithSignature("transfer(address,uint256)", _to, _amount));
// `transfer` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Transfers token from one address to another
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _from Address of sender
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function transferFromERC20(
IERC20 _token,
address _from,
address _to,
uint256 _amount
) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) =
address(_token).call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount));
// `transferFrom` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Recovers signer's address from ethereum signature for given message
/// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1)
/// @param _messageHash signed message hash.
/// @return address of the signer
function recoverAddressFromEthSignature(bytes memory _signature, bytes32 _messageHash)
internal
pure
returns (address)
{
require(_signature.length == 65, "P"); // incorrect signature length
bytes32 signR;
bytes32 signS;
uint8 signV;
assembly {
signR := mload(add(_signature, 32))
signS := mload(add(_signature, 64))
signV := byte(0, mload(add(_signature, 96)))
}
return ecrecover(_messageHash, signV, signR, signS);
}
/// @notice Returns new_hash = hash(old_hash + bytes)
function concatHash(bytes32 _hash, bytes memory _bytes) internal pure returns (bytes32) {
bytes32 result;
assembly {
let bytesLen := add(mload(_bytes), 32)
mstore(_bytes, _hash)
result := keccak256(_bytes, bytesLen)
mstore(_bytes, sub(bytesLen, 32))
}
return result;
}
function hashBytesToBytes20(bytes memory _bytes) internal pure returns (bytes20) {
return bytes20(uint160(uint256(keccak256(_bytes))));
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: UNLICENSED
/**
* @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 symbol() external pure returns (string memory);
/**
* @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);
} | @title Ownable Contract @author Matter Labs NO CHANGE | contract Ownable {
bytes32 private constant masterPosition = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
}
constructor(address masterAddress) {
setMaster(masterAddress);
}
function requireMaster(address _address) internal view {
}
function getMaster() public view returns (address master) {
bytes32 position = masterPosition;
assembly {
master := sload(position)
}
}
function getMaster() public view returns (address master) {
bytes32 position = masterPosition;
assembly {
master := sload(position)
}
}
function setMaster(address _newMaster) internal {
bytes32 position = masterPosition;
assembly {
sstore(position, _newMaster)
}
}
function setMaster(address _newMaster) internal {
bytes32 position = masterPosition;
assembly {
sstore(position, _newMaster)
}
}
function transferMastership(address _newMaster) external {
requireMaster(msg.sender);
setMaster(_newMaster);
}
}
| 5,826,658 | [
1,
5460,
429,
13456,
225,
490,
9293,
511,
5113,
3741,
26267,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
14223,
6914,
288,
203,
565,
1731,
1578,
3238,
5381,
4171,
2555,
273,
374,
6114,
8643,
2138,
6669,
5193,
69,
4313,
28,
70,
23,
31331,
8906,
3437,
70,
29,
74,
28,
69,
26,
24171,
73,
3247,
23,
73,
4449,
70,
26,
73,
28,
1340,
2499,
8285,
72,
26,
69,
27,
4033,
28,
3361,
70,
25,
72,
26,
23494,
31,
203,
203,
97,
203,
203,
565,
3885,
12,
2867,
4171,
1887,
13,
288,
203,
3639,
444,
7786,
12,
7525,
1887,
1769,
203,
565,
289,
203,
203,
565,
445,
2583,
7786,
12,
2867,
389,
2867,
13,
2713,
1476,
288,
203,
565,
289,
203,
203,
565,
445,
27607,
1435,
1071,
1476,
1135,
261,
2867,
4171,
13,
288,
203,
3639,
1731,
1578,
1754,
273,
4171,
2555,
31,
203,
3639,
19931,
288,
203,
5411,
4171,
519,
272,
945,
12,
3276,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
27607,
1435,
1071,
1476,
1135,
261,
2867,
4171,
13,
288,
203,
3639,
1731,
1578,
1754,
273,
4171,
2555,
31,
203,
3639,
19931,
288,
203,
5411,
4171,
519,
272,
945,
12,
3276,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
444,
7786,
12,
2867,
389,
2704,
7786,
13,
2713,
288,
203,
3639,
1731,
1578,
1754,
273,
4171,
2555,
31,
203,
3639,
19931,
288,
203,
5411,
272,
2233,
12,
3276,
16,
389,
2704,
7786,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
444,
7786,
12,
2867,
389,
2704,
7786,
13,
2713,
288,
203,
3639,
1731,
1578,
1754,
273,
4171,
2555,
31,
203,
3639,
19931,
2
] |
./full_match/44787/0x38CB7c0C83A6e5524711c88BCD695Ff3C9e37450/sources/contracts/Bonus.sol | require(_msgSender() == starNFT.ownerOf(_tokenId), "not your token"); require(_amount > 0, "no bonus"); bonusWithdrawn = bonusWithdrawn.add(_amount); tokenWithdraw[_tokenId] = tokenWithdraw[_tokenId].add(_amount); starToken.transfer(_msgSender(), _amount); | function bonusWithdraw(uint256 _tokenId) view public returns(uint256){
return _getBonus(_tokenId);
}
| 13,262,635 | [
1,
6528,
24899,
3576,
12021,
1435,
422,
10443,
50,
4464,
18,
8443,
951,
24899,
2316,
548,
3631,
315,
902,
3433,
1147,
8863,
2583,
24899,
8949,
405,
374,
16,
315,
2135,
324,
22889,
8863,
324,
22889,
1190,
9446,
82,
273,
324,
22889,
1190,
9446,
82,
18,
1289,
24899,
8949,
1769,
1147,
1190,
9446,
63,
67,
2316,
548,
65,
273,
1147,
1190,
9446,
63,
67,
2316,
548,
8009,
1289,
24899,
8949,
1769,
10443,
1345,
18,
13866,
24899,
3576,
12021,
9334,
389,
8949,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
324,
22889,
1190,
9446,
12,
11890,
5034,
389,
2316,
548,
13,
1476,
1071,
1135,
12,
11890,
5034,
15329,
203,
3639,
327,
389,
588,
38,
22889,
24899,
2316,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.5.0;
contract PiggyBank {
// State variables:
address payable owner; // contract owner's address;
uint limit; // piggybank's minimal limit to withdraw;
uint128 balance; // piggybank's deposit balance;
uint version = 1; // version of the PiggyBank.
// Modifier that allows public function to accept all external calls.
modifier alwaysAccept {
// Runtime function that allows contract to process inbound messages spending
// its own resources (it's necessary if contract should process all inbound messages,
// not only those that carry value with them).
tvm.accept();
_;
}
// Modifier that allows public function to be called only by message signed with owner's pubkey.
modifier checkPubkeyAndAccept {
require(msg.pubkey() == tvm.pubkey());
tvm.accept();
_;
}
// Modifier that allows public function to be called only from the owners address.
modifier checkOwnerAndAccept {
require(msg.sender == owner);
tvm.accept();
_;
}
// Modifier that allows public function to be called only when the limit is reached.
modifier checkBalance() {
require(balance >= limit);
_;
}
// Constructor saves the address of the contract owner in a state variable and
// initializes the limit and the balance.
constructor(address payable pb_owner, uint pb_limit) public alwaysAccept {
owner = pb_owner;
limit = pb_limit;
balance = 0;
}
// Function that can be called by anyone.
function deposit() public payable alwaysAccept {
balance += uint128(msg.value);
}
// Function to change the PiggyBank limit that can be called only by the owner
function setLimit(uint newLimit) public payable checkOwnerAndAccept {
limit = newLimit;
}
// Function that can be called only by the owner after reaching the limit.
function withdraw() public checkBalance checkOwnerAndAccept {
msg.sender.transfer(balance);
balance = 0;
}
// Function that changes the code of current contract.
function setCode(TvmCell newcode) public checkPubkeyAndAccept {
// Runtime function that creates an output action that would change this
// smart contract code to that given by cell newcode.
tvm.setcode(newcode);
// Runtime function that replaces current code of the contract with newcode.
tvm.setCurrentCode(newcode);
// Call function onCodeUpgrade of the 'new' code.
onCodeUpgrade();
}
// After code upgrade caused by calling setCode function we may need to do some actions.
// We can add them into this function with constant id.
function onCodeUpgrade() private {
version = 2;
setLimit(limit * 2);
}
// Function to obtain contract version.
function getVersion() public view alwaysAccept returns (uint) {
return version;
}
}
| Function to change the PiggyBank limit that can be called only by the owner | function setLimit(uint newLimit) public payable checkOwnerAndAccept {
limit = newLimit;
}
| 15,840,073 | [
1,
2083,
358,
2549,
326,
453,
360,
7797,
16040,
1800,
716,
848,
506,
2566,
1338,
635,
326,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
444,
3039,
12,
11890,
394,
3039,
13,
1071,
8843,
429,
866,
5541,
1876,
5933,
288,
203,
202,
202,
3595,
273,
394,
3039,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../HandlerBase.sol";
import "./IKyberNetworkProxy.sol";
contract HKyberNetwork is HandlerBase {
using SafeERC20 for IERC20;
// prettier-ignore
address public constant ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// prettier-ignore
address public constant KYBERNETWORK_PROXY = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755;
function getContractName() public pure override returns (string memory) {
return "HKyberNetwork";
}
function swapEtherToToken(
uint256 value,
address token,
uint256 minRate
) external payable returns (uint256 destAmount) {
IKyberNetworkProxy kyber = IKyberNetworkProxy(KYBERNETWORK_PROXY);
value = _getBalance(ETH_TOKEN_ADDRESS, value);
try
kyber.swapEtherToToken.value(value)(IERC20(token), minRate)
returns (uint256 amount) {
destAmount = amount;
} catch Error(string memory reason) {
_revertMsg("swapEtherToToken", reason);
} catch {
_revertMsg("swapEtherToToken");
}
// Update involved token
_updateToken(token);
}
function swapTokenToEther(
address token,
uint256 tokenQty,
uint256 minRate
) external payable returns (uint256 destAmount) {
IKyberNetworkProxy kyber = IKyberNetworkProxy(KYBERNETWORK_PROXY);
tokenQty = _getBalance(token, tokenQty);
IERC20(token).safeApprove(address(kyber), tokenQty);
try kyber.swapTokenToEther(IERC20(token), tokenQty, minRate) returns (
uint256 amount
) {
destAmount = amount;
} catch Error(string memory reason) {
_revertMsg("swapTokenToEther", reason);
} catch {
_revertMsg("swapTokenToEther");
}
IERC20(token).safeApprove(address(kyber), 0);
}
function swapTokenToToken(
address srcToken,
uint256 srcQty,
address destToken,
uint256 minRate
) external payable returns (uint256 destAmount) {
IKyberNetworkProxy kyber = IKyberNetworkProxy(KYBERNETWORK_PROXY);
srcQty = _getBalance(srcToken, srcQty);
IERC20(srcToken).safeApprove(address(kyber), srcQty);
try
kyber.swapTokenToToken(
IERC20(srcToken),
srcQty,
IERC20(destToken),
minRate
)
returns (uint256 amount) {
destAmount = amount;
} catch Error(string memory reason) {
_revertMsg("swapTokenToToken", reason);
} catch {
_revertMsg("swapTokenToToken");
}
IERC20(srcToken).safeApprove(address(kyber), 0);
// Update involved token
_updateToken(destToken);
}
}
| prettier-ignore prettier-ignore | contract HKyberNetwork is HandlerBase {
using SafeERC20 for IERC20;
address public constant ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBERNETWORK_PROXY = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755;
function getContractName() public pure override returns (string memory) {
return "HKyberNetwork";
}
function swapEtherToToken(
uint256 value,
address token,
uint256 minRate
) external payable returns (uint256 destAmount) {
IKyberNetworkProxy kyber = IKyberNetworkProxy(KYBERNETWORK_PROXY);
value = _getBalance(ETH_TOKEN_ADDRESS, value);
try
kyber.swapEtherToToken.value(value)(IERC20(token), minRate)
returns (uint256 amount) {
destAmount = amount;
_revertMsg("swapEtherToToken", reason);
_revertMsg("swapEtherToToken");
}
}
function swapEtherToToken(
uint256 value,
address token,
uint256 minRate
) external payable returns (uint256 destAmount) {
IKyberNetworkProxy kyber = IKyberNetworkProxy(KYBERNETWORK_PROXY);
value = _getBalance(ETH_TOKEN_ADDRESS, value);
try
kyber.swapEtherToToken.value(value)(IERC20(token), minRate)
returns (uint256 amount) {
destAmount = amount;
_revertMsg("swapEtherToToken", reason);
_revertMsg("swapEtherToToken");
}
}
} catch Error(string memory reason) {
} catch {
_updateToken(token);
function swapTokenToEther(
address token,
uint256 tokenQty,
uint256 minRate
) external payable returns (uint256 destAmount) {
IKyberNetworkProxy kyber = IKyberNetworkProxy(KYBERNETWORK_PROXY);
tokenQty = _getBalance(token, tokenQty);
IERC20(token).safeApprove(address(kyber), tokenQty);
try kyber.swapTokenToEther(IERC20(token), tokenQty, minRate) returns (
uint256 amount
) {
destAmount = amount;
_revertMsg("swapTokenToEther", reason);
_revertMsg("swapTokenToEther");
}
IERC20(token).safeApprove(address(kyber), 0);
}
function swapTokenToEther(
address token,
uint256 tokenQty,
uint256 minRate
) external payable returns (uint256 destAmount) {
IKyberNetworkProxy kyber = IKyberNetworkProxy(KYBERNETWORK_PROXY);
tokenQty = _getBalance(token, tokenQty);
IERC20(token).safeApprove(address(kyber), tokenQty);
try kyber.swapTokenToEther(IERC20(token), tokenQty, minRate) returns (
uint256 amount
) {
destAmount = amount;
_revertMsg("swapTokenToEther", reason);
_revertMsg("swapTokenToEther");
}
IERC20(token).safeApprove(address(kyber), 0);
}
} catch Error(string memory reason) {
} catch {
function swapTokenToToken(
address srcToken,
uint256 srcQty,
address destToken,
uint256 minRate
) external payable returns (uint256 destAmount) {
IKyberNetworkProxy kyber = IKyberNetworkProxy(KYBERNETWORK_PROXY);
srcQty = _getBalance(srcToken, srcQty);
IERC20(srcToken).safeApprove(address(kyber), srcQty);
try
kyber.swapTokenToToken(
IERC20(srcToken),
srcQty,
IERC20(destToken),
minRate
)
returns (uint256 amount) {
destAmount = amount;
_revertMsg("swapTokenToToken", reason);
_revertMsg("swapTokenToToken");
}
IERC20(srcToken).safeApprove(address(kyber), 0);
}
function swapTokenToToken(
address srcToken,
uint256 srcQty,
address destToken,
uint256 minRate
) external payable returns (uint256 destAmount) {
IKyberNetworkProxy kyber = IKyberNetworkProxy(KYBERNETWORK_PROXY);
srcQty = _getBalance(srcToken, srcQty);
IERC20(srcToken).safeApprove(address(kyber), srcQty);
try
kyber.swapTokenToToken(
IERC20(srcToken),
srcQty,
IERC20(destToken),
minRate
)
returns (uint256 amount) {
destAmount = amount;
_revertMsg("swapTokenToToken", reason);
_revertMsg("swapTokenToToken");
}
IERC20(srcToken).safeApprove(address(kyber), 0);
}
} catch Error(string memory reason) {
} catch {
_updateToken(destToken);
}
| 12,785,398 | [
1,
1484,
748,
2453,
17,
6185,
675,
748,
2453,
17,
6185,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
670,
47,
93,
744,
3906,
353,
4663,
2171,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
1758,
1071,
5381,
512,
2455,
67,
8412,
67,
15140,
273,
374,
17432,
1340,
1340,
41,
1340,
73,
41,
73,
41,
1340,
41,
73,
41,
73,
41,
1340,
9383,
41,
1340,
1340,
41,
1340,
1340,
1340,
73,
9383,
73,
41,
31,
203,
565,
1758,
1071,
5381,
1475,
61,
6271,
28047,
67,
16085,
273,
374,
92,
28,
2643,
41,
26,
42,
7228,
40,
25,
2313,
41,
952,
17295,
29,
9793,
74,
26,
5193,
25,
73,
23,
7228,
5292,
3672,
11035,
38,
21761,
31,
203,
203,
565,
445,
336,
8924,
461,
1435,
1071,
16618,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
315,
44,
47,
93,
744,
3906,
14432,
203,
565,
289,
203,
203,
565,
445,
7720,
41,
1136,
774,
1345,
12,
203,
3639,
2254,
5034,
460,
16,
203,
3639,
1758,
1147,
16,
203,
3639,
2254,
5034,
1131,
4727,
203,
565,
262,
3903,
8843,
429,
1135,
261,
11890,
5034,
1570,
6275,
13,
288,
203,
3639,
467,
47,
93,
744,
3906,
3886,
417,
93,
744,
273,
467,
47,
93,
744,
3906,
3886,
12,
47,
61,
6271,
28047,
67,
16085,
1769,
203,
3639,
460,
273,
389,
588,
13937,
12,
1584,
44,
67,
8412,
67,
15140,
16,
460,
1769,
203,
3639,
775,
203,
5411,
417,
93,
744,
18,
22270,
41,
1136,
774,
1345,
18,
1132,
12,
1132,
21433,
45,
654,
39,
3462,
12,
2316,
3631,
1131,
4727,
13,
203,
3639,
1135,
261,
2
] |
./partial_match/1/0x5Dc58f812b2e244DABA2fabd33f399cD699D7Ddc/sources/GammaFarm.sol | Calculate stake/unstake amounts: | uint256 lusdToUnstake = 0;
| 2,686,339 | [
1,
8695,
384,
911,
19,
23412,
911,
30980,
30,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
328,
407,
72,
774,
984,
334,
911,
273,
374,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-02-11
*/
// File: @aragon/os/contracts/common/EtherTokenConstant.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// aragonOS and aragon-apps rely on address(0) to denote native ETH, in
// contracts where both tokens and ETH are accepted
contract EtherTokenConstant {
address internal constant ETH = address(0);
}
// File: @aragon/apps-agent/contracts/standards/ERC1271.sol
pragma solidity 0.4.24;
// ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md
// Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified
// Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728
contract ERC1271 {
bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector
bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated
bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000;
/**
* @dev Function must be implemented by deriving contract
* @param _hash Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
* @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not
*
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4);
function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) {
return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE;
}
}
contract ERC1271Bytes is ERC1271 {
/**
* @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation
* @param _data Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
* @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not
*
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) {
return isValidSignature(keccak256(_data), _signature);
}
}
// File: @aragon/apps-agent/contracts/SignatureValidator.sol
pragma solidity 0.4.24;
// Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol
// This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442
library SignatureValidator {
enum SignatureMode {
Invalid, // 0x00
EIP712, // 0x01
EthSign, // 0x02
ERC1271, // 0x03
NMode // 0x04, to check if mode is specified, leave at the end
}
// bytes4(keccak256("isValidSignature(bytes,bytes)")
bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b;
uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000;
string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE";
/// @dev Validates that a hash was signed by a specified signer.
/// @param hash Hash which was signed.
/// @param signer Address of the signer.
/// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}.
/// @return Returns whether signature is from a specified user.
function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) {
if (signature.length == 0) {
return false;
}
uint8 modeByte = uint8(signature[0]);
if (modeByte >= uint8(SignatureMode.NMode)) {
return false;
}
SignatureMode mode = SignatureMode(modeByte);
if (mode == SignatureMode.EIP712) {
return ecVerify(hash, signer, signature);
} else if (mode == SignatureMode.EthSign) {
return ecVerify(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),
signer,
signature
);
} else if (mode == SignatureMode.ERC1271) {
// Pop the mode byte before sending it down the validation chain
return safeIsValidSignature(signer, hash, popFirstByte(signature));
} else {
return false;
}
}
function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) {
(bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature);
if (badSig) {
return false;
}
return signer == ecrecover(hash, v, r, s);
}
function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) {
if (signature.length != 66) {
badSig = true;
return;
}
v = uint8(signature[65]);
assembly {
r := mload(add(signature, 33))
s := mload(add(signature, 65))
}
// Allow signature version to be 0 or 1
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
badSig = true;
}
}
function popFirstByte(bytes memory input) private pure returns (bytes memory output) {
uint256 inputLength = input.length;
require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE);
output = new bytes(inputLength - 1);
if (output.length == 0) {
return output;
}
uint256 inputPointer;
uint256 outputPointer;
assembly {
inputPointer := add(input, 0x21)
outputPointer := add(output, 0x20)
}
memcpy(outputPointer, inputPointer, output.length);
}
function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) {
bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature);
bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS);
return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE;
}
function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) {
uint256 gasLeft = gasleft();
uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft;
bool ok;
assembly {
ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0)
}
if (!ok) {
return;
}
uint256 size;
assembly { size := returndatasize }
if (size != 32) {
return;
}
assembly {
let ptr := mload(0x40) // get next free memory ptr
returndatacopy(ptr, 0, size) // copy return from above `staticcall`
ret := mload(ptr) // read data at ptr and set it to be returned
}
return ret;
}
// From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol
function memcpy(uint256 dest, uint256 src, uint256 len) private pure {
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
}
// File: @aragon/apps-agent/contracts/standards/IERC165.sol
pragma solidity 0.4.24;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external pure returns (bool);
}
// File: @aragon/os/contracts/common/UnstructuredStorage.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
library UnstructuredStorage {
function getStorageBool(bytes32 position) internal view returns (bool data) {
assembly { data := sload(position) }
}
function getStorageAddress(bytes32 position) internal view returns (address data) {
assembly { data := sload(position) }
}
function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
assembly { data := sload(position) }
}
function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
assembly { data := sload(position) }
}
function setStorageBool(bytes32 position, bool data) internal {
assembly { sstore(position, data) }
}
function setStorageAddress(bytes32 position, address data) internal {
assembly { sstore(position, data) }
}
function setStorageBytes32(bytes32 position, bytes32 data) internal {
assembly { sstore(position, data) }
}
function setStorageUint256(bytes32 position, uint256 data) internal {
assembly { sstore(position, data) }
}
}
// File: @aragon/os/contracts/acl/IACL.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IACL {
function initialize(address permissionsCreator) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
}
// File: @aragon/os/contracts/common/IVaultRecoverable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IVaultRecoverable {
event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
function transferToVault(address token) external;
function allowRecoverability(address token) external view returns (bool);
function getRecoveryVault() external view returns (address);
}
// File: @aragon/os/contracts/kernel/IKernel.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IKernelEvents {
event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
}
// This should be an interface, but interfaces can't inherit yet :(
contract IKernel is IKernelEvents, IVaultRecoverable {
function acl() public view returns (IACL);
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
function setApp(bytes32 namespace, bytes32 appId, address app) public;
function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
}
// File: @aragon/os/contracts/apps/AppStorage.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract AppStorage {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
*/
bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
function kernel() public view returns (IKernel) {
return IKernel(KERNEL_POSITION.getStorageAddress());
}
function appId() public view returns (bytes32) {
return APP_ID_POSITION.getStorageBytes32();
}
function setKernel(IKernel _kernel) internal {
KERNEL_POSITION.setStorageAddress(address(_kernel));
}
function setAppId(bytes32 _appId) internal {
APP_ID_POSITION.setStorageBytes32(_appId);
}
}
// File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ACLSyntaxSugar {
function arr() internal pure returns (uint256[]) {
return new uint256[](0);
}
function arr(bytes32 _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(address _a, address _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c);
}
function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c, _d);
}
function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), _c, _d, _e);
}
function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(uint256 _a) internal pure returns (uint256[] r) {
r = new uint256[](1);
r[0] = _a;
}
function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
r = new uint256[](2);
r[0] = _a;
r[1] = _b;
}
function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
r = new uint256[](3);
r[0] = _a;
r[1] = _b;
r[2] = _c;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
r = new uint256[](4);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
r = new uint256[](5);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
r[4] = _e;
}
}
contract ACLHelpers {
function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 30));
}
function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 31));
}
function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
a = uint32(_x);
b = uint32(_x >> (8 * 4));
c = uint32(_x >> (8 * 8));
}
}
// File: @aragon/os/contracts/common/Uint256Helpers.sol
pragma solidity ^0.4.24;
library Uint256Helpers {
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
return uint64(a);
}
}
// File: @aragon/os/contracts/common/TimeHelpers.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
// File: @aragon/os/contracts/common/Initializable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Initializable is TimeHelpers {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.initializable.initializationBlock")
bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
modifier onlyInit {
require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
_;
}
modifier isInitialized {
require(hasInitialized(), ERROR_NOT_INITIALIZED);
_;
}
/**
* @return Block number in which the contract was initialized
*/
function getInitializationBlock() public view returns (uint256) {
return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
}
/**
* @return Whether the contract has been initialized by the time of the current block
*/
function hasInitialized() public view returns (bool) {
uint256 initializationBlock = getInitializationBlock();
return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
}
/**
* @dev Function to be called by top level contract after initialization has finished.
*/
function initialized() internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
}
/**
* @dev Function to be called by top level contract after initialization to enable the contract
* at a future block number rather than immediately.
*/
function initializedAt(uint256 _blockNumber) internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
}
}
// File: @aragon/os/contracts/common/Petrifiable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Petrifiable is Initializable {
// Use block UINT256_MAX (which should be never) as the initializable date
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
function isPetrified() public view returns (bool) {
return getInitializationBlock() == PETRIFIED_BLOCK;
}
/**
* @dev Function to be called by top level contract to prevent being initialized.
* Useful for freezing base contracts when they're used behind proxies.
*/
function petrify() internal onlyInit {
initializedAt(PETRIFIED_BLOCK);
}
}
// File: @aragon/os/contracts/common/Autopetrified.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Autopetrified is Petrifiable {
constructor() public {
// Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
// This renders them uninitializable (and unusable without a proxy).
petrify();
}
}
// File: @aragon/os/contracts/common/ConversionHelpers.sol
pragma solidity ^0.4.24;
library ConversionHelpers {
string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
// Force cast the uint256[] into a bytes array, by overwriting its length
// Note that the bytes array doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 byteLength = _input.length * 32;
assembly {
output := _input
mstore(output, byteLength)
}
}
function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
// Force cast the bytes array into a uint256[], by overwriting its length
// Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 intsLength = _input.length / 32;
require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
assembly {
output := _input
mstore(output, intsLength)
}
}
}
// File: @aragon/os/contracts/common/ReentrancyGuard.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ReentrancyGuard {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
*/
bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
modifier nonReentrant() {
// Ensure mutex is unlocked
require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
// Lock mutex before function call
REENTRANCY_MUTEX_POSITION.setStorageBool(true);
// Perform function call
_;
// Unlock mutex after function call
REENTRANCY_MUTEX_POSITION.setStorageBool(false);
}
}
// File: @aragon/os/contracts/lib/token/ERC20.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, 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
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @aragon/os/contracts/common/IsContract.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
// File: @aragon/os/contracts/common/SafeERC20.sol
// Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
// and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
pragma solidity ^0.4.24;
library SafeERC20 {
// Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
// https://github.com/ethereum/solidity/issues/3544
bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
private
returns (bool)
{
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
function staticInvoke(address _addr, bytes memory _calldata)
private
view
returns (bool, uint256)
{
bool success;
uint256 ret;
assembly {
let ptr := mload(0x40) // free memory pointer
success := staticcall(
gas, // forward all gas
_addr, // address
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
ret := mload(ptr)
}
}
return (success, ret);
}
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
TRANSFER_SELECTOR,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
/**
* @dev Static call into ERC20.balanceOf().
* Reverts if the call fails for some reason (should never fail).
*/
function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
bytes memory balanceOfCallData = abi.encodeWithSelector(
_token.balanceOf.selector,
_owner
);
(bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
require(success, ERROR_TOKEN_BALANCE_REVERTED);
return tokenBalance;
}
/**
* @dev Static call into ERC20.allowance().
* Reverts if the call fails for some reason (should never fail).
*/
function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
bytes memory allowanceCallData = abi.encodeWithSelector(
_token.allowance.selector,
_owner,
_spender
);
(bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return allowance;
}
}
// File: @aragon/os/contracts/common/VaultRecoverable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
using SafeERC20 for ERC20;
string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
/**
* @notice Send funds to recovery Vault. This contract should never receive funds,
* but in case it does, this function allows one to recover them.
* @param _token Token balance to be sent to recovery vault.
*/
function transferToVault(address _token) external {
require(allowRecoverability(_token), ERROR_DISALLOWED);
address vault = getRecoveryVault();
require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
uint256 balance;
if (_token == ETH) {
balance = address(this).balance;
vault.transfer(balance);
} else {
ERC20 token = ERC20(_token);
balance = token.staticBalanceOf(this);
require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
}
emit RecoverToVault(vault, _token, balance);
}
/**
* @dev By default deriving from AragonApp makes it recoverable
* @param token Token address that would be recovered
* @return bool whether the app allows the recovery
*/
function allowRecoverability(address token) public view returns (bool) {
return true;
}
// Cast non-implemented interface to be public so we can use it internally
function getRecoveryVault() public view returns (address);
}
// File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IEVMScriptExecutor {
function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
function executorType() external pure returns (bytes32);
}
// File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRegistryConstants {
/* Hardcoded constants to save gas
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
*/
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
}
interface IEVMScriptRegistry {
function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
function disableScriptExecutor(uint256 executorId) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
}
// File: @aragon/os/contracts/kernel/KernelConstants.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract KernelAppIds {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
*/
bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
}
contract KernelNamespaceConstants {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
*/
bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
}
// File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
/* This is manually crafted in assembly
string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
*/
event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
}
function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
return IEVMScriptRegistry(registryAddr);
}
function runScript(bytes _script, bytes _input, address[] _blacklist)
internal
isInitialized
protectState
returns (bytes)
{
IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
bytes4 sig = executor.execScript.selector;
bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
bytes memory output;
assembly {
let success := delegatecall(
gas, // forward all gas
executor, // address
add(data, 0x20), // calldata start
mload(data), // calldata length
0, // don't write output (we'll handle this ourselves)
0 // don't write output
)
output := mload(0x40) // free mem ptr get
switch success
case 0 {
// If the call errored, forward its full error data
returndatacopy(output, 0, returndatasize)
revert(output, returndatasize)
}
default {
switch gt(returndatasize, 0x3f)
case 0 {
// Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
// revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
// See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
// this memory layout
mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Copy result
//
// Needs to perform an ABI decode for the expected `bytes` return type of
// `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
// [ position of the first dynamic length return value = 0x20 (32 bytes) ]
// [ output length (32 bytes) ]
// [ output content (N bytes) ]
//
// Perform the ABI decode by ignoring the first 32 bytes of the return data
let copysize := sub(returndatasize, 0x20)
returndatacopy(output, 0x20, copysize)
mstore(0x40, add(output, copysize)) // free mem ptr set
}
}
}
emit ScriptResult(address(executor), _script, _input, output);
return output;
}
modifier protectState {
address preKernel = address(kernel());
bytes32 preAppId = appId();
_; // exec
require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
}
}
// File: @aragon/os/contracts/apps/AragonApp.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
// that they can never be initialized.
// Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
// ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
// are included so that they are automatically usable by subclassing contracts
contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
modifier auth(bytes32 _role) {
require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
_;
}
modifier authP(bytes32 _role, uint256[] _params) {
require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
_;
}
/**
* @dev Check whether an action can be performed by a sender for a particular role on this app
* @param _sender Sender of the call
* @param _role Role on this app
* @param _params Permission params for the role
* @return Boolean indicating whether the sender has the permissions to perform the action.
* Always returns false if the app hasn't been initialized yet.
*/
function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
if (!hasInitialized()) {
return false;
}
IKernel linkedKernel = kernel();
if (address(linkedKernel) == address(0)) {
return false;
}
return linkedKernel.hasPermission(
_sender,
address(this),
_role,
ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
);
}
/**
* @dev Get the recovery vault for the app
* @return Recovery vault address for the app
*/
function getRecoveryVault() public view returns (address) {
// Funds recovery via a vault is only available when used with a kernel
return kernel().getRecoveryVault(); // if kernel is not set, it will revert
}
}
// File: @aragon/os/contracts/common/DepositableStorage.sol
pragma solidity 0.4.24;
contract DepositableStorage {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.depositableStorage.depositable")
bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea;
function isDepositable() public view returns (bool) {
return DEPOSITABLE_POSITION.getStorageBool();
}
function setDepositable(bool _depositable) internal {
DEPOSITABLE_POSITION.setStorageBool(_depositable);
}
}
// File: @aragon/apps-vault/contracts/Vault.sol
pragma solidity 0.4.24;
contract Vault is EtherTokenConstant, AragonApp, DepositableStorage {
using SafeERC20 for ERC20;
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO";
string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE";
string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO";
string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO";
string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED";
string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH";
string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT";
string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED";
event VaultTransfer(address indexed token, address indexed to, uint256 amount);
event VaultDeposit(address indexed token, address indexed sender, uint256 amount);
/**
* @dev On a normal send() or transfer() this fallback is never executed as it will be
* intercepted by the Proxy (see aragonOS#281)
*/
function () external payable isInitialized {
require(msg.data.length == 0, ERROR_DATA_NON_ZERO);
_deposit(ETH, msg.value);
}
/**
* @notice Initialize Vault app
* @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work
*/
function initialize() external onlyInit {
initialized();
setDepositable(true);
}
/**
* @notice Deposit `_value` `_token` to the vault
* @param _token Address of the token being transferred
* @param _value Amount of tokens being transferred
*/
function deposit(address _token, uint256 _value) external payable isInitialized {
_deposit(_token, _value);
}
/**
* @notice Transfer `_value` `_token` from the Vault to `_to`
* @param _token Address of the token being transferred
* @param _to Address of the recipient of tokens
* @param _value Amount of tokens being transferred
*/
/* solium-disable-next-line function-order */
function transfer(address _token, address _to, uint256 _value)
external
authP(TRANSFER_ROLE, arr(_token, _to, _value))
{
require(_value > 0, ERROR_TRANSFER_VALUE_ZERO);
if (_token == ETH) {
require(_to.send(_value), ERROR_SEND_REVERTED);
} else {
require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED);
}
emit VaultTransfer(_token, _to, _value);
}
function balance(address _token) public view returns (uint256) {
if (_token == ETH) {
return address(this).balance;
} else {
return ERC20(_token).staticBalanceOf(address(this));
}
}
/**
* @dev Disable recovery escape hatch, as it could be used
* maliciously to transfer funds away from the vault
*/
function allowRecoverability(address) public view returns (bool) {
return false;
}
function _deposit(address _token, uint256 _value) internal {
require(isDepositable(), ERROR_NOT_DEPOSITABLE);
require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO);
if (_token == ETH) {
// Deposit is implicit in this case
require(msg.value == _value, ERROR_VALUE_MISMATCH);
} else {
require(
ERC20(_token).safeTransferFrom(msg.sender, address(this), _value),
ERROR_TOKEN_TRANSFER_FROM_REVERTED
);
}
emit VaultDeposit(_token, msg.sender, _value);
}
}
// File: @aragon/os/contracts/common/IForwarder.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IForwarder {
function isForwarder() external pure returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function canForward(address sender, bytes evmCallScript) public view returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function forward(bytes evmCallScript) public;
}
// File: @aragon/apps-agent/contracts/Agent.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault {
/* Hardcoded constants to save gas
bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE");
bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE");
bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE");
bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE");
bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE");
bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE");
bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE");
*/
bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4;
bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694;
bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa;
bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a;
bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c;
bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c;
bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f;
uint256 public constant PROTECTED_TOKENS_CAP = 10;
bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7;
string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED";
string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED";
string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED";
string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED";
string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20";
string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED";
string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED";
string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF";
string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD";
mapping (bytes32 => bool) public isPresigned;
address public designatedSigner;
address[] public protectedTokens;
event SafeExecute(address indexed sender, address indexed target, bytes data);
event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data);
event AddProtectedToken(address indexed token);
event RemoveProtectedToken(address indexed token);
event PresignHash(address indexed sender, bytes32 indexed hash);
event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner);
/**
* @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'`
* @param _target Address where the action is being executed
* @param _ethValue Amount of ETH from the contract that is sent with the action
* @param _data Calldata for the action
* @return Exits call frame forwarding the return data of the executed call (either error or success data)
*/
function execute(address _target, uint256 _ethValue, bytes _data)
external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context
authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs
{
bool result = _target.call.value(_ethValue)(_data);
if (result) {
emit Execute(msg.sender, _target, _ethValue, _data);
}
assembly {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, returndatasize) }
default { return(ptr, returndatasize) }
}
}
/**
* @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent
* @param _target Address where the action is being executed
* @param _data Calldata for the action
* @return Exits call frame forwarding the return data of the executed call (either error or success data)
*/
function safeExecute(address _target, bytes _data)
external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context
authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs
{
uint256 protectedTokensLength = protectedTokens.length;
address[] memory protectedTokens_ = new address[](protectedTokensLength);
uint256[] memory balances = new uint256[](protectedTokensLength);
for (uint256 i = 0; i < protectedTokensLength; i++) {
address token = protectedTokens[i];
require(_target != token, ERROR_TARGET_PROTECTED);
// we copy the protected tokens array to check whether the storage array has been modified during the underlying call
protectedTokens_[i] = token;
// we copy the balances to check whether they have been modified during the underlying call
balances[i] = balance(token);
}
bool result = _target.call(_data);
bytes32 ptr;
uint256 size;
assembly {
size := returndatasize
ptr := mload(0x40)
mstore(0x40, add(ptr, returndatasize))
returndatacopy(ptr, 0, returndatasize)
}
if (result) {
// if the underlying call has succeeded, we check that the protected tokens
// and their balances have not been modified and return the call's return data
require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED);
for (uint256 j = 0; j < protectedTokensLength; j++) {
require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED);
require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED);
}
emit SafeExecute(msg.sender, _target, _data);
assembly {
return(ptr, size)
}
} else {
// if the underlying call has failed, we revert and forward returned error data
assembly {
revert(ptr, size)
}
}
}
/**
* @notice Add `_token.symbol(): string` to the list of protected tokens
* @param _token Address of the token to be protected
*/
function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) {
require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED);
require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20);
require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED);
_addProtectedToken(_token);
}
/**
* @notice Remove `_token.symbol(): string` from the list of protected tokens
* @param _token Address of the token to be unprotected
*/
function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) {
require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED);
_removeProtectedToken(_token);
}
/**
* @notice Pre-sign hash `_hash`
* @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()'
*/
function presignHash(bytes32 _hash)
external
authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash))
{
isPresigned[_hash] = true;
emit PresignHash(msg.sender, _hash);
}
/**
* @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app
* @param _designatedSigner Address that will be able to sign messages on behalf of the app
*/
function setDesignatedSigner(address _designatedSigner)
external
authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner))
{
// Prevent an infinite loop by setting the app itself as its designated signer.
// An undetectable loop can be created by setting a different contract as the
// designated signer which calls back into `isValidSignature`.
// Given that `isValidSignature` is always called with just 50k gas, the max
// damage of the loop is wasting 50k gas.
require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF);
address oldDesignatedSigner = designatedSigner;
designatedSigner = _designatedSigner;
emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner);
}
// Forwarding fns
/**
* @notice Tells whether the Agent app is a forwarder or not
* @dev IForwarder interface conformance
* @return Always true
*/
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Execute the script as the Agent app
* @dev IForwarder interface conformance. Forwards any token holder action.
* @param _evmScript Script being executed
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
bytes memory input = ""; // no input
address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything
runScript(_evmScript, input, blacklist);
// We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful
}
/**
* @notice Tells whether `_sender` can forward actions or not
* @dev IForwarder interface conformance
* @param _sender Address of the account intending to forward an action
* @return True if the given address can run scripts, false otherwise
*/
function canForward(address _sender, bytes _evmScript) public view returns (bool) {
// Note that `canPerform()` implicitly does an initialization check itself
return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript)));
}
// ERC-165 conformance
/**
* @notice Tells whether this contract supports a given ERC-165 interface
* @param _interfaceId Interface bytes to check
* @return True if this contract supports the interface
*/
function supportsInterface(bytes4 _interfaceId) external pure returns (bool) {
return
_interfaceId == ERC1271_INTERFACE_ID ||
_interfaceId == ERC165_INTERFACE_ID;
}
// ERC-1271 conformance
/**
* @notice Tells whether a signature is seen as valid by this contract through ERC-1271
* @param _hash Arbitrary length data signed on the behalf of address (this)
* @param _signature Signature byte array associated with _data
* @return The ERC-1271 magic value if the signature is valid
*/
function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) {
// Short-circuit in case the hash was presigned. Optimization as performing calls
// and ecrecover is more expensive than an SLOAD.
if (isPresigned[_hash]) {
return returnIsValidSignatureMagicNumber(true);
}
bool isValid;
if (designatedSigner == address(0)) {
isValid = false;
} else {
isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature);
}
return returnIsValidSignatureMagicNumber(isValid);
}
// Getters
function getProtectedTokensLength() public view isInitialized returns (uint256) {
return protectedTokens.length;
}
// Internal fns
function _addProtectedToken(address _token) internal {
protectedTokens.push(_token);
emit AddProtectedToken(_token);
}
function _removeProtectedToken(address _token) internal {
protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1];
protectedTokens.length--;
emit RemoveProtectedToken(_token);
}
function _isERC20(address _token) internal view returns (bool) {
if (!isContract(_token)) {
return false;
}
// Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now)
balance(_token);
return true;
}
function _protectedTokenIndex(address _token) internal view returns (uint256) {
for (uint i = 0; i < protectedTokens.length; i++) {
if (protectedTokens[i] == _token) {
return i;
}
}
revert(ERROR_TOKEN_NOT_PROTECTED);
}
function _tokenIsProtected(address _token) internal view returns (bool) {
for (uint256 i = 0; i < protectedTokens.length; i++) {
if (protectedTokens[i] == _token) {
return true;
}
}
return false;
}
function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(_evmScript)));
}
function _getSig(bytes _data) internal pure returns (bytes4 sig) {
if (_data.length < 4) {
return;
}
assembly { sig := mload(add(_data, 0x20)) }
}
}
// File: @aragon/os/contracts/lib/math/SafeMath.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted to use pragma ^0.4.24 and satisfy our linter rules
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b, ERROR_MUL_OVERFLOW);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// File: @aragon/os/contracts/lib/math/SafeMath64.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules
// Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417
pragma solidity ^0.4.24;
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// File: @aragon/apps-shared-minime/contracts/ITokenController.sol
pragma solidity ^0.4.24;
/// @dev The token controller contract must implement these functions
interface ITokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) external payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) external returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) external returns(bool);
}
// File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol
pragma solidity ^0.4.24;
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController {
require(msg.sender == controller);
_;
}
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) onlyController public {
controller = _newController;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(
address from,
uint256 _amount,
address _token,
bytes _data
) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = "MMT_0.1"; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
MiniMeTokenFactory _tokenFactory,
MiniMeToken _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public
{
tokenFactory = _tokenFactory;
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = _parentToken;
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount)
return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onTransfer(_from, _to, _amount) == true);
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true);
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) {
require(approve(_spender, _amount));
_spender.receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(MiniMeToken)
{
uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
snapshot,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), snapshot);
return cloneToken;
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) onlyController public {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) {
if (checkpoints.length == 0)
return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock)
return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0)
return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () external payable {
require(isContract(controller));
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true);
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) onlyController public {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
MiniMeToken _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken)
{
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
// File: @aragon/apps-voting/contracts/Voting.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Voting is IForwarder, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE");
bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE");
bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE");
uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18
string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE";
string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS";
string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS";
string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS";
string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG";
string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG";
string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE";
string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE";
string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD";
string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER";
enum VoterState { Absent, Yea, Nay }
struct Vote {
bool executed;
uint64 startDate;
uint64 snapshotBlock;
uint64 supportRequiredPct;
uint64 minAcceptQuorumPct;
uint256 yea;
uint256 nay;
uint256 votingPower;
bytes executionScript;
mapping (address => VoterState) voters;
}
MiniMeToken public token;
uint64 public supportRequiredPct;
uint64 public minAcceptQuorumPct;
uint64 public voteTime;
// We are mimicing an array, we use a mapping instead to make app upgrade more graceful
mapping (uint256 => Vote) internal votes;
uint256 public votesLength;
event StartVote(uint256 indexed voteId, address indexed creator, string metadata);
event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake);
event ExecuteVote(uint256 indexed voteId);
event ChangeSupportRequired(uint64 supportRequiredPct);
event ChangeMinQuorum(uint64 minAcceptQuorumPct);
modifier voteExists(uint256 _voteId) {
require(_voteId < votesLength, ERROR_NO_VOTE);
_;
}
/**
* @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)`
* @param _token MiniMeToken Address that will be used as governance token
* @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%)
* @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%)
* @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision)
*/
function initialize(
MiniMeToken _token,
uint64 _supportRequiredPct,
uint64 _minAcceptQuorumPct,
uint64 _voteTime
)
external
onlyInit
{
initialized();
require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS);
require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG);
token = _token;
supportRequiredPct = _supportRequiredPct;
minAcceptQuorumPct = _minAcceptQuorumPct;
voteTime = _voteTime;
}
/**
* @notice Change required support to `@formatPct(_supportRequiredPct)`%
* @param _supportRequiredPct New required support
*/
function changeSupportRequiredPct(uint64 _supportRequiredPct)
external
authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct)))
{
require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS);
require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG);
supportRequiredPct = _supportRequiredPct;
emit ChangeSupportRequired(_supportRequiredPct);
}
/**
* @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`%
* @param _minAcceptQuorumPct New acceptance quorum
*/
function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct)
external
authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct)))
{
require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS);
minAcceptQuorumPct = _minAcceptQuorumPct;
emit ChangeMinQuorum(_minAcceptQuorumPct);
}
/**
* @notice Create a new vote about "`_metadata`"
* @param _executionScript EVM script to be executed on approval
* @param _metadata Vote metadata
* @return voteId Id for newly created vote
*/
function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) {
return _newVote(_executionScript, _metadata, true, true);
}
/**
* @notice Create a new vote about "`_metadata`"
* @param _executionScript EVM script to be executed on approval
* @param _metadata Vote metadata
* @param _castVote Whether to also cast newly created vote
* @param _executesIfDecided Whether to also immediately execute newly created vote if decided
* @return voteId id for newly created vote
*/
function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided)
external
auth(CREATE_VOTES_ROLE)
returns (uint256 voteId)
{
return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided);
}
/**
* @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId`
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @param _voteId Id for vote
* @param _supports Whether voter supports the vote
* @param _executesIfDecided Whether the vote should execute its action if it becomes decided
*/
function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) {
require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE);
_vote(_voteId, _supports, msg.sender, _executesIfDecided);
}
/**
* @notice Execute vote #`_voteId`
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @param _voteId Id for vote
*/
function executeVote(uint256 _voteId) external voteExists(_voteId) {
_executeVote(_voteId);
}
// Forwarding fns
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Creates a vote to execute the desired action, and casts a support vote if possible
* @dev IForwarder interface conformance
* @param _evmScript Start vote with script
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
_newVote(_evmScript, "", true, true);
}
function canForward(address _sender, bytes) public view returns (bool) {
// Note that `canPerform()` implicitly does an initialization check itself
return canPerform(_sender, CREATE_VOTES_ROLE, arr());
}
// Getter fns
/**
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
*/
function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) {
return _canExecute(_voteId);
}
/**
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
*/
function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) {
return _canVote(_voteId, _voter);
}
function getVote(uint256 _voteId)
public
view
voteExists(_voteId)
returns (
bool open,
bool executed,
uint64 startDate,
uint64 snapshotBlock,
uint64 supportRequired,
uint64 minAcceptQuorum,
uint256 yea,
uint256 nay,
uint256 votingPower,
bytes script
)
{
Vote storage vote_ = votes[_voteId];
open = _isVoteOpen(vote_);
executed = vote_.executed;
startDate = vote_.startDate;
snapshotBlock = vote_.snapshotBlock;
supportRequired = vote_.supportRequiredPct;
minAcceptQuorum = vote_.minAcceptQuorumPct;
yea = vote_.yea;
nay = vote_.nay;
votingPower = vote_.votingPower;
script = vote_.executionScript;
}
function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) {
return votes[_voteId].voters[_voter];
}
// Internal fns
function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided)
internal
returns (uint256 voteId)
{
uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block
uint256 votingPower = token.totalSupplyAt(snapshotBlock);
require(votingPower > 0, ERROR_NO_VOTING_POWER);
voteId = votesLength++;
Vote storage vote_ = votes[voteId];
vote_.startDate = getTimestamp64();
vote_.snapshotBlock = snapshotBlock;
vote_.supportRequiredPct = supportRequiredPct;
vote_.minAcceptQuorumPct = minAcceptQuorumPct;
vote_.votingPower = votingPower;
vote_.executionScript = _executionScript;
emit StartVote(voteId, msg.sender, _metadata);
if (_castVote && _canVote(voteId, msg.sender)) {
_vote(voteId, true, msg.sender, _executesIfDecided);
}
}
function _vote(
uint256 _voteId,
bool _supports,
address _voter,
bool _executesIfDecided
) internal
{
Vote storage vote_ = votes[_voteId];
// This could re-enter, though we can assume the governance token is not malicious
uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock);
VoterState state = vote_.voters[_voter];
// If voter had previously voted, decrease count
if (state == VoterState.Yea) {
vote_.yea = vote_.yea.sub(voterStake);
} else if (state == VoterState.Nay) {
vote_.nay = vote_.nay.sub(voterStake);
}
if (_supports) {
vote_.yea = vote_.yea.add(voterStake);
} else {
vote_.nay = vote_.nay.add(voterStake);
}
vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay;
emit CastVote(_voteId, _voter, _supports, voterStake);
if (_executesIfDecided && _canExecute(_voteId)) {
// We've already checked if the vote can be executed with `_canExecute()`
_unsafeExecuteVote(_voteId);
}
}
function _executeVote(uint256 _voteId) internal {
require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE);
_unsafeExecuteVote(_voteId);
}
/**
* @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed
*/
function _unsafeExecuteVote(uint256 _voteId) internal {
Vote storage vote_ = votes[_voteId];
vote_.executed = true;
bytes memory input = new bytes(0); // TODO: Consider input for voting scripts
runScript(vote_.executionScript, input, new address[](0));
emit ExecuteVote(_voteId);
}
function _canExecute(uint256 _voteId) internal view returns (bool) {
Vote storage vote_ = votes[_voteId];
if (vote_.executed) {
return false;
}
// Voting is already decided
if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) {
return true;
}
// Vote ended?
if (_isVoteOpen(vote_)) {
return false;
}
// Has enough support?
uint256 totalVotes = vote_.yea.add(vote_.nay);
if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) {
return false;
}
// Has min quorum?
if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) {
return false;
}
return true;
}
function _canVote(uint256 _voteId, address _voter) internal view returns (bool) {
Vote storage vote_ = votes[_voteId];
return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0;
}
function _isVoteOpen(Vote storage vote_) internal view returns (bool) {
return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed;
}
/**
* @dev Calculates whether `_value` is more than a percentage `_pct` of `_total`
*/
function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) {
if (_total == 0) {
return false;
}
uint256 computedPct = _value.mul(PCT_BASE) / _total;
return computedPct > _pct;
}
}
// File: @aragon/ppf-contracts/contracts/IFeed.sol
pragma solidity ^0.4.18;
interface IFeed {
function ratePrecision() external pure returns (uint256);
function get(address base, address quote) external view returns (uint128 xrt, uint64 when);
}
// File: @aragon/apps-finance/contracts/Finance.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Finance is EtherTokenConstant, IsContract, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
using SafeERC20 for ERC20;
bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE");
bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE");
bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE");
bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE");
bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE");
uint256 internal constant NO_SCHEDULED_PAYMENT = 0;
uint256 internal constant NO_TRANSACTION = 0;
uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20;
uint256 internal constant MAX_UINT256 = uint256(-1);
uint64 internal constant MAX_UINT64 = uint64(-1);
uint64 internal constant MINIMUM_PERIOD = uint64(1 days);
string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION";
string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT";
string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION";
string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD";
string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT";
string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT";
string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO";
string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO";
string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO";
string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE";
string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO";
string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO";
string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH";
string private constant ERROR_BUDGET = "FINANCE_BUDGET";
string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM";
string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME";
string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER";
string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT";
string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED";
string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE";
string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET";
// Order optimized for storage
struct ScheduledPayment {
address token;
address receiver;
address createdBy;
bool inactive;
uint256 amount;
uint64 initialPaymentTime;
uint64 interval;
uint64 maxExecutions;
uint64 executions;
}
// Order optimized for storage
struct Transaction {
address token;
address entity;
bool isIncoming;
uint256 amount;
uint256 paymentId;
uint64 paymentExecutionNumber;
uint64 date;
uint64 periodId;
}
struct TokenStatement {
uint256 expenses;
uint256 income;
}
struct Period {
uint64 startTime;
uint64 endTime;
uint256 firstTransactionId;
uint256 lastTransactionId;
mapping (address => TokenStatement) tokenStatement;
}
struct Settings {
uint64 periodDuration;
mapping (address => uint256) budgets;
mapping (address => bool) hasBudget;
}
Vault public vault;
Settings internal settings;
// We are mimicing arrays, we use mappings instead to make app upgrade more graceful
mapping (uint256 => ScheduledPayment) internal scheduledPayments;
// Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not
// linked to a scheduled payment
uint256 public paymentsNextIndex;
mapping (uint256 => Transaction) internal transactions;
uint256 public transactionsNextIndex;
mapping (uint64 => Period) internal periods;
uint64 public periodsLength;
event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds);
event SetBudget(address indexed token, uint256 amount, bool hasBudget);
event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference);
event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference);
event ChangePaymentState(uint256 indexed paymentId, bool active);
event ChangePeriodDuration(uint64 newDuration);
event PaymentFailure(uint256 paymentId);
// Modifier used by all methods that impact accounting to make sure accounting period
// is changed before the operation if needed
// NOTE: its use **MUST** be accompanied by an initialization check
modifier transitionsPeriod {
bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions());
require(completeTransition, ERROR_COMPLETE_TRANSITION);
_;
}
modifier scheduledPaymentExists(uint256 _paymentId) {
require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT);
_;
}
modifier transactionExists(uint256 _transactionId) {
require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION);
_;
}
modifier periodExists(uint64 _periodId) {
require(_periodId < periodsLength, ERROR_NO_PERIOD);
_;
}
/**
* @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever
* @dev Send ETH to Vault. Send all the available balance.
*/
function () external payable isInitialized transitionsPeriod {
require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO);
_deposit(
ETH,
msg.value,
"Ether transfer to Finance app",
msg.sender,
true
);
}
/**
* @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)`
* @param _vault Address of the vault Finance will rely on (non changeable)
* @param _periodDuration Duration in seconds of each period
*/
function initialize(Vault _vault, uint64 _periodDuration) external onlyInit {
initialized();
require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT);
vault = _vault;
require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT);
settings.periodDuration = _periodDuration;
// Reserve the first scheduled payment index as an unused index for transactions not linked
// to a scheduled payment
scheduledPayments[0].inactive = true;
paymentsNextIndex = 1;
// Reserve the first transaction index as an unused index for periods with no transactions
transactionsNextIndex = 1;
// Start the first period
_newPeriod(getTimestamp64());
}
/**
* @notice Deposit `@tokenAmount(_token, _amount)`
* @dev Deposit for approved ERC20 tokens or ETH
* @param _token Address of deposited token
* @param _amount Amount of tokens sent
* @param _reference Reason for payment
*/
function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod {
require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO);
if (_token == ETH) {
// Ensure that the ETH sent with the transaction equals the amount in the deposit
require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH);
}
_deposit(
_token,
_amount,
_reference,
msg.sender,
true
);
}
/**
* @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`'
* @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256`
* as its interval auth parameter (as a sentinel value for "never repeating").
* While this protects against most cases (you typically want to set a baseline requirement
* for interval time), it does mean users will have to explicitly check for this case when
* granting a permission that includes a upperbound requirement on the interval time.
* @param _token Address of token for payment
* @param _receiver Address that will receive payment
* @param _amount Tokens that are paid every time the payment is due
* @param _reference String detailing payment reason
*/
function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference)
external
// Use MAX_UINT256 as the interval parameter, as this payment will never repeat
// Payment time parameter is left as the last param as it was added later
authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp()))
transitionsPeriod
{
require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO);
_makePaymentTransaction(
_token,
_receiver,
_amount,
NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created
0, // also unrelated to any payment executions
_reference
);
}
/**
* @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)`
* @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used
* @param _token Address of token for payment
* @param _receiver Address that will receive payment
* @param _amount Tokens that are paid every time the payment is due
* @param _initialPaymentTime Timestamp for when the first payment is done
* @param _interval Number of seconds that need to pass between payment transactions
* @param _maxExecutions Maximum instances a payment can be executed
* @param _reference String detailing payment reason
*/
function newScheduledPayment(
address _token,
address _receiver,
uint256 _amount,
uint64 _initialPaymentTime,
uint64 _interval,
uint64 _maxExecutions,
string _reference
)
external
// Payment time parameter is left as the last param as it was added later
authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime)))
transitionsPeriod
returns (uint256 paymentId)
{
require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO);
require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO);
require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO);
// Token budget must not be set at all or allow at least one instance of this payment each period
require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET);
// Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead
if (_maxExecutions == 1) {
require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE);
}
paymentId = paymentsNextIndex++;
emit NewPayment(paymentId, _receiver, _maxExecutions, _reference);
ScheduledPayment storage payment = scheduledPayments[paymentId];
payment.token = _token;
payment.receiver = _receiver;
payment.amount = _amount;
payment.initialPaymentTime = _initialPaymentTime;
payment.interval = _interval;
payment.maxExecutions = _maxExecutions;
payment.createdBy = msg.sender;
// We skip checking how many times the new payment was executed to allow creating new
// scheduled payments before having enough vault balance
_executePayment(paymentId);
}
/**
* @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period
* @param _periodDuration Duration in seconds for accounting periods
*/
function setPeriodDuration(uint64 _periodDuration)
external
authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration)))
transitionsPeriod
{
require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT);
settings.periodDuration = _periodDuration;
emit ChangePeriodDuration(_periodDuration);
}
/**
* @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately
* @param _token Address for token
* @param _amount New budget amount
*/
function setBudget(
address _token,
uint256 _amount
)
external
authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0)))
transitionsPeriod
{
settings.budgets[_token] = _amount;
if (!settings.hasBudget[_token]) {
settings.hasBudget[_token] = true;
}
emit SetBudget(_token, _amount, true);
}
/**
* @notice Remove spending limit for `_token.symbol(): string`, effective immediately
* @param _token Address for token
*/
function removeBudget(address _token)
external
authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0)))
transitionsPeriod
{
settings.budgets[_token] = 0;
settings.hasBudget[_token] = false;
emit SetBudget(_token, 0, false);
}
/**
* @notice Execute pending payment #`_paymentId`
* @dev Executes any payment (requires role)
* @param _paymentId Identifier for payment
*/
function executePayment(uint256 _paymentId)
external
authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount))
scheduledPaymentExists(_paymentId)
transitionsPeriod
{
_executePaymentAtLeastOnce(_paymentId);
}
/**
* @notice Execute pending payment #`_paymentId`
* @dev Always allow receiver of a payment to trigger execution
* Initialization check is implicitly provided by `scheduledPaymentExists()` as new
* scheduled payments can only be created via `newScheduledPayment(),` which requires initialization
* @param _paymentId Identifier for payment
*/
function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod {
require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER);
_executePaymentAtLeastOnce(_paymentId);
}
/**
* @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId`
* @dev Note that we do not require this action to transition periods, as it doesn't directly
* impact any accounting periods.
* Not having to transition periods also makes disabling payments easier to prevent funds
* from being pulled out in the event of a breach.
* @param _paymentId Identifier for payment
* @param _active Whether it will be active or inactive
*/
function setPaymentStatus(uint256 _paymentId, bool _active)
external
authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0)))
scheduledPaymentExists(_paymentId)
{
scheduledPayments[_paymentId].inactive = !_active;
emit ChangePaymentState(_paymentId, _active);
}
/**
* @notice Send tokens held in this contract to the Vault
* @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens.
* This contract should never receive tokens with a simple transfer call, but in case it
* happens, this function allows for their recovery.
* @param _token Token whose balance is going to be transferred.
*/
function recoverToVault(address _token) external isInitialized transitionsPeriod {
uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this));
require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO);
_deposit(
_token,
amount,
"Recover to Vault",
address(this),
false
);
}
/**
* @notice Transition accounting period if needed
* @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions
* param is provided. If more than the specified number of periods need to be transitioned,
* it will return false.
* @param _maxTransitions Maximum periods that can be transitioned
* @return success Boolean indicating whether the accounting period is the correct one (if false,
* maxTransitions was surpased and another call is needed)
*/
function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) {
return _tryTransitionAccountingPeriod(_maxTransitions);
}
// Getter fns
/**
* @dev Disable recovery escape hatch if the app has been initialized, as it could be used
* maliciously to transfer funds in the Finance app to another Vault
* finance#recoverToVault() should be used to recover funds to the Finance's vault
*/
function allowRecoverability(address) public view returns (bool) {
return !hasInitialized();
}
function getPayment(uint256 _paymentId)
public
view
scheduledPaymentExists(_paymentId)
returns (
address token,
address receiver,
uint256 amount,
uint64 initialPaymentTime,
uint64 interval,
uint64 maxExecutions,
bool inactive,
uint64 executions,
address createdBy
)
{
ScheduledPayment storage payment = scheduledPayments[_paymentId];
token = payment.token;
receiver = payment.receiver;
amount = payment.amount;
initialPaymentTime = payment.initialPaymentTime;
interval = payment.interval;
maxExecutions = payment.maxExecutions;
executions = payment.executions;
inactive = payment.inactive;
createdBy = payment.createdBy;
}
function getTransaction(uint256 _transactionId)
public
view
transactionExists(_transactionId)
returns (
uint64 periodId,
uint256 amount,
uint256 paymentId,
uint64 paymentExecutionNumber,
address token,
address entity,
bool isIncoming,
uint64 date
)
{
Transaction storage transaction = transactions[_transactionId];
token = transaction.token;
entity = transaction.entity;
isIncoming = transaction.isIncoming;
date = transaction.date;
periodId = transaction.periodId;
amount = transaction.amount;
paymentId = transaction.paymentId;
paymentExecutionNumber = transaction.paymentExecutionNumber;
}
function getPeriod(uint64 _periodId)
public
view
periodExists(_periodId)
returns (
bool isCurrent,
uint64 startTime,
uint64 endTime,
uint256 firstTransactionId,
uint256 lastTransactionId
)
{
Period storage period = periods[_periodId];
isCurrent = _currentPeriodId() == _periodId;
startTime = period.startTime;
endTime = period.endTime;
firstTransactionId = period.firstTransactionId;
lastTransactionId = period.lastTransactionId;
}
function getPeriodTokenStatement(uint64 _periodId, address _token)
public
view
periodExists(_periodId)
returns (uint256 expenses, uint256 income)
{
TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token];
expenses = tokenStatement.expenses;
income = tokenStatement.income;
}
/**
* @dev We have to check for initialization as periods are only valid after initializing
*/
function currentPeriodId() public view isInitialized returns (uint64) {
return _currentPeriodId();
}
/**
* @dev We have to check for initialization as periods are only valid after initializing
*/
function getPeriodDuration() public view isInitialized returns (uint64) {
return settings.periodDuration;
}
/**
* @dev We have to check for initialization as budgets are only valid after initializing
*/
function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) {
budget = settings.budgets[_token];
hasBudget = settings.hasBudget[_token];
}
/**
* @dev We have to check for initialization as budgets are only valid after initializing
*/
function getRemainingBudget(address _token) public view isInitialized returns (uint256) {
return _getRemainingBudget(_token);
}
/**
* @dev We have to check for initialization as budgets are only valid after initializing
*/
function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) {
return _canMakePayment(_token, _amount);
}
/**
* @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new
* scheduled payments can only be created via `newScheduledPayment(),` which requires initialization
*/
function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) {
return _nextPaymentTime(_paymentId);
}
// Internal fns
function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal {
_recordIncomingTransaction(
_token,
_sender,
_amount,
_reference
);
if (_token == ETH) {
vault.deposit.value(_amount)(ETH, _amount);
} else {
// First, transfer the tokens to Finance if necessary
// External deposit will be false when the assets were already in the Finance app
// and just need to be transferred to the Vault
if (_isExternalDeposit) {
// This assumes the sender has approved the tokens for Finance
require(
ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount),
ERROR_TOKEN_TRANSFER_FROM_REVERTED
);
}
// Approve the tokens for the Vault (it does the actual transferring)
require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED);
// Finally, initiate the deposit
vault.deposit(_token, _amount);
}
}
function _executePayment(uint256 _paymentId) internal returns (uint256) {
ScheduledPayment storage payment = scheduledPayments[_paymentId];
require(!payment.inactive, ERROR_PAYMENT_INACTIVE);
uint64 paid = 0;
while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) {
if (!_canMakePayment(payment.token, payment.amount)) {
emit PaymentFailure(_paymentId);
break;
}
// The while() predicate prevents these two from ever overflowing
payment.executions += 1;
paid += 1;
// We've already checked the remaining budget with `_canMakePayment()`
_unsafeMakePaymentTransaction(
payment.token,
payment.receiver,
payment.amount,
_paymentId,
payment.executions,
""
);
}
return paid;
}
function _executePaymentAtLeastOnce(uint256 _paymentId) internal {
uint256 paid = _executePayment(_paymentId);
if (paid == 0) {
if (_nextPaymentTime(_paymentId) <= getTimestamp64()) {
revert(ERROR_EXECUTE_PAYMENT_NUM);
} else {
revert(ERROR_EXECUTE_PAYMENT_TIME);
}
}
}
function _makePaymentTransaction(
address _token,
address _receiver,
uint256 _amount,
uint256 _paymentId,
uint64 _paymentExecutionNumber,
string _reference
)
internal
{
require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET);
_unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference);
}
/**
* @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the
* remaining budget
*/
function _unsafeMakePaymentTransaction(
address _token,
address _receiver,
uint256 _amount,
uint256 _paymentId,
uint64 _paymentExecutionNumber,
string _reference
)
internal
{
_recordTransaction(
false,
_token,
_receiver,
_amount,
_paymentId,
_paymentExecutionNumber,
_reference
);
vault.transfer(_token, _receiver, _amount);
}
function _newPeriod(uint64 _startTime) internal returns (Period storage) {
// There should be no way for this to overflow since each period is at least one day
uint64 newPeriodId = periodsLength++;
Period storage period = periods[newPeriodId];
period.startTime = _startTime;
// Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime
// to MAX_UINT64 (let's assume that's the end of time for now).
uint64 endTime = _startTime + settings.periodDuration - 1;
if (endTime < _startTime) { // overflowed
endTime = MAX_UINT64;
}
period.endTime = endTime;
emit NewPeriod(newPeriodId, period.startTime, period.endTime);
return period;
}
function _recordIncomingTransaction(
address _token,
address _sender,
uint256 _amount,
string _reference
)
internal
{
_recordTransaction(
true, // incoming transaction
_token,
_sender,
_amount,
NO_SCHEDULED_PAYMENT, // unrelated to any existing payment
0, // and no payment executions
_reference
);
}
function _recordTransaction(
bool _incoming,
address _token,
address _entity,
uint256 _amount,
uint256 _paymentId,
uint64 _paymentExecutionNumber,
string _reference
)
internal
{
uint64 periodId = _currentPeriodId();
TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token];
if (_incoming) {
tokenStatement.income = tokenStatement.income.add(_amount);
} else {
tokenStatement.expenses = tokenStatement.expenses.add(_amount);
}
uint256 transactionId = transactionsNextIndex++;
Transaction storage transaction = transactions[transactionId];
transaction.token = _token;
transaction.entity = _entity;
transaction.isIncoming = _incoming;
transaction.amount = _amount;
transaction.paymentId = _paymentId;
transaction.paymentExecutionNumber = _paymentExecutionNumber;
transaction.date = getTimestamp64();
transaction.periodId = periodId;
Period storage period = periods[periodId];
if (period.firstTransactionId == NO_TRANSACTION) {
period.firstTransactionId = transactionId;
}
emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference);
}
function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) {
Period storage currentPeriod = periods[_currentPeriodId()];
uint64 timestamp = getTimestamp64();
// Transition periods if necessary
while (timestamp > currentPeriod.endTime) {
if (_maxTransitions == 0) {
// Required number of transitions is over allowed number, return false indicating
// it didn't fully transition
return false;
}
// We're already protected from underflowing above
_maxTransitions -= 1;
// If there were any transactions in period, record which was the last
// In case 0 transactions occured, first and last tx id will be 0
if (currentPeriod.firstTransactionId != NO_TRANSACTION) {
currentPeriod.lastTransactionId = transactionsNextIndex.sub(1);
}
// New period starts at end time + 1
currentPeriod = _newPeriod(currentPeriod.endTime.add(1));
}
return true;
}
function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) {
return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount;
}
function _currentPeriodId() internal view returns (uint64) {
// There is no way for this to overflow if protected by an initialization check
return periodsLength - 1;
}
function _getRemainingBudget(address _token) internal view returns (uint256) {
if (!settings.hasBudget[_token]) {
return MAX_UINT256;
}
uint256 budget = settings.budgets[_token];
uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses;
// A budget decrease can cause the spent amount to be greater than period budget
// If so, return 0 to not allow more spending during period
if (spent >= budget) {
return 0;
}
// We're already protected from the overflow above
return budget - spent;
}
function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) {
ScheduledPayment storage payment = scheduledPayments[_paymentId];
if (payment.executions >= payment.maxExecutions) {
return MAX_UINT64; // re-executes in some billions of years time... should not need to worry
}
// Split in multiple lines to circumvent linter warning
uint64 increase = payment.executions.mul(payment.interval);
uint64 nextPayment = payment.initialPaymentTime.add(increase);
return nextPayment;
}
// Syntax sugar
function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) {
r = new uint256[](6);
r[0] = uint256(_a);
r[1] = uint256(_b);
r[2] = _c;
r[3] = _d;
r[4] = _e;
r[5] = _f;
}
// Mocked fns (overrided during testing)
// Must be view for mocking purposes
function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; }
}
// File: @aragon/apps-payroll/contracts/Payroll.sol
pragma solidity 0.4.24;
/**
* @title Payroll in multiple currencies
*/
contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
/* Hardcoded constants to save gas
* bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE");
* bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE");
* bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE");
* bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE");
* bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE");
* bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE");
* bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE");
* bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE");
*/
bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e;
bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242;
bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d;
bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae;
bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16;
bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06;
bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302;
bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e;
uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()`
uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout
uint256 internal constant MAX_UINT256 = uint256(-1);
uint64 internal constant MAX_UINT64 = uint64(-1);
string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST";
string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE";
string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH";
string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT";
string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET";
string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS";
string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH";
string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH";
string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN";
string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL";
string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE";
string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID";
string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD";
string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS";
string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST";
string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT";
string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT";
string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE";
string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW";
string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG";
string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT";
enum PaymentType { Payroll, Reimbursement, Bonus }
struct Employee {
address accountAddress; // unique, but can be changed over time
uint256 denominationTokenSalary; // salary per second in denomination Token
uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries
uint256 bonus;
uint256 reimbursements;
uint64 lastPayroll;
uint64 endDate;
address[] allocationTokenAddresses;
mapping(address => uint256) allocationTokens;
}
Finance public finance;
address public denominationToken;
IFeed public feed;
uint64 public rateExpiryTime;
// Employees start at index 1, to allow us to use employees[0] to check for non-existent employees
uint256 public nextEmployee;
mapping(uint256 => Employee) internal employees; // employee ID -> employee
mapping(address => uint256) internal employeeIds; // employee address -> employee ID
mapping(address => bool) internal allowedTokens;
event AddEmployee(
uint256 indexed employeeId,
address indexed accountAddress,
uint256 initialDenominationSalary,
uint64 startDate,
string role
);
event TerminateEmployee(uint256 indexed employeeId, uint64 endDate);
event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary);
event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount);
event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount);
event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount);
event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress);
event DetermineAllocation(uint256 indexed employeeId);
event SendPayment(
uint256 indexed employeeId,
address indexed accountAddress,
address indexed token,
uint256 amount,
uint256 exchangeRate,
string paymentReference
);
event SetAllowedToken(address indexed token, bool allowed);
event SetPriceFeed(address indexed feed);
event SetRateExpiryTime(uint64 time);
// Check employee exists by ID
modifier employeeIdExists(uint256 _employeeId) {
require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST);
_;
}
// Check employee exists and is still active
modifier employeeActive(uint256 _employeeId) {
// No need to check for existence as _isEmployeeIdActive() is false for non-existent employees
require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE);
_;
}
// Check sender matches an existing employee
modifier employeeMatches {
require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH);
_;
}
/**
* @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)`
* @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake"
* address used by the price feed to denominate fiat currencies
* @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable)
* @param _denominationToken Address of the denomination token used for salary accounting
* @param _priceFeed Address of the price feed
* @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates
*/
function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit {
initialized();
require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT);
finance = _finance;
denominationToken = _denominationToken;
_setPriceFeed(_priceFeed);
_setRateExpiryTime(_rateExpiryTime);
// Employees start at index 1, to allow us to use employees[0] to check for non-existent employees
nextEmployee = 1;
}
/**
* @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens
* @param _token Address of the token to be added or removed from the list of allowed tokens for payments
* @param _allowed Boolean to tell whether the given token should be added or removed from the list
*/
function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) {
require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET);
allowedTokens[_token] = _allowed;
emit SetAllowedToken(_token, _allowed);
}
/**
* @notice Set the price feed for exchange rates to `_feed`
* @param _feed Address of the new price feed instance
*/
function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) {
_setPriceFeed(_feed);
}
/**
* @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)`
* @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert
* @param _time The expiration time in seconds for exchange rates
*/
function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) {
_setRateExpiryTime(_time);
}
/**
* @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)`
* @param _accountAddress Employee's address to receive payroll
* @param _initialDenominationSalary Employee's salary, per second in denomination token
* @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value)
* @param _role Employee's role
*/
function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role)
external
authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate)))
{
_addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role);
}
/**
* @notice Add `_amount` to bonus for employee #`_employeeId`
* @param _employeeId Employee's identifier
* @param _amount Amount to be added to the employee's bonuses in denomination token
*/
function addBonus(uint256 _employeeId, uint256 _amount)
external
authP(ADD_BONUS_ROLE, arr(_employeeId, _amount))
employeeActive(_employeeId)
{
_addBonus(_employeeId, _amount);
}
/**
* @notice Add `_amount` to reimbursements for employee #`_employeeId`
* @param _employeeId Employee's identifier
* @param _amount Amount to be added to the employee's reimbursements in denomination token
*/
function addReimbursement(uint256 _employeeId, uint256 _amount)
external
authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount))
employeeActive(_employeeId)
{
_addReimbursement(_employeeId, _amount);
}
/**
* @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second
* @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid
* losing any accrued salary for an employee due to the employer changing their salary.
* @param _employeeId Employee's identifier
* @param _denominationSalary Employee's new salary, per second in denomination token
*/
function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary)
external
authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary))
employeeActive(_employeeId)
{
Employee storage employee = employees[_employeeId];
// Accrue employee's owed salary; don't cap to revert on overflow
uint256 owed = _getOwedSalarySinceLastPayroll(employee, false);
_addAccruedSalary(_employeeId, owed);
// Update employee to track the new salary and payment date
employee.lastPayroll = getTimestamp64();
employee.denominationTokenSalary = _denominationSalary;
emit SetEmployeeSalary(_employeeId, _denominationSalary);
}
/**
* @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)`
* @param _employeeId Employee's identifier
* @param _endDate Termination timestamp in seconds
*/
function terminateEmployee(uint256 _employeeId, uint64 _endDate)
external
authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate)))
employeeActive(_employeeId)
{
_terminateEmployee(_employeeId, _endDate);
}
/**
* @notice Change your employee account address to `_newAccountAddress`
* @dev Initialization check is implicitly provided by `employeeMatches` as new employees can
* only be added via `addEmployee(),` which requires initialization.
* As the employee is allowed to call this, we enforce non-reentrancy.
* @param _newAccountAddress New address to receive payments for the requesting employee
*/
function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant {
uint256 employeeId = employeeIds[msg.sender];
address oldAddress = employees[employeeId].accountAddress;
_setEmployeeAddress(employeeId, _newAccountAddress);
// Don't delete the old address until after setting the new address to check that the
// employee specified a new address
delete employeeIds[oldAddress];
emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress);
}
/**
* @notice Set the token distribution for your payments
* @dev Initialization check is implicitly provided by `employeeMatches` as new employees can
* only be added via `addEmployee(),` which requires initialization.
* As the employee is allowed to call this, we enforce non-reentrancy.
* @param _tokens Array of token addresses; they must belong to the list of allowed tokens
* @param _distribution Array with each token's corresponding proportions (must be integers summing to 100)
*/
function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant {
// Check array lengthes match
require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS);
require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH);
uint256 employeeId = employeeIds[msg.sender];
Employee storage employee = employees[employeeId];
// Delete previous token allocations
address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses;
for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) {
delete employee.allocationTokens[previousAllowedTokenAddresses[j]];
}
delete employee.allocationTokenAddresses;
// Set distributions only if given tokens are allowed
for (uint256 i = 0; i < _tokens.length; i++) {
employee.allocationTokenAddresses.push(_tokens[i]);
employee.allocationTokens[_tokens[i]] = _distribution[i];
}
_ensureEmployeeTokenAllocationsIsValid(employee);
emit DetermineAllocation(employeeId);
}
/**
* @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'`
* @dev Reverts if no payments were made.
* Initialization check is implicitly provided by `employeeMatches` as new employees can
* only be added via `addEmployee(),` which requires initialization.
* As the employee is allowed to call this, we enforce non-reentrancy.
* @param _type Payment type being requested (Payroll, Reimbursement or Bonus)
* @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all.
* @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens
*/
function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant {
uint256 paymentAmount;
uint256 employeeId = employeeIds[msg.sender];
Employee storage employee = employees[employeeId];
_ensureEmployeeTokenAllocationsIsValid(employee);
require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH);
// Do internal employee accounting
if (_type == PaymentType.Payroll) {
// Salary is capped here to avoid reverting at this point if it becomes too big
// (so employees aren't DDOSed if their salaries get too large)
// If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly
uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee);
paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount);
_updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount);
} else if (_type == PaymentType.Reimbursement) {
uint256 owedReimbursements = employee.reimbursements;
paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount);
employee.reimbursements = owedReimbursements.sub(paymentAmount);
} else if (_type == PaymentType.Bonus) {
uint256 owedBonusAmount = employee.bonus;
paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount);
employee.bonus = owedBonusAmount.sub(paymentAmount);
} else {
revert(ERROR_INVALID_PAYMENT_TYPE);
}
// Actually transfer the owed funds
require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID);
_removeEmployeeIfTerminatedAndPaidOut(employeeId);
}
// Forwarding fns
/**
* @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not.
* @return Always true
*/
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Execute desired action as an active employee
* @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app.
* @param _evmScript Script being executed
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
bytes memory input = new bytes(0); // TODO: Consider input for this
// Add the Finance app to the blacklist to disallow employees from executing actions on the
// Finance app from Payroll's context (since Payroll requires permissions on Finance)
address[] memory blacklist = new address[](1);
blacklist[0] = address(finance);
runScript(_evmScript, input, blacklist);
}
/**
* @dev IForwarder interface conformance. Tells whether a given address can forward actions or not.
* @param _sender Address of the account intending to forward an action
* @return True if the given address is an active employee, false otherwise
*/
function canForward(address _sender, bytes) public view returns (bool) {
return _isEmployeeIdActive(employeeIds[_sender]);
}
// Getter fns
/**
* @dev Return employee's identifier by their account address
* @param _accountAddress Employee's address to receive payments
* @return Employee's identifier
*/
function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) {
require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST);
return employeeIds[_accountAddress];
}
/**
* @dev Return all information for employee by their ID
* @param _employeeId Employee's identifier
* @return Employee's address to receive payments
* @return Employee's salary, per second in denomination token
* @return Employee's accrued salary
* @return Employee's bonus amount
* @return Employee's reimbursements amount
* @return Employee's last payment date
* @return Employee's termination date (max uint64 if none)
* @return Employee's allowed payment tokens
*/
function getEmployee(uint256 _employeeId)
public
view
employeeIdExists(_employeeId)
returns (
address accountAddress,
uint256 denominationSalary,
uint256 accruedSalary,
uint256 bonus,
uint256 reimbursements,
uint64 lastPayroll,
uint64 endDate,
address[] allocationTokens
)
{
Employee storage employee = employees[_employeeId];
accountAddress = employee.accountAddress;
denominationSalary = employee.denominationTokenSalary;
accruedSalary = employee.accruedSalary;
bonus = employee.bonus;
reimbursements = employee.reimbursements;
lastPayroll = employee.lastPayroll;
endDate = employee.endDate;
allocationTokens = employee.allocationTokenAddresses;
}
/**
* @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well.
* The result will be capped to max uint256 to avoid having an overflow.
* @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary.
*/
function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) {
return _getTotalOwedCappedSalary(employees[_employeeId]);
}
/**
* @dev Get an employee's payment allocation for a token
* @param _employeeId Employee's identifier
* @param _token Token to query the payment allocation for
* @return Employee's payment allocation for the token being queried
*/
function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) {
return employees[_employeeId].allocationTokens[_token];
}
/**
* @dev Check if a token is allowed to be used for payments
* @param _token Address of the token to be checked
* @return True if the given token is allowed, false otherwise
*/
function isTokenAllowed(address _token) public view isInitialized returns (bool) {
return allowedTokens[_token];
}
// Internal fns
/**
* @dev Set the price feed used for exchange rates
* @param _feed Address of the new price feed instance
*/
function _setPriceFeed(IFeed _feed) internal {
require(isContract(_feed), ERROR_FEED_NOT_CONTRACT);
feed = _feed;
emit SetPriceFeed(feed);
}
/**
* @dev Set the exchange rate expiry time in seconds.
* Exchange rates older than the given value won't be accepted for payments and will cause
* payouts to revert.
* @param _time The expiration time in seconds for exchange rates
*/
function _setRateExpiryTime(uint64 _time) internal {
// Require a sane minimum for the rate expiry time
require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT);
rateExpiryTime = _time;
emit SetRateExpiryTime(rateExpiryTime);
}
/**
* @dev Add a new employee to Payroll
* @param _accountAddress Employee's address to receive payroll
* @param _initialDenominationSalary Employee's salary, per second in denomination token
* @param _startDate Employee's starting timestamp in seconds
* @param _role Employee's role
*/
function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal {
uint256 employeeId = nextEmployee++;
_setEmployeeAddress(employeeId, _accountAddress);
Employee storage employee = employees[employeeId];
employee.denominationTokenSalary = _initialDenominationSalary;
employee.lastPayroll = _startDate;
employee.endDate = MAX_UINT64;
emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role);
}
/**
* @dev Add amount to an employee's bonuses
* @param _employeeId Employee's identifier
* @param _amount Amount be added to the employee's bonuses in denomination token
*/
function _addBonus(uint256 _employeeId, uint256 _amount) internal {
Employee storage employee = employees[_employeeId];
employee.bonus = employee.bonus.add(_amount);
emit AddEmployeeBonus(_employeeId, _amount);
}
/**
* @dev Add amount to an employee's reimbursements
* @param _employeeId Employee's identifier
* @param _amount Amount be added to the employee's reimbursements in denomination token
*/
function _addReimbursement(uint256 _employeeId, uint256 _amount) internal {
Employee storage employee = employees[_employeeId];
employee.reimbursements = employee.reimbursements.add(_amount);
emit AddEmployeeReimbursement(_employeeId, _amount);
}
/**
* @dev Add amount to an employee's accrued salary
* @param _employeeId Employee's identifier
* @param _amount Amount be added to the employee's accrued salary in denomination token
*/
function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal {
Employee storage employee = employees[_employeeId];
employee.accruedSalary = employee.accruedSalary.add(_amount);
emit AddEmployeeAccruedSalary(_employeeId, _amount);
}
/**
* @dev Set an employee's account address
* @param _employeeId Employee's identifier
* @param _accountAddress Employee's address to receive payroll
*/
function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal {
// Check address is non-null
require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS);
// Check address isn't already being used
require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST);
employees[_employeeId].accountAddress = _accountAddress;
// Create IDs mapping
employeeIds[_accountAddress] = _employeeId;
}
/**
* @dev Terminate employee on end date
* @param _employeeId Employee's identifier
* @param _endDate Termination timestamp in seconds
*/
function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal {
// Prevent past termination dates
require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE);
employees[_employeeId].endDate = _endDate;
emit TerminateEmployee(_employeeId, _endDate);
}
/**
* @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation
* @param _employeeId Employee's identifier
* @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation.
* @param _type Payment type being transferred (Payroll, Reimbursement or Bonus)
* @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens
* @return True if there was at least one token transfer
*/
function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) {
if (_totalAmount == 0) {
return false;
}
Employee storage employee = employees[_employeeId];
address employeeAddress = employee.accountAddress;
string memory paymentReference = _paymentReferenceFor(_type);
address[] storage allocationTokenAddresses = employee.allocationTokenAddresses;
for (uint256 i = 0; i < allocationTokenAddresses.length; i++) {
address token = allocationTokenAddresses[i];
uint256 tokenAllocation = employee.allocationTokens[token];
if (tokenAllocation != uint256(0)) {
// Get the exchange rate for the payout token in denomination token,
// as we do accounting in denomination tokens
uint256 exchangeRate = _getExchangeRateInDenominationToken(token);
require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW);
// Convert amount (in denomination tokens) to payout token and apply allocation
uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation);
// Divide by 100 for the allocation percentage and by the exchange rate precision
tokenAmount = tokenAmount.div(100).div(feed.ratePrecision());
// Finance reverts if the payment wasn't possible
finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference);
emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference);
somethingPaid = true;
}
}
}
/**
* @dev Remove employee if there are no owed funds and employee's end date has been reached
* @param _employeeId Employee's identifier
*/
function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal {
Employee storage employee = employees[_employeeId];
if (
employee.lastPayroll == employee.endDate &&
(employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0)
) {
delete employeeIds[employee.accountAddress];
delete employees[_employeeId];
}
}
/**
* @dev Updates the accrued salary and payroll date of an employee based on a payment amount and
* their currently owed salary since last payroll date
* @param _employee Employee struct in storage
* @param _paymentAmount Amount being paid to the employee
*/
function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal {
uint256 accruedSalary = _employee.accruedSalary;
if (_paymentAmount <= accruedSalary) {
// Employee is only cashing out some previously owed salary so we don't need to update
// their last payroll date
// No need to use SafeMath as we already know _paymentAmount <= accruedSalary
_employee.accruedSalary = accruedSalary - _paymentAmount;
return;
}
// Employee is cashing out some of their currently owed salary so their last payroll date
// needs to be modified based on the amount of salary paid
uint256 currentSalaryPaid = _paymentAmount;
if (accruedSalary > 0) {
// Employee is cashing out a mixed amount between previous and current owed salaries;
// first use up their accrued salary
// No need to use SafeMath here as we already know _paymentAmount > accruedSalary
currentSalaryPaid = _paymentAmount - accruedSalary;
// We finally need to clear their accrued salary
_employee.accruedSalary = 0;
}
uint256 salary = _employee.denominationTokenSalary;
uint256 timeDiff = currentSalaryPaid.div(salary);
// If they're being paid an amount that doesn't match perfectly with the adjusted time
// (up to a seconds' worth of salary), add the second and put the extra remaining salary
// into their accrued salary
uint256 extraSalary = currentSalaryPaid % salary;
if (extraSalary > 0) {
timeDiff = timeDiff.add(1);
_employee.accruedSalary = salary - extraSalary;
}
uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff);
// Even though this function should never receive a currentSalaryPaid value that would
// result in the lastPayrollDate being higher than the current time,
// let's double check to be safe
require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG);
// Already know lastPayrollDate must fit in uint64 from above
_employee.lastPayroll = uint64(lastPayrollDate);
}
/**
* @dev Tell whether an employee is registered in this Payroll or not
* @param _employeeId Employee's identifier
* @return True if the given employee ID belongs to an registered employee, false otherwise
*/
function _employeeExists(uint256 _employeeId) internal view returns (bool) {
return employees[_employeeId].accountAddress != address(0);
}
/**
* @dev Tell whether an employee has a valid token allocation or not.
* A valid allocation is one that sums to 100 and only includes allowed tokens.
* @param _employee Employee struct in storage
* @return Reverts if employee's allocation is invalid
*/
function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view {
uint256 sum = 0;
address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses;
for (uint256 i = 0; i < allocationTokenAddresses.length; i++) {
address token = allocationTokenAddresses[i];
require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN);
sum = sum.add(_employee.allocationTokens[token]);
}
require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL);
}
/**
* @dev Tell whether an employee is still active or not
* @param _employee Employee struct in storage
* @return True if the employee exists and has an end date that has not been reached yet, false otherwise
*/
function _isEmployeeActive(Employee storage _employee) internal view returns (bool) {
return _employee.endDate >= getTimestamp64();
}
/**
* @dev Tell whether an employee id is still active or not
* @param _employeeId Employee's identifier
* @return True if the employee exists and has an end date that has not been reached yet, false otherwise
*/
function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) {
return _isEmployeeActive(employees[_employeeId]);
}
/**
* @dev Get exchange rate for a token based on the denomination token.
* As an example, if the denomination token was USD and ETH's price was 100USD,
* this would return 0.01 * precision rate for ETH.
* @param _token Token to get price of in denomination tokens
* @return Exchange rate (multiplied by the PPF rate precision)
*/
function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) {
// xrt is the number of `_token` that can be exchanged for one `denominationToken`
(uint128 xrt, uint64 when) = feed.get(
denominationToken, // Base (e.g. USD)
_token // Quote (e.g. ETH)
);
// Check the price feed is recent enough
if (getTimestamp64().sub(when) >= rateExpiryTime) {
return 0;
}
return uint256(xrt);
}
/**
* @dev Get owed salary since last payroll for an employee
* @param _employee Employee struct in storage
* @param _capped Safely cap the owed salary at max uint
* @return Owed salary in denomination tokens since last payroll for the employee.
* If _capped is false, it reverts in case of an overflow.
*/
function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) {
uint256 timeDiff = _getOwedPayrollPeriod(_employee);
if (timeDiff == 0) {
return 0;
}
uint256 salary = _employee.denominationTokenSalary;
if (_capped) {
// Return max uint if the result overflows
uint256 result = salary * timeDiff;
return (result / timeDiff != salary) ? MAX_UINT256 : result;
} else {
return salary.mul(timeDiff);
}
}
/**
* @dev Get owed payroll period for an employee
* @param _employee Employee struct in storage
* @return Owed time in seconds since the employee's last payroll date
*/
function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) {
// Get the min of current date and termination date
uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate;
// Make sure we don't revert if we try to get the owed salary for an employee whose last
// payroll date is now or in the future
// This can happen either by adding new employees with start dates in the future, to allow
// us to change their salary before their start date, or by terminating an employee and
// paying out their full owed salary
if (date <= _employee.lastPayroll) {
return 0;
}
// Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check
return uint256(date - _employee.lastPayroll);
}
/**
* @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well.
* The result will be capped to max uint256 to avoid having an overflow.
* @param _employee Employee struct in storage
* @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary.
*/
function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) {
uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount
uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary;
if (totalOwedSalary < currentOwedSalary) {
totalOwedSalary = MAX_UINT256;
}
return totalOwedSalary;
}
/**
* @dev Get payment reference for a given payment type
* @param _type Payment type to query the reference of
* @return Payment reference for the given payment type
*/
function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) {
if (_type == PaymentType.Payroll) {
return "Employee salary";
} else if (_type == PaymentType.Reimbursement) {
return "Employee reimbursement";
} if (_type == PaymentType.Bonus) {
return "Employee bonus";
}
revert(ERROR_INVALID_PAYMENT_TYPE);
}
function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) {
require(_owedAmount > 0, ERROR_NOTHING_PAID);
require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT);
return _requestedAmount > 0 ? _requestedAmount : _owedAmount;
}
}
// File: @aragon/apps-token-manager/contracts/TokenManager.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
/* solium-disable function-order */
pragma solidity 0.4.24;
contract TokenManager is ITokenController, IForwarder, AragonApp {
using SafeMath for uint256;
bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE");
bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE");
bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE");
bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE");
bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE");
uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50;
string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN";
string private constant ERROR_NO_VESTING = "TM_NO_VESTING";
string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER";
string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM";
string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM";
string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS";
string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE";
string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE";
string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED";
string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD";
string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED";
string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED";
struct TokenVesting {
uint256 amount;
uint64 start;
uint64 cliff;
uint64 vesting;
bool revokable;
}
// Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract
MiniMeToken public token;
uint256 public maxAccountTokens;
// We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful
mapping (address => mapping (uint256 => TokenVesting)) internal vestings;
mapping (address => uint256) public vestingsLengths;
// Other token specific events can be watched on the token address directly (avoids duplication)
event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount);
event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount);
modifier onlyToken() {
require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN);
_;
}
modifier vestingExists(address _holder, uint256 _vestingId) {
// TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function
require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING);
_;
}
/**
* @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''`
* @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller)
* @param _transferable whether the token can be transferred by holders
* @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens)
*/
function initialize(
MiniMeToken _token,
bool _transferable,
uint256 _maxAccountTokens
)
external
onlyInit
{
initialized();
require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER);
token = _token;
maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens;
if (token.transfersEnabled() != _transferable) {
token.enableTransfers(_transferable);
}
}
/**
* @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver`
* @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead)
* @param _amount Number of tokens minted
*/
function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) {
require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM);
_mint(_receiver, _amount);
}
/**
* @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager
* @param _amount Number of tokens minted
*/
function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) {
_mint(address(this), _amount);
}
/**
* @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings
* @param _receiver The address receiving the tokens
* @param _amount Number of tokens transferred
*/
function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) {
_assign(_receiver, _amount);
}
/**
* @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder`
* @param _holder Holder of tokens being burned
* @param _amount Number of tokens being burned
*/
function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) {
// minime.destroyTokens() never returns false, only reverts on failure
token.destroyTokens(_holder, _amount);
}
/**
* @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable)
* @param _receiver The address receiving the tokens, cannot be Token Manager itself
* @param _amount Number of tokens vested
* @param _start Date the vesting calculations start
* @param _cliff Date when the initial portion of tokens are transferable
* @param _vested Date when all tokens are transferable
* @param _revokable Whether the vesting can be revoked by the Token Manager
*/
function assignVested(
address _receiver,
uint256 _amount,
uint64 _start,
uint64 _cliff,
uint64 _vested,
bool _revokable
)
external
authP(ASSIGN_ROLE, arr(_receiver, _amount))
returns (uint256)
{
require(_receiver != address(this), ERROR_VESTING_TO_TM);
require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS);
require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE);
uint256 vestingId = vestingsLengths[_receiver]++;
vestings[_receiver][vestingId] = TokenVesting(
_amount,
_start,
_cliff,
_vested,
_revokable
);
_assign(_receiver, _amount);
emit NewVesting(_receiver, vestingId, _amount);
return vestingId;
}
/**
* @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager
* @param _holder Address whose vesting to revoke
* @param _vestingId Numeric id of the vesting
*/
function revokeVesting(address _holder, uint256 _vestingId)
external
authP(REVOKE_VESTINGS_ROLE, arr(_holder))
vestingExists(_holder, _vestingId)
{
TokenVesting storage v = vestings[_holder][_vestingId];
require(v.revokable, ERROR_VESTING_NOT_REVOKABLE);
uint256 nonVested = _calculateNonVestedTokens(
v.amount,
getTimestamp(),
v.start,
v.cliff,
v.vesting
);
// To make vestingIds immutable over time, we just zero out the revoked vesting
// Clearing this out also allows the token transfer back to the Token Manager to succeed
delete vestings[_holder][_vestingId];
// transferFrom always works as controller
// onTransfer hook always allows if transfering to token controller
require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED);
emit RevokeVesting(_holder, _vestingId, nonVested);
}
// ITokenController fns
// `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token
// contract and are only meant to be called through the managed MiniMe token that gets assigned
// during initialization.
/*
* @dev Notifies the controller about a token transfer allowing the controller to decide whether
* to allow it or react if desired (only callable from the token).
* Initialization check is implicitly provided by `onlyToken()`.
* @param _from The origin of the transfer
* @param _to The destination of the transfer
* @param _amount The amount of the transfer
* @return False if the controller does not authorize the transfer
*/
function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) {
return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount;
}
/**
* @dev Notifies the controller about an approval allowing the controller to react if desired
* Initialization check is implicitly provided by `onlyToken()`.
* @return False if the controller does not authorize the approval
*/
function onApprove(address, address, uint) external onlyToken returns (bool) {
return true;
}
/**
* @dev Called when ether is sent to the MiniMe Token contract
* Initialization check is implicitly provided by `onlyToken()`.
* @return True if the ether is accepted, false for it to throw
*/
function proxyPayment(address) external payable onlyToken returns (bool) {
return false;
}
// Forwarding fns
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Execute desired action as a token holder
* @dev IForwarder interface conformance. Forwards any token holder action.
* @param _evmScript Script being executed
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
bytes memory input = new bytes(0); // TODO: Consider input for this
// Add the managed token to the blacklist to disallow a token holder from executing actions
// on the token controller's (this contract) behalf
address[] memory blacklist = new address[](1);
blacklist[0] = address(token);
runScript(_evmScript, input, blacklist);
}
function canForward(address _sender, bytes) public view returns (bool) {
return hasInitialized() && token.balanceOf(_sender) > 0;
}
// Getter fns
function getVesting(
address _recipient,
uint256 _vestingId
)
public
view
vestingExists(_recipient, _vestingId)
returns (
uint256 amount,
uint64 start,
uint64 cliff,
uint64 vesting,
bool revokable
)
{
TokenVesting storage tokenVesting = vestings[_recipient][_vestingId];
amount = tokenVesting.amount;
start = tokenVesting.start;
cliff = tokenVesting.cliff;
vesting = tokenVesting.vesting;
revokable = tokenVesting.revokable;
}
function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) {
return _transferableBalance(_holder, getTimestamp());
}
function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) {
return _transferableBalance(_holder, _time);
}
/**
* @dev Disable recovery escape hatch for own token,
* as the it has the concept of issuing tokens without assigning them
*/
function allowRecoverability(address _token) public view returns (bool) {
return _token != address(token);
}
// Internal fns
function _assign(address _receiver, uint256 _amount) internal {
require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED);
// Must use transferFrom() as transfer() does not give the token controller full control
require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED);
}
function _mint(address _receiver, uint256 _amount) internal {
require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED);
token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false
}
function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) {
// Max balance doesn't apply to the token manager itself
if (_receiver == address(this)) {
return true;
}
return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens;
}
/**
* @dev Calculate amount of non-vested tokens at a specifc time
* @param tokens The total amount of tokens vested
* @param time The time at which to check
* @param start The date vesting started
* @param cliff The cliff period
* @param vested The fully vested date
* @return The amount of non-vested tokens of a specific grant
* transferableTokens
* | _/-------- vestedTokens rect
* | _/
* | _/
* | _/
* | _/
* | /
* | .|
* | . |
* | . |
* | . |
* | . |
* | . |
* +===+===========+---------+----------> time
* Start Cliff Vested
*/
function _calculateNonVestedTokens(
uint256 tokens,
uint256 time,
uint256 start,
uint256 cliff,
uint256 vested
)
private
pure
returns (uint256)
{
// Shortcuts for before cliff and after vested cases.
if (time >= vested) {
return 0;
}
if (time < cliff) {
return tokens;
}
// Interpolate all vested tokens.
// As before cliff the shortcut returns 0, we can just calculate a value
// in the vesting rect (as shown in above's figure)
// vestedTokens = tokens * (time - start) / (vested - start)
// In assignVesting we enforce start <= cliff <= vested
// Here we shortcut time >= vested and time < cliff,
// so no division by 0 is possible
uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start);
// tokens - vestedTokens
return tokens.sub(vestedTokens);
}
function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) {
uint256 transferable = token.balanceOf(_holder);
// This check is not strictly necessary for the current version of this contract, as
// Token Managers now cannot assign vestings to themselves.
// However, this was a possibility in the past, so in case there were vestings assigned to
// themselves, this will still return the correct value (entire balance, as the Token
// Manager does not have a spending limit on its own balance).
if (_holder != address(this)) {
uint256 vestingsCount = vestingsLengths[_holder];
for (uint256 i = 0; i < vestingsCount; i++) {
TokenVesting storage v = vestings[_holder][i];
uint256 nonTransferable = _calculateNonVestedTokens(
v.amount,
_time,
v.start,
v.cliff,
v.vesting
);
transferable = transferable.sub(nonTransferable);
}
}
return transferable;
}
}
// File: @aragon/apps-survey/contracts/Survey.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Survey is AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE");
bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE");
uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18
uint256 public constant ABSTAIN_VOTE = 0;
string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION";
string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY";
string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER";
string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE";
string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT";
string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION";
string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE";
string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED";
string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION";
struct OptionCast {
uint256 optionId;
uint256 stake;
}
/* Allows for multiple option votes.
* Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the
* contract.
*/
struct MultiOptionVote {
uint256 optionsCastedLength;
// `castedVotes` simulates an array
// Each OptionCast in `castedVotes` must be ordered by ascending option IDs
mapping (uint256 => OptionCast) castedVotes;
}
struct SurveyStruct {
uint64 startDate;
uint64 snapshotBlock;
uint64 minParticipationPct;
uint256 options;
uint256 votingPower; // total tokens that can cast a vote
uint256 participation; // tokens that casted a vote
// Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0
mapping (uint256 => uint256) optionPower; // option ID -> voting power for option
mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes
}
MiniMeToken public token;
uint64 public minParticipationPct;
uint64 public surveyTime;
// We are mimicing an array, we use a mapping instead to make app upgrade more graceful
mapping (uint256 => SurveyStruct) internal surveys;
uint256 public surveysLength;
event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata);
event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower);
event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower);
event ChangeMinParticipation(uint64 minParticipationPct);
modifier acceptableMinParticipationPct(uint64 _minParticipationPct) {
require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION);
_;
}
modifier surveyExists(uint256 _surveyId) {
require(_surveyId < surveysLength, ERROR_NO_SURVEY);
_;
}
/**
* @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)`
* @param _token MiniMeToken address that will be used as governance token
* @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%)
* @param _surveyTime Seconds that a survey will be open for token holders to vote
*/
function initialize(
MiniMeToken _token,
uint64 _minParticipationPct,
uint64 _surveyTime
)
external
onlyInit
acceptableMinParticipationPct(_minParticipationPct)
{
initialized();
token = _token;
minParticipationPct = _minParticipationPct;
surveyTime = _surveyTime;
}
/**
* @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`%
* @param _minParticipationPct New acceptance participation
*/
function changeMinAcceptParticipationPct(uint64 _minParticipationPct)
external
authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct)))
acceptableMinParticipationPct(_minParticipationPct)
{
minParticipationPct = _minParticipationPct;
emit ChangeMinParticipation(_minParticipationPct);
}
/**
* @notice Create a new non-binding survey about "`_metadata`"
* @param _metadata Survey metadata
* @param _options Number of options voters can decide between
* @return surveyId id for newly created survey
*/
function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) {
uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block
uint256 votingPower = token.totalSupplyAt(snapshotBlock);
require(votingPower > 0, ERROR_NO_VOTING_POWER);
surveyId = surveysLength++;
SurveyStruct storage survey = surveys[surveyId];
survey.startDate = getTimestamp64();
survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block
survey.minParticipationPct = minParticipationPct;
survey.options = _options;
survey.votingPower = votingPower;
emit StartSurvey(surveyId, msg.sender, _metadata);
}
/**
* @notice Reset previously casted vote in survey #`_surveyId`, if any.
* @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only
* be created via `newSurvey(),` which requires initialization
* @param _surveyId Id for survey
*/
function resetVote(uint256 _surveyId) external surveyExists(_surveyId) {
require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE);
_resetVote(_surveyId);
}
/**
* @notice Vote for multiple options in survey #`_surveyId`.
* @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only
* be created via `newSurvey(),` which requires initialization
* @param _surveyId Id for survey
* @param _optionIds Array with indexes of supported options
* @param _stakes Number of tokens assigned to each option
*/
function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes)
external
surveyExists(_surveyId)
{
require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT);
require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE);
_voteOptions(_surveyId, _optionIds, _stakes);
}
/**
* @notice Vote option #`_optionId` in survey #`_surveyId`.
* @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only
* be created via `newSurvey(),` which requires initialization
* @dev It will use the whole balance.
* @param _surveyId Id for survey
* @param _optionId Index of supported option
*/
function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) {
require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE);
SurveyStruct storage survey = surveys[_surveyId];
// This could re-enter, though we can asume the governance token is not maliciuous
uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock);
uint256[] memory options = new uint256[](1);
uint256[] memory stakes = new uint256[](1);
options[0] = _optionId;
stakes[0] = voterStake;
_voteOptions(_surveyId, options, stakes);
}
// Getter fns
function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) {
SurveyStruct storage survey = surveys[_surveyId];
return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0;
}
function getSurvey(uint256 _surveyId)
public
view
surveyExists(_surveyId)
returns (
bool open,
uint64 startDate,
uint64 snapshotBlock,
uint64 minParticipation,
uint256 votingPower,
uint256 participation,
uint256 options
)
{
SurveyStruct storage survey = surveys[_surveyId];
open = _isSurveyOpen(survey);
startDate = survey.startDate;
snapshotBlock = survey.snapshotBlock;
minParticipation = survey.minParticipationPct;
votingPower = survey.votingPower;
participation = survey.participation;
options = survey.options;
}
/**
* @dev This is not meant to be used on-chain
*/
/* solium-disable-next-line function-order */
function getVoterState(uint256 _surveyId, address _voter)
external
view
surveyExists(_surveyId)
returns (uint256[] options, uint256[] stakes)
{
MultiOptionVote storage vote = surveys[_surveyId].votes[_voter];
if (vote.optionsCastedLength == 0) {
return (new uint256[](0), new uint256[](0));
}
options = new uint256[](vote.optionsCastedLength + 1);
stakes = new uint256[](vote.optionsCastedLength + 1);
for (uint256 i = 0; i <= vote.optionsCastedLength; i++) {
options[i] = vote.castedVotes[i].optionId;
stakes[i] = vote.castedVotes[i].stake;
}
}
function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) {
SurveyStruct storage survey = surveys[_surveyId];
require(_optionId <= survey.options, ERROR_NO_OPTION);
return survey.optionPower[_optionId];
}
function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) {
SurveyStruct storage survey = surveys[_surveyId];
// votingPower is always > 0
uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower;
return participationPct >= survey.minParticipationPct;
}
// Internal fns
/*
* @dev Assumes the survey exists and that msg.sender can vote
*/
function _resetVote(uint256 _surveyId) internal {
SurveyStruct storage survey = surveys[_surveyId];
MultiOptionVote storage previousVote = survey.votes[msg.sender];
if (previousVote.optionsCastedLength > 0) {
// Voter removes their vote (index 0 is the abstain vote)
for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) {
OptionCast storage previousOptionCast = previousVote.castedVotes[i];
uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId];
uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake);
survey.optionPower[previousOptionCast.optionId] = currentOptionPower;
emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower);
}
// Compute previously casted votes (i.e. substract non-used tokens from stake)
uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock);
uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake);
// And remove it from total participation
survey.participation = survey.participation.sub(previousParticipation);
// Reset previously voted options
delete survey.votes[msg.sender];
}
}
/*
* @dev Assumes the survey exists and that msg.sender can vote
*/
function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal {
SurveyStruct storage survey = surveys[_surveyId];
MultiOptionVote storage senderVotes = survey.votes[msg.sender];
// Revert previous votes, if any
_resetVote(_surveyId);
uint256 totalVoted = 0;
// Reserve first index for ABSTAIN_VOTE
senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 });
for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) {
// Voters don't specify that they're abstaining,
// but we still keep track of this by reserving the first index of a survey's votes.
// We subtract 1 from the indexes of the arrays passed in by the voter to account for this.
uint256 optionId = _optionIds[optionIndex - 1];
uint256 stake = _stakes[optionIndex - 1];
require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION);
require(stake > 0, ERROR_NO_STAKE);
// Let's avoid repeating an option by making sure that ascending order is preserved in
// the options array by checking that the current optionId is larger than the last one
// we added
require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED);
// Register voter amount
senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake });
// Add to total option support
survey.optionPower[optionId] = survey.optionPower[optionId].add(stake);
// Keep track of stake used so far
totalVoted = totalVoted.add(stake);
emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]);
}
// Compute and register non used tokens
// Implictly we are doing require(totalVoted <= voterStake) too
// (as stated before, index 0 is for ABSTAIN_VOTE option)
uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock);
senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted);
// Register number of options voted
senderVotes.optionsCastedLength = _optionIds.length;
// Add voter tokens to participation
survey.participation = survey.participation.add(totalVoted);
assert(survey.participation <= survey.votingPower);
}
function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) {
return getTimestamp64() < _survey.startDate.add(surveyTime);
}
}
// File: @aragon/os/contracts/acl/IACLOracle.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IACLOracle {
function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool);
}
// File: @aragon/os/contracts/acl/ACL.sol
pragma solidity 0.4.24;
/* solium-disable function-order */
// Allow public initialize() to be first
contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE");
*/
bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a;
enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types
struct Param {
uint8 id;
uint8 op;
uint240 value; // even though value is an uint240 it can store addresses
// in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal
// op and id take less than 1 byte each so it can be kept in 1 sstore
}
uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200;
uint8 internal constant TIMESTAMP_PARAM_ID = 201;
// 202 is unused
uint8 internal constant ORACLE_PARAM_ID = 203;
uint8 internal constant LOGIC_OP_PARAM_ID = 204;
uint8 internal constant PARAM_VALUE_PARAM_ID = 205;
// TODO: Add execution times param type?
/* Hardcoded constant to save gas
bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0));
*/
bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;
bytes32 public constant NO_PERMISSION = bytes32(0);
address public constant ANY_ENTITY = address(-1);
address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager"
uint256 internal constant ORACLE_CHECK_GAS = 30000;
string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL";
string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER";
string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER";
// Whether someone has a permission
mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash
mapping (bytes32 => Param[]) internal permissionParams; // params hash => params
// Who is the manager of a permission
mapping (bytes32 => address) internal permissionManager;
event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed);
event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash);
event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager);
modifier onlyPermissionManager(address _app, bytes32 _role) {
require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER);
_;
}
modifier noPermissionManager(address _app, bytes32 _role) {
// only allow permission creation (or re-creation) when there is no manager
require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER);
_;
}
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(address _permissionsCreator) public onlyInit {
initialized();
require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL);
_createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator);
}
/**
* @dev Creates a permission that wasn't previously set and managed.
* If a created permission is removed it is possible to reset it with createPermission.
* This is the **ONLY** way to create permissions and set managers to permissions that don't
* have a manager.
* In terms of the ACL being initialized, this function implicitly protects all the other
* state-changing external functions, as they all require the sender to be a manager.
* @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _manager Address of the entity that will be able to grant and revoke the permission further.
*/
function createPermission(address _entity, address _app, bytes32 _role, address _manager)
external
auth(CREATE_PERMISSIONS_ROLE)
noPermissionManager(_app, _role)
{
_createPermission(_entity, _app, _role, _manager);
}
/**
* @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager
* @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
*/
function grantPermission(address _entity, address _app, bytes32 _role)
external
{
grantPermissionP(_entity, _app, _role, new uint256[](0));
}
/**
* @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager
* @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _params Permission parameters
*/
function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params)
public
onlyPermissionManager(_app, _role)
{
bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH;
_setPermission(_entity, _app, _role, paramsHash);
}
/**
* @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager
* @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity to revoke access from
* @param _app Address of the app in which the role will be revoked
* @param _role Identifier for the group of actions in app being revoked
*/
function revokePermission(address _entity, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermission(_entity, _app, _role, NO_PERMISSION);
}
/**
* @notice Set `_newManager` as the manager of `_role` in `_app`
* @param _newManager Address for the new manager
* @param _app Address of the app in which the permission management is being transferred
* @param _role Identifier for the group of actions being transferred
*/
function setPermissionManager(address _newManager, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(_newManager, _app, _role);
}
/**
* @notice Remove the manager of `_role` in `_app`
* @param _app Address of the app in which the permission is being unmanaged
* @param _role Identifier for the group of actions being unmanaged
*/
function removePermissionManager(address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(address(0), _app, _role);
}
/**
* @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
* @param _app Address of the app in which the permission is being burned
* @param _role Identifier for the group of actions being burned
*/
function createBurnedPermission(address _app, bytes32 _role)
external
auth(CREATE_PERMISSIONS_ROLE)
noPermissionManager(_app, _role)
{
_setPermissionManager(BURN_ENTITY, _app, _role);
}
/**
* @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
* @param _app Address of the app in which the permission is being burned
* @param _role Identifier for the group of actions being burned
*/
function burnPermissionManager(address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(BURN_ENTITY, _app, _role);
}
/**
* @notice Get parameters for permission array length
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return Length of the array
*/
function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) {
return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length;
}
/**
* @notice Get parameter for permission
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @param _index Index of parameter in the array
* @return Parameter (id, op, value)
*/
function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index)
external
view
returns (uint8, uint8, uint240)
{
Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index];
return (param.id, param.op, param.value);
}
/**
* @dev Get manager for permission
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return address of the manager for the permission
*/
function getPermissionManager(address _app, bytes32 _role) public view returns (address) {
return permissionManager[roleHash(_app, _role)];
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission statu
* @param _who Sender of the original call
* @param _where Address of the app
* @param _where Identifier for a group of actions in app
* @param _how Permission parameters
* @return boolean indicating whether the ACL allows the role or not
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) {
return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how));
}
function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) {
bytes32 whoParams = permissions[permissionHash(_who, _where, _what)];
if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) {
return true;
}
bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)];
if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) {
return true;
}
return false;
}
function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) {
uint256[] memory empty = new uint256[](0);
return hasPermission(_who, _where, _what, empty);
}
function evalParams(
bytes32 _paramsHash,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) public view returns (bool)
{
if (_paramsHash == EMPTY_PARAM_HASH) {
return true;
}
return _evalParam(_paramsHash, 0, _who, _where, _what, _how);
}
/**
* @dev Internal createPermission for access inside the kernel (on instantiation)
*/
function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal {
_setPermission(_entity, _app, _role, EMPTY_PARAM_HASH);
_setPermissionManager(_manager, _app, _role);
}
/**
* @dev Internal function called to actually save the permission
*/
function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal {
permissions[permissionHash(_entity, _app, _role)] = _paramsHash;
bool entityHasPermission = _paramsHash != NO_PERMISSION;
bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH;
emit SetPermission(_entity, _app, _role, entityHasPermission);
if (permissionHasParams) {
emit SetPermissionParams(_entity, _app, _role, _paramsHash);
}
}
function _saveParams(uint256[] _encodedParams) internal returns (bytes32) {
bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams));
Param[] storage params = permissionParams[paramHash];
if (params.length == 0) { // params not saved before
for (uint256 i = 0; i < _encodedParams.length; i++) {
uint256 encodedParam = _encodedParams[i];
Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam));
params.push(param);
}
}
return paramHash;
}
function _evalParam(
bytes32 _paramsHash,
uint32 _paramId,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) internal view returns (bool)
{
if (_paramId >= permissionParams[_paramsHash].length) {
return false; // out of bounds
}
Param memory param = permissionParams[_paramsHash][_paramId];
if (param.id == LOGIC_OP_PARAM_ID) {
return _evalLogic(param, _paramsHash, _who, _where, _what, _how);
}
uint256 value;
uint256 comparedTo = uint256(param.value);
// get value
if (param.id == ORACLE_PARAM_ID) {
value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0;
comparedTo = 1;
} else if (param.id == BLOCK_NUMBER_PARAM_ID) {
value = getBlockNumber();
} else if (param.id == TIMESTAMP_PARAM_ID) {
value = getTimestamp();
} else if (param.id == PARAM_VALUE_PARAM_ID) {
value = uint256(param.value);
} else {
if (param.id >= _how.length) {
return false;
}
value = uint256(uint240(_how[param.id])); // force lost precision
}
if (Op(param.op) == Op.RET) {
return uint256(value) > 0;
}
return compare(value, Op(param.op), comparedTo);
}
function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how)
internal
view
returns (bool)
{
if (Op(_param.op) == Op.IF_ELSE) {
uint32 conditionParam;
uint32 successParam;
uint32 failureParam;
(conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value));
bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how);
return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how);
}
uint32 param1;
uint32 param2;
(param1, param2,) = decodeParamsList(uint256(_param.value));
bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how);
if (Op(_param.op) == Op.NOT) {
return !r1;
}
if (r1 && Op(_param.op) == Op.OR) {
return true;
}
if (!r1 && Op(_param.op) == Op.AND) {
return false;
}
bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how);
if (Op(_param.op) == Op.XOR) {
return r1 != r2;
}
return r2; // both or and and depend on result of r2 after checks
}
function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) {
if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace
if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace
if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace
if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace
if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace
if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace
return false;
}
function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) {
bytes4 sig = _oracleAddr.canPerform.selector;
// a raw call is required so we can return false if the call reverts, rather than reverting
bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how);
uint256 oracleCheckGas = ORACLE_CHECK_GAS;
bool ok;
assembly {
ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0)
}
if (!ok) {
return false;
}
uint256 size;
assembly { size := returndatasize }
if (size != 32) {
return false;
}
bool result;
assembly {
let ptr := mload(0x40) // get next free memory ptr
returndatacopy(ptr, 0, size) // copy return from above `staticcall`
result := mload(ptr) // read data at ptr and set it to result
mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr
}
return result;
}
/**
* @dev Internal function that sets management
*/
function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal {
permissionManager[roleHash(_app, _role)] = _newManager;
emit ChangePermissionManager(_app, _role, _newManager);
}
function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("ROLE", _where, _what));
}
function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what));
}
}
// File: @aragon/os/contracts/apm/Repo.sol
pragma solidity 0.4.24;
/* solium-disable function-order */
// Allow public initialize() to be first
contract Repo is AragonApp {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE");
*/
bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8;
string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP";
string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION";
string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION";
struct Version {
uint16[3] semanticVersion;
address contractAddress;
bytes contentURI;
}
uint256 internal versionsNextIndex;
mapping (uint256 => Version) internal versions;
mapping (bytes32 => uint256) internal versionIdForSemantic;
mapping (address => uint256) internal latestVersionIdForContract;
event NewVersion(uint256 versionId, uint16[3] semanticVersion);
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize this Repo
*/
function initialize() public onlyInit {
initialized();
versionsNextIndex = 1;
}
/**
* @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)`
* @param _newSemanticVersion Semantic version for new repo version
* @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)
* @param _contentURI External URI for fetching new version's content
*/
function newVersion(
uint16[3] _newSemanticVersion,
address _contractAddress,
bytes _contentURI
) public auth(CREATE_VERSION_ROLE)
{
address contractAddress = _contractAddress;
uint256 lastVersionIndex = versionsNextIndex - 1;
uint16[3] memory lastSematicVersion;
if (lastVersionIndex > 0) {
Version storage lastVersion = versions[lastVersionIndex];
lastSematicVersion = lastVersion.semanticVersion;
if (contractAddress == address(0)) {
contractAddress = lastVersion.contractAddress;
}
// Only allows smart contract change on major version bumps
require(
lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0],
ERROR_INVALID_VERSION
);
}
require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP);
uint256 versionId = versionsNextIndex++;
versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI);
versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId;
latestVersionIdForContract[contractAddress] = versionId;
emit NewVersion(versionId, _newSemanticVersion);
}
function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
return getByVersionId(versionsNextIndex - 1);
}
function getLatestForContractAddress(address _contractAddress)
public
view
returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI)
{
return getByVersionId(latestVersionIdForContract[_contractAddress]);
}
function getBySemanticVersion(uint16[3] _semanticVersion)
public
view
returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI)
{
return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]);
}
function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION);
Version storage version = versions[_versionId];
return (version.semanticVersion, version.contractAddress, version.contentURI);
}
function getVersionsCount() public view returns (uint256) {
return versionsNextIndex - 1;
}
function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) {
bool hasBumped;
uint i = 0;
while (i < 3) {
if (hasBumped) {
if (_newVersion[i] != 0) {
return false;
}
} else if (_newVersion[i] != _oldVersion[i]) {
if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) {
return false;
}
hasBumped = true;
}
i++;
}
return hasBumped;
}
function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(version[0], version[1], version[2]));
}
}
// File: @aragon/os/contracts/apm/APMNamehash.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract APMNamehash {
/* Hardcoded constants to save gas
bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm"))));
*/
bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba;
function apmNamehash(string name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name))));
}
}
// File: @aragon/os/contracts/kernel/KernelStorage.sol
pragma solidity 0.4.24;
contract KernelStorage {
// namespace => app id => address
mapping (bytes32 => mapping (bytes32 => address)) public apps;
bytes32 public recoveryVaultAppId;
}
// File: @aragon/os/contracts/lib/misc/ERCProxy.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ERCProxy {
uint256 internal constant FORWARDING = 1;
uint256 internal constant UPGRADEABLE = 2;
function proxyType() public pure returns (uint256 proxyTypeId);
function implementation() public view returns (address codeAddr);
}
// File: @aragon/os/contracts/common/DelegateProxy.sol
pragma solidity 0.4.24;
contract DelegateProxy is ERCProxy, IsContract {
uint256 internal constant FWD_GAS_LIMIT = 10000;
/**
* @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
* @param _dst Destination address to perform the delegatecall
* @param _calldata Calldata for the delegatecall
*/
function delegatedFwd(address _dst, bytes _calldata) internal {
require(isContract(_dst));
uint256 fwdGasLimit = FWD_GAS_LIMIT;
assembly {
let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
// File: @aragon/os/contracts/common/DepositableDelegateProxy.sol
pragma solidity 0.4.24;
contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
event ProxyDeposit(address sender, uint256 value);
function () external payable {
// send / transfer
if (gasleft() < FWD_GAS_LIMIT) {
require(msg.value > 0 && msg.data.length == 0);
require(isDepositable());
emit ProxyDeposit(msg.sender, msg.value);
} else { // all calls except for send or transfer
address target = implementation();
delegatedFwd(target, msg.data);
}
}
}
// File: @aragon/os/contracts/apps/AppProxyBase.sol
pragma solidity 0.4.24;
contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants {
/**
* @dev Initialize AppProxy
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
setKernel(_kernel);
setAppId(_appId);
// Implicit check that kernel is actually a Kernel
// The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
// occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
// it.
address appCode = getAppBase(_appId);
// If initialize payload is provided, it will be executed
if (_initializePayload.length > 0) {
require(isContract(appCode));
// Cannot make delegatecall as a delegateproxy.delegatedFwd as it
// returns ending execution context and halts contract deployment
require(appCode.delegatecall(_initializePayload));
}
}
function getAppBase(bytes32 _appId) internal view returns (address) {
return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId);
}
}
// File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol
pragma solidity 0.4.24;
contract AppProxyUpgradeable is AppProxyBase {
/**
* @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload)
public // solium-disable-line visibility-first
{
// solium-disable-previous-line no-empty-blocks
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return getAppBase(appId());
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
}
// File: @aragon/os/contracts/apps/AppProxyPinned.sol
pragma solidity 0.4.24;
contract AppProxyPinned is IsContract, AppProxyBase {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.appStorage.pinnedCode")
bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e;
/**
* @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload)
public // solium-disable-line visibility-first
{
setPinnedCode(getAppBase(_appId));
require(isContract(pinnedCode()));
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return pinnedCode();
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return FORWARDING;
}
function setPinnedCode(address _pinnedCode) internal {
PINNED_CODE_POSITION.setStorageAddress(_pinnedCode);
}
function pinnedCode() internal view returns (address) {
return PINNED_CODE_POSITION.getStorageAddress();
}
}
// File: @aragon/os/contracts/factory/AppProxyFactory.sol
pragma solidity 0.4.24;
contract AppProxyFactory {
event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId);
/**
* @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyUpgradeable
*/
function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) {
return newAppProxy(_kernel, _appId, new bytes(0));
}
/**
* @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyUpgradeable
*/
function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) {
AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), true, _appId);
return proxy;
}
/**
* @notice Create a new pinned app instance on `_kernel` with identifier `_appId`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyPinned
*/
function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) {
return newAppProxyPinned(_kernel, _appId, new bytes(0));
}
/**
* @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @param _initializePayload Proxy initialization payload
* @return AppProxyPinned
*/
function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), false, _appId);
return proxy;
}
}
// File: @aragon/os/contracts/kernel/Kernel.sol
pragma solidity 0.4.24;
// solium-disable-next-line max-len
contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar {
/* Hardcoded constants to save gas
bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE");
*/
bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0;
string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT";
string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE";
string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED";
/**
* @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately.
* @param _shouldPetrify Immediately petrify this instance so that it can never be initialized
*/
constructor(bool _shouldPetrify) public {
if (_shouldPetrify) {
petrify();
}
}
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions
* @param _baseAcl Address of base ACL app
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit {
initialized();
// Set ACL base
_setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl);
// Create ACL instance and attach it as the default ACL app
IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID));
acl.initialize(_permissionsCreator);
_setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl);
recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID;
}
/**
* @dev Create a new instance of an app linked to this kernel
* @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
return newAppInstance(_appId, _appBase, new bytes(0), false);
}
/**
* @dev Create a new instance of an app linked to this kernel and set its base
* implementation if it was not already set
* @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @param _initializePayload Payload for call made by the proxy during its construction to initialize
* @param _setDefault Whether the app proxy app is the default one.
* Useful when the Kernel needs to know of an instance of a particular app,
* like Vault for escape hatch mechanism.
* @return AppProxy instance
*/
function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
_setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
appProxy = newAppProxy(this, _appId, _initializePayload);
// By calling setApp directly and not the internal functions, we make sure the params are checked
// and it will only succeed if sender has permissions to set something to the namespace.
if (_setDefault) {
setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
}
}
/**
* @dev Create a new pinned instance of an app linked to this kernel
* @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`.
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
return newPinnedAppInstance(_appId, _appBase, new bytes(0), false);
}
/**
* @dev Create a new pinned instance of an app linked to this kernel and set
* its base implementation if it was not already set
* @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @param _initializePayload Payload for call made by the proxy during its construction to initialize
* @param _setDefault Whether the app proxy app is the default one.
* Useful when the Kernel needs to know of an instance of a particular app,
* like Vault for escape hatch mechanism.
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
_setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
appProxy = newAppProxyPinned(this, _appId, _initializePayload);
// By calling setApp directly and not the internal functions, we make sure the params are checked
// and it will only succeed if sender has permissions to set something to the namespace.
if (_setDefault) {
setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
}
}
/**
* @dev Set the resolving address of an app instance or base implementation
* @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app`
* @param _namespace App namespace to use
* @param _appId Identifier for app
* @param _app Address of the app instance or base implementation
* @return ID of app
*/
function setApp(bytes32 _namespace, bytes32 _appId, address _app)
public
auth(APP_MANAGER_ROLE, arr(_namespace, _appId))
{
_setApp(_namespace, _appId, _app);
}
/**
* @dev Set the default vault id for the escape hatch mechanism
* @param _recoveryVaultAppId Identifier of the recovery vault app
*/
function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId))
{
recoveryVaultAppId = _recoveryVaultAppId;
}
// External access to default app id and namespace constants to mimic default getters for constants
/* solium-disable function-order, mixedcase */
function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; }
function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; }
function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; }
function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; }
function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; }
/* solium-enable function-order, mixedcase */
/**
* @dev Get the address of an app instance or base implementation
* @param _namespace App namespace to use
* @param _appId Identifier for app
* @return Address of the app
*/
function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) {
return apps[_namespace][_appId];
}
/**
* @dev Get the address of the recovery Vault instance (to recover funds)
* @return Address of the Vault
*/
function getRecoveryVault() public view returns (address) {
return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
}
/**
* @dev Get the installed ACL app
* @return ACL app
*/
function acl() public view returns (IACL) {
return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID));
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission status
* @param _who Sender of the original call
* @param _where Address of the app
* @param _what Identifier for a group of actions in app
* @param _how Extra data for ACL auth
* @return Boolean indicating whether the ACL allows the role or not.
* Always returns false if the kernel hasn't been initialized yet.
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) {
IACL defaultAcl = acl();
return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas)
defaultAcl.hasPermission(_who, _where, _what, _how);
}
function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal {
require(isContract(_app), ERROR_APP_NOT_CONTRACT);
apps[_namespace][_appId] = _app;
emit SetApp(_namespace, _appId, _app);
}
function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal {
address app = getApp(_namespace, _appId);
if (app != address(0)) {
// The only way to set an app is if it passes the isContract check, so no need to check it again
require(app == _app, ERROR_INVALID_APP_CHANGE);
} else {
_setApp(_namespace, _appId, _app);
}
}
modifier auth(bytes32 _role, uint256[] memory _params) {
require(
hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)),
ERROR_AUTH_FAILED
);
_;
}
}
// File: @aragon/os/contracts/lib/ens/AbstractENS.sol
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol
pragma solidity ^0.4.15;
interface AbstractENS {
function owner(bytes32 _node) public constant returns (address);
function resolver(bytes32 _node) public constant returns (address);
function ttl(bytes32 _node) public constant returns (uint64);
function setOwner(bytes32 _node, address _owner) public;
function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public;
function setResolver(bytes32 _node, address _resolver) public;
function setTTL(bytes32 _node, uint64 _ttl) public;
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed _node, address _owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed _node, address _resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed _node, uint64 _ttl);
}
// File: @aragon/os/contracts/lib/ens/ENS.sol
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol
pragma solidity ^0.4.0;
/**
* The ENS registry contract.
*/
contract ENS is AbstractENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping(bytes32=>Record) records;
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) {
if (records[node].owner != msg.sender) throw;
_;
}
/**
* Constructs a new ENS registrar.
*/
function ENS() public {
records[0].owner = msg.sender;
}
/**
* Returns the address that owns the specified node.
*/
function owner(bytes32 node) public constant returns (address) {
return records[node].owner;
}
/**
* Returns the address of the resolver for the specified node.
*/
function resolver(bytes32 node) public constant returns (address) {
return records[node].resolver;
}
/**
* Returns the TTL of a node, and any records associated with it.
*/
function ttl(bytes32 node) public constant returns (uint64) {
return records[node].ttl;
}
/**
* Transfers ownership of a node to a new address. May only be called by the current
* owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) only_owner(node) public {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* Transfers ownership of a subnode keccak256(node, label) to a new address. May only be
* called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public {
var subnode = keccak256(node, label);
NewOwner(node, label, owner);
records[subnode].owner = owner;
}
/**
* Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) only_owner(node) public {
NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) only_owner(node) public {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
}
// File: @aragon/os/contracts/lib/ens/PublicResolver.sol
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol
pragma solidity ^0.4.0;
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver {
bytes4 constant INTERFACE_META_ID = 0x01ffc9a7;
bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5;
bytes4 constant NAME_INTERFACE_ID = 0x691f3431;
bytes4 constant ABI_INTERFACE_ID = 0x2203ab56;
bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233;
bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c;
event AddrChanged(bytes32 indexed node, address a);
event ContentChanged(bytes32 indexed node, bytes32 hash);
event NameChanged(bytes32 indexed node, string name);
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
event TextChanged(bytes32 indexed node, string indexed indexedKey, string key);
struct PublicKey {
bytes32 x;
bytes32 y;
}
struct Record {
address addr;
bytes32 content;
string name;
PublicKey pubkey;
mapping(string=>string) text;
mapping(uint256=>bytes) abis;
}
AbstractENS ens;
mapping(bytes32=>Record) records;
modifier only_owner(bytes32 node) {
if (ens.owner(node) != msg.sender) throw;
_;
}
/**
* Constructor.
* @param ensAddr The ENS registrar contract.
*/
function PublicResolver(AbstractENS ensAddr) public {
ens = ensAddr;
}
/**
* Returns true if the resolver implements the interface specified by the provided hash.
* @param interfaceID The ID of the interface to check for.
* @return True if the contract implements the requested interface.
*/
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return interfaceID == ADDR_INTERFACE_ID ||
interfaceID == CONTENT_INTERFACE_ID ||
interfaceID == NAME_INTERFACE_ID ||
interfaceID == ABI_INTERFACE_ID ||
interfaceID == PUBKEY_INTERFACE_ID ||
interfaceID == TEXT_INTERFACE_ID ||
interfaceID == INTERFACE_META_ID;
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public constant returns (address ret) {
ret = records[node].addr;
}
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) only_owner(node) public {
records[node].addr = addr;
AddrChanged(node, addr);
}
/**
* Returns the content hash associated with an ENS node.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The ENS node to query.
* @return The associated content hash.
*/
function content(bytes32 node) public constant returns (bytes32 ret) {
ret = records[node].content;
}
/**
* Sets the content hash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The node to update.
* @param hash The content hash to set
*/
function setContent(bytes32 node, bytes32 hash) only_owner(node) public {
records[node].content = hash;
ContentChanged(node, hash);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) public constant returns (string ret) {
ret = records[node].name;
}
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string name) only_owner(node) public {
records[node].name = name;
NameChanged(node, name);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) {
var record = records[node];
for(contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) {
data = record.abis[contentType];
return;
}
}
contentType = 0;
}
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public {
// Content types must be powers of 2
if (((contentType - 1) & contentType) != 0) throw;
records[node].abis[contentType] = data;
ABIChanged(node, contentType);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) {
return (records[node].pubkey.x, records[node].pubkey.y);
}
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public {
records[node].pubkey = PublicKey(x, y);
PubkeyChanged(node, x, y);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string key) public constant returns (string ret) {
ret = records[node].text[key];
}
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string key, string value) only_owner(node) public {
records[node].text[key] = value;
TextChanged(node, key, key);
}
}
// File: @aragon/os/contracts/kernel/KernelProxy.sol
pragma solidity 0.4.24;
contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy {
/**
* @dev KernelProxy is a proxy contract to a kernel implementation. The implementation
* can update the reference, which effectively upgrades the contract
* @param _kernelImpl Address of the contract used as implementation for kernel
*/
constructor(IKernel _kernelImpl) public {
require(isContract(address(_kernelImpl)));
apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl;
// Note that emitting this event is important for verifying that a KernelProxy instance
// was never upgraded to a malicious Kernel logic contract over its lifespan.
// This starts the "chain of trust", that can be followed through later SetApp() events
// emitted during kernel upgrades.
emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl);
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID];
}
}
// File: @aragon/os/contracts/evmscript/ScriptHelpers.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
library ScriptHelpers {
function getSpecId(bytes _script) internal pure returns (uint32) {
return uint32At(_script, 0);
}
function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := mload(add(_data, add(0x20, _location)))
}
}
function addressAt(bytes _data, uint256 _location) internal pure returns (address result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000),
0x1000000000000000000000000)
}
}
function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000),
0x100000000000000000000000000000000000000000000000000000000)
}
}
function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := add(_data, add(0x20, _location))
}
}
function toBytes(bytes4 _sig) internal pure returns (bytes) {
bytes memory payload = new bytes(4);
assembly { mstore(add(payload, 0x20), _sig) }
return payload;
}
}
// File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol
pragma solidity 0.4.24;
/* solium-disable function-order */
// Allow public initialize() to be first
contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp {
using ScriptHelpers for bytes;
/* Hardcoded constants to save gas
bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE");
bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE");
*/
bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2;
// WARN: Manager can censor all votes and the like happening in an org
bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3;
uint256 internal constant SCRIPT_START_LOCATION = 4;
string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR";
string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED";
string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED";
string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT";
struct ExecutorEntry {
IEVMScriptExecutor executor;
bool enabled;
}
uint256 private executorsNextIndex;
mapping (uint256 => ExecutorEntry) public executors;
event EnableExecutor(uint256 indexed executorId, address indexed executorAddress);
event DisableExecutor(uint256 indexed executorId, address indexed executorAddress);
modifier executorExists(uint256 _executorId) {
require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR);
_;
}
/**
* @notice Initialize the registry
*/
function initialize() public onlyInit {
initialized();
// Create empty record to begin executor IDs at 1
executorsNextIndex = 1;
}
/**
* @notice Add a new script executor with address `_executor` to the registry
* @param _executor Address of the IEVMScriptExecutor that will be added to the registry
* @return id Identifier of the executor in the registry
*/
function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) {
uint256 executorId = executorsNextIndex++;
executors[executorId] = ExecutorEntry(_executor, true);
emit EnableExecutor(executorId, _executor);
return executorId;
}
/**
* @notice Disable script executor with ID `_executorId`
* @param _executorId Identifier of the executor in the registry
*/
function disableScriptExecutor(uint256 _executorId)
external
authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
{
// Note that we don't need to check for an executor's existence in this case, as only
// existing executors can be enabled
ExecutorEntry storage executorEntry = executors[_executorId];
require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED);
executorEntry.enabled = false;
emit DisableExecutor(_executorId, executorEntry.executor);
}
/**
* @notice Enable script executor with ID `_executorId`
* @param _executorId Identifier of the executor in the registry
*/
function enableScriptExecutor(uint256 _executorId)
external
authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
executorExists(_executorId)
{
ExecutorEntry storage executorEntry = executors[_executorId];
require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED);
executorEntry.enabled = true;
emit EnableExecutor(_executorId, executorEntry.executor);
}
/**
* @dev Get the script executor that can execute a particular script based on its first 4 bytes
* @param _script EVMScript being inspected
*/
function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT);
uint256 id = _script.getSpecId();
// Note that we don't need to check for an executor's existence in this case, as only
// existing executors can be enabled
ExecutorEntry storage entry = executors[id];
return entry.enabled ? entry.executor : IEVMScriptExecutor(0);
}
}
// File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified {
uint256 internal constant SCRIPT_START_LOCATION = 4;
}
// File: @aragon/os/contracts/evmscript/executors/CallsScript.sol
pragma solidity 0.4.24;
// Inspired by https://github.com/reverendus/tx-manager
contract CallsScript is BaseEVMScriptExecutor {
using ScriptHelpers for bytes;
/* Hardcoded constants to save gas
bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT");
*/
bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302;
string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL";
string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH";
/* This is manually crafted in assembly
string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED";
*/
event LogScriptCall(address indexed sender, address indexed src, address indexed dst);
/**
* @notice Executes a number of call scripts
* @param _script [ specId (uint32) ] many calls with this structure ->
* [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ]
* @param _blacklist Addresses the script cannot call to, or will revert.
* @return Always returns empty byte array
*/
function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) {
uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id
while (location < _script.length) {
// Check there's at least address + calldataLength available
require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH);
address contractAddress = _script.addressAt(location);
// Check address being called is not blacklist
for (uint256 i = 0; i < _blacklist.length; i++) {
require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL);
}
// logged before execution to ensure event ordering in receipt
// if failed entire execution is reverted regardless
emit LogScriptCall(msg.sender, address(this), contractAddress);
uint256 calldataLength = uint256(_script.uint32At(location + 0x14));
uint256 startOffset = location + 0x14 + 0x04;
uint256 calldataStart = _script.locationOf(startOffset);
// compute end of script / next location
location = startOffset + calldataLength;
require(location <= _script.length, ERROR_INVALID_LENGTH);
bool success;
assembly {
success := call(
sub(gas, 5000), // forward gas left - 5000
contractAddress, // address
0, // no value
calldataStart, // calldata start
calldataLength, // calldata length
0, // don't write output
0 // don't write output
)
switch success
case 0 {
let ptr := mload(0x40)
switch returndatasize
case 0 {
// No error data was returned, revert with "EVMCALLS_CALL_REVERTED"
// See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in
// this memory layout
mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length
mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason
revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Forward the full error data
returndatacopy(ptr, 0, returndatasize)
revert(ptr, returndatasize)
}
}
default { }
}
}
// No need to allocate empty bytes for the return as this can only be called via an delegatecall
// (due to the isInitialized modifier)
}
function executorType() external pure returns (bytes32) {
return EXECUTOR_TYPE;
}
}
// File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol
pragma solidity 0.4.24;
contract EVMScriptRegistryFactory is EVMScriptRegistryConstants {
EVMScriptRegistry public baseReg;
IEVMScriptExecutor public baseCallScript;
/**
* @notice Create a new EVMScriptRegistryFactory.
*/
constructor() public {
baseReg = new EVMScriptRegistry();
baseCallScript = IEVMScriptExecutor(new CallsScript());
}
/**
* @notice Install a new pinned instance of EVMScriptRegistry on `_dao`.
* @param _dao Kernel
* @return Installed EVMScriptRegistry
*/
function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) {
bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector);
reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true));
ACL acl = ACL(_dao.acl());
acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this);
reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript
// Clean up the permissions
acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
return reg;
}
}
// File: @aragon/os/contracts/factory/DAOFactory.sol
pragma solidity 0.4.24;
contract DAOFactory {
IKernel public baseKernel;
IACL public baseACL;
EVMScriptRegistryFactory public regFactory;
event DeployDAO(address dao);
event DeployEVMScriptRegistry(address reg);
/**
* @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`.
* @param _baseKernel Base Kernel
* @param _baseACL Base ACL
* @param _regFactory EVMScriptRegistry factory
*/
constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public {
// No need to init as it cannot be killed by devops199
if (address(_regFactory) != address(0)) {
regFactory = _regFactory;
}
baseKernel = _baseKernel;
baseACL = _baseACL;
}
/**
* @notice Create a new DAO with `_root` set as the initial admin
* @param _root Address that will be granted control to setup DAO permissions
* @return Newly created DAO
*/
function newDAO(address _root) public returns (Kernel) {
Kernel dao = Kernel(new KernelProxy(baseKernel));
if (address(regFactory) == address(0)) {
dao.initialize(baseACL, _root);
} else {
dao.initialize(baseACL, this);
ACL acl = ACL(dao.acl());
bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE();
bytes32 appManagerRole = dao.APP_MANAGER_ROLE();
acl.grantPermission(regFactory, acl, permRole);
acl.createPermission(regFactory, dao, appManagerRole, this);
EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao);
emit DeployEVMScriptRegistry(address(reg));
// Clean up permissions
// First, completely reset the APP_MANAGER_ROLE
acl.revokePermission(regFactory, dao, appManagerRole);
acl.removePermissionManager(dao, appManagerRole);
// Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE
acl.revokePermission(regFactory, acl, permRole);
acl.revokePermission(this, acl, permRole);
acl.grantPermission(_root, acl, permRole);
acl.setPermissionManager(_root, acl, permRole);
}
emit DeployDAO(address(dao));
return dao;
}
}
// File: @aragon/id/contracts/ens/IPublicResolver.sol
pragma solidity ^0.4.0;
interface IPublicResolver {
function supportsInterface(bytes4 interfaceID) constant returns (bool);
function addr(bytes32 node) constant returns (address ret);
function setAddr(bytes32 node, address addr);
function hash(bytes32 node) constant returns (bytes32 ret);
function setHash(bytes32 node, bytes32 hash);
}
// File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol
pragma solidity 0.4.24;
interface IFIFSResolvingRegistrar {
function register(bytes32 _subnode, address _owner) external;
function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public;
}
// File: @aragon/templates-shared/contracts/BaseTemplate.sol
pragma solidity 0.4.24;
contract BaseTemplate is APMNamehash, IsContract {
using Uint256Helpers for uint256;
/* Hardcoded constant to save gas
* bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth
* bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth
* bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth
* bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth
* bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth
* bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth
* bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth
*/
bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a;
bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4;
bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991;
bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae;
bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f;
bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e;
string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT";
string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT";
string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED";
string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT";
string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED";
string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT";
string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS";
string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID";
ENS internal ens;
DAOFactory internal daoFactory;
MiniMeTokenFactory internal miniMeFactory;
IFIFSResolvingRegistrar internal aragonID;
event DeployDao(address dao);
event SetupDao(address dao);
event DeployToken(address token);
event InstalledApp(address appProxy, bytes32 appId);
constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public {
require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT);
require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT);
ens = _ens;
aragonID = _aragonID;
daoFactory = _daoFactory;
miniMeFactory = _miniMeFactory;
}
/**
* @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full
* control during setup. Once the DAO setup has finished, it is recommended to call the
* `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root
* permissions to the end entity in control of the organization.
*/
function _createDAO() internal returns (Kernel dao, ACL acl) {
dao = daoFactory.newDAO(this);
emit DeployDao(address(dao));
acl = ACL(dao.acl());
_createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE());
}
/* ACL */
function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal {
_acl.createPermission(_grantees[0], _app, _permission, address(this));
for (uint256 i = 1; i < _grantees.length; i++) {
_acl.grantPermission(_grantees[i], _app, _permission);
}
_acl.revokePermission(address(this), _app, _permission);
_acl.setPermissionManager(_manager, _app, _permission);
}
function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal {
_acl.createPermission(address(this), _app, _permission, address(this));
}
function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal {
_acl.revokePermission(address(this), _app, _permission);
_acl.removePermissionManager(_app, _permission);
}
function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal {
_transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to);
}
function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal {
ACL _acl = ACL(_dao.acl());
_transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager);
_transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager);
emit SetupDao(_dao);
}
function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal {
_acl.grantPermission(_to, _app, _permission);
_acl.revokePermission(address(this), _app, _permission);
_acl.setPermissionManager(_manager, _app, _permission);
}
/* AGENT */
function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) {
bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector);
Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData));
// We assume that installing the Agent app as a default app means the DAO should have its
// Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent.
_dao.setRecoveryVaultAppId(AGENT_APP_ID);
return agent;
}
function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) {
bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector);
return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData));
}
function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager);
_acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager);
}
/* VAULT */
function _installVaultApp(Kernel _dao) internal returns (Vault) {
bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector);
return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData));
}
function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager);
}
/* VOTING */
function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) {
return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]);
}
function _installVotingApp(
Kernel _dao,
MiniMeToken _token,
uint64 _support,
uint64 _acceptance,
uint64 _duration
)
internal returns (Voting)
{
bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration);
return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData));
}
function _createVotingPermissions(
ACL _acl,
Voting _voting,
address _settingsGrantee,
address _createVotesGrantee,
address _manager
)
internal
{
_acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager);
_acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager);
_acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager);
}
/* SURVEY */
function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) {
bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime);
return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData));
}
function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager);
_acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager);
}
/* PAYROLL */
function _installPayrollApp(
Kernel _dao,
Finance _finance,
address _denominationToken,
IFeed _priceFeed,
uint64 _rateExpiryTime
)
internal returns (Payroll)
{
bytes memory initializeData = abi.encodeWithSelector(
Payroll(0).initialize.selector,
_finance,
_denominationToken,
_priceFeed,
_rateExpiryTime
);
return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData));
}
/**
* @dev Internal function to configure payroll permissions. Note that we allow defining different managers for
* payroll since it may be useful to have one control the payroll settings (rate expiration, price feed,
* and allowed tokens), and another one to control the employee functionality (bonuses, salaries,
* reimbursements, employees, etc).
* @param _acl ACL instance being configured
* @param _acl Payroll app being configured
* @param _employeeManager Address that will receive permissions to handle employee payroll functionality
* @param _settingsManager Address that will receive permissions to manage payroll settings
* @param _permissionsManager Address that will be the ACL manager for the payroll permissions
*/
function _createPayrollPermissions(
ACL _acl,
Payroll _payroll,
address _employeeManager,
address _settingsManager,
address _permissionsManager
)
internal
{
_acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager);
_acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager);
_acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager);
_acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager);
}
function _unwrapPayrollSettings(
uint256[4] memory _payrollSettings
)
internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager)
{
denominationToken = _toAddress(_payrollSettings[0]);
priceFeed = IFeed(_toAddress(_payrollSettings[1]));
rateExpiryTime = _payrollSettings[2].toUint64();
employeeManager = _toAddress(_payrollSettings[3]);
}
/* FINANCE */
function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) {
bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration);
return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData));
}
function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager);
_acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager);
}
function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager);
}
function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal {
_acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE());
}
function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal {
_acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE());
}
/* TOKEN MANAGER */
function _installTokenManagerApp(
Kernel _dao,
MiniMeToken _token,
bool _transferable,
uint256 _maxAccountTokens
)
internal returns (TokenManager)
{
TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID));
_token.changeController(tokenManager);
tokenManager.initialize(_token, _transferable, _maxAccountTokens);
return tokenManager;
}
function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager);
_acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager);
}
function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal {
_createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
for (uint256 i = 0; i < _holders.length; i++) {
_tokenManager.mint(_holders[i], _stakes[i]);
}
_removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
}
function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal {
_createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
for (uint256 i = 0; i < _holders.length; i++) {
_tokenManager.mint(_holders[i], _stake);
}
_removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
}
function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal {
_createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
_tokenManager.mint(_holder, _stake);
_removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
}
/* EVM SCRIPTS */
function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal {
EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry());
_acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager);
_acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager);
}
/* APPS */
function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) {
return _installNonDefaultApp(_dao, _appId, new bytes(0));
}
function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) {
return _installApp(_dao, _appId, _initializeData, false);
}
function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) {
return _installDefaultApp(_dao, _appId, new bytes(0));
}
function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) {
return _installApp(_dao, _appId, _initializeData, true);
}
function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) {
address latestBaseAppAddress = _latestVersionAppBase(_appId);
address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault));
emit InstalledApp(instance, _appId);
return instance;
}
function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) {
Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId));
(,base,) = repo.getLatest();
}
/* TOKEN */
function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) {
require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED);
MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true);
emit DeployToken(address(token));
return token;
}
function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view {
require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT);
}
/* IDS */
function _validateId(string memory _id) internal pure {
require(bytes(_id).length > 0, ERROR_INVALID_ID);
}
function _registerID(string memory _name, address _owner) internal {
require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED);
aragonID.register(keccak256(abi.encodePacked(_name)), _owner);
}
function _ensureAragonIdIsValid(address _aragonID) internal view {
require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT);
}
/* HELPERS */
function _toAddress(uint256 _value) private pure returns (address) {
require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS);
return address(_value);
}
}
// File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol
pragma solidity 0.4.24;
/*
Bancor Formula interface
*/
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256);
function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256);
}
// File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol
pragma solidity 0.4.24;
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
constructor() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
}
// File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol
pragma solidity 0.4.24;
contract BancorFormula is IBancorFormula, Utils {
using SafeMath for uint256;
string public version = '0.3';
uint256 private constant ONE = 1;
uint32 private constant MAX_WEIGHT = 1000000;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
/**
Auto-generated via 'PrintIntScalingFactors.py'
*/
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x200000000000000000000000000000000;
/**
Auto-generated via 'PrintLn2ScalingFactors.py'
*/
uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8;
uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
/**
Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py'
*/
uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3;
uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000;
/**
Auto-generated via 'PrintFunctionConstructor.py'
*/
uint256[128] private maxExpArray;
constructor() public {
// maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff;
// maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff;
// maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff;
// maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff;
// maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff;
// maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff;
// maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
}
/**
@dev given a token supply, connector balance, weight and a deposit amount (in the connector token),
calculates the return for a given conversion (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1)
@param _supply token total supply
@param _connectorBalance total connector balance
@param _connectorWeight connector weight, represented in ppm, 1-1000000
@param _depositAmount deposit amount, in connector token
@return purchase return amount
*/
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT);
// special case for 0 deposit amount
if (_depositAmount == 0)
return 0;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return _supply.mul(_depositAmount) / _connectorBalance;
uint256 result;
uint8 precision;
uint256 baseN = _depositAmount.add(_connectorBalance);
(result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT);
uint256 temp = _supply.mul(result) >> precision;
return temp - _supply;
}
/**
@dev given a token supply, connector balance, weight and a sell amount (in the main token),
calculates the return for a given conversion (in the connector token)
Formula:
Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000)))
@param _supply token total supply
@param _connectorBalance total connector
@param _connectorWeight constant connector Weight, represented in ppm, 1-1000000
@param _sellAmount sell amount, in the token itself
@return sale return amount
*/
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply);
// special case for 0 sell amount
if (_sellAmount == 0)
return 0;
// special case for selling the entire supply
if (_sellAmount == _supply)
return _connectorBalance;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return _connectorBalance.mul(_sellAmount) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _sellAmount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight);
uint256 temp1 = _connectorBalance.mul(result);
uint256 temp2 = _connectorBalance << precision;
return (temp1 - temp2) / result;
}
/**
@dev given two connector balances/weights and a sell amount (in the first connector token),
calculates the return for a conversion from the first connector token to the second connector token (in the second connector token)
Formula:
Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight))
@param _fromConnectorBalance input connector balance
@param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000
@param _toConnectorBalance output connector balance
@param _toConnectorWeight output connector weight, represented in ppm, 1-1000000
@param _amount input connector amount
@return second connector amount
*/
function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) {
// validate input
require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT);
// special case for equal weights
if (_fromConnectorWeight == _toConnectorWeight)
return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount);
uint256 result;
uint8 precision;
uint256 baseN = _fromConnectorBalance.add(_amount);
(result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight);
uint256 temp1 = _toConnectorBalance.mul(result);
uint256 temp2 = _toConnectorBalance << precision;
return (temp1 - temp2) / result;
}
/**
General Description:
Determine a value of precision.
Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
Return the result along with the precision used.
Detailed Description:
Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision".
The larger "precision" is, the more accurately this value represents the real value.
However, the larger "precision" is, the more bits are required in order to store this value.
And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul".
*/
function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) {
require(_baseN < MAX_NUM);
uint256 baseLog;
uint256 base = _baseN * FIXED_1 / _baseD;
if (base < OPT_LOG_MAX_VAL) {
baseLog = optimalLog(base);
}
else {
baseLog = generalLog(base);
}
uint256 baseLogTimesExp = baseLog * _expN / _expD;
if (baseLogTimesExp < OPT_EXP_MAX_VAL) {
return (optimalExp(baseLogTimesExp), MAX_PRECISION);
}
else {
uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);
return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision);
}
}
/**
Compute log(x / FIXED_1) * FIXED_1.
This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
*/
function generalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
/**
Compute the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
}
else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
- This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
- This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x)
lo = mid;
else
hi = mid;
}
if (maxExpArray[hi] >= _x)
return hi;
if (maxExpArray[lo] >= _x)
return lo;
require(false);
return 0;
}
/**
This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'.
It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!)
xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!)
xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!)
xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!)
xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!)
xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!)
xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!)
xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!)
xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!)
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
}
/**
Return log(x / FIXED_1) * FIXED_1
Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1
Auto-generated via 'PrintFunctionOptimalLog.py'
Detailed description:
- Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2
- The natural logarithm of each (pre-calculated) exponent is the degree of the exponent
- The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1
- The natural logarithm of the input is calculated by summing up the intermediate results above
- For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859)
*/
function optimalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
uint256 w;
if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1
if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2
if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3
if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4
if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5
if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6
if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7
if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8
z = y = x - FIXED_1;
w = y * y / FIXED_1;
res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02
res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04
res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06
res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08
res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10
res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12
res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14
res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16
return res;
}
/**
Return e ^ (x / FIXED_1) * FIXED_1
Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1
Auto-generated via 'PrintFunctionOptimalExp.py'
Detailed description:
- Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
- The exponentiation of each binary exponent is given (pre-calculated)
- The exponentiation of r is calculated via Taylor series for e^x, where x = r
- The exponentiation of the input is calculated by multiplying the intermediate results above
- For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function optimalExp(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3)
z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!)
res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
return res;
}
}
// File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol
pragma solidity 0.4.24;
contract IAragonFundraisingController {
function openTrading() external;
function updateTappedAmount(address _token) external;
function collateralsToBeClaimed(address _collateral) public view returns (uint256);
function balanceOf(address _who, address _token) public view returns (uint256);
}
// File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol
pragma solidity 0.4.24;
contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE");
bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE");
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE");
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE");
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE");
bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE");
*/
bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4;
bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb;
bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822;
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d;
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2;
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d;
bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7;
bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0;
uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18
uint32 public constant PPM = 1000000;
string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS";
string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE";
string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO";
string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING";
string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL";
string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE";
string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT";
string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN";
string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN";
string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED";
string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED";
string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM";
string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER";
string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED";
string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED";
string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT";
string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE";
string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED";
struct Collateral {
bool whitelisted;
uint256 virtualSupply;
uint256 virtualBalance;
uint32 reserveRatio;
uint256 slippage;
}
struct MetaBatch {
bool initialized;
uint256 realSupply;
uint256 buyFeePct;
uint256 sellFeePct;
IBancorFormula formula;
mapping(address => Batch) batches;
}
struct Batch {
bool initialized;
bool cancelled;
uint256 supply;
uint256 balance;
uint32 reserveRatio;
uint256 slippage;
uint256 totalBuySpend;
uint256 totalBuyReturn;
uint256 totalSellSpend;
uint256 totalSellReturn;
mapping(address => uint256) buyers;
mapping(address => uint256) sellers;
}
IAragonFundraisingController public controller;
TokenManager public tokenManager;
ERC20 public token;
Vault public reserve;
address public beneficiary;
IBancorFormula public formula;
uint256 public batchBlocks;
uint256 public buyFeePct;
uint256 public sellFeePct;
bool public isOpen;
uint256 public tokensToBeMinted;
mapping(address => uint256) public collateralsToBeClaimed;
mapping(address => Collateral) public collaterals;
mapping(uint256 => MetaBatch) public metaBatches;
event UpdateBeneficiary (address indexed beneficiary);
event UpdateFormula (address indexed formula);
event UpdateFees (uint256 buyFeePct, uint256 sellFeePct);
event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula);
event NewBatch (
uint256 indexed id,
address indexed collateral,
uint256 supply,
uint256 balance,
uint32 reserveRatio,
uint256 slippage)
;
event CancelBatch (uint256 indexed id, address indexed collateral);
event AddCollateralToken (
address indexed collateral,
uint256 virtualSupply,
uint256 virtualBalance,
uint32 reserveRatio,
uint256 slippage
);
event RemoveCollateralToken (address indexed collateral);
event UpdateCollateralToken (
address indexed collateral,
uint256 virtualSupply,
uint256 virtualBalance,
uint32 reserveRatio,
uint256 slippage
);
event Open ();
event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value);
event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount);
event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount);
event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value);
event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value);
event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount);
event UpdatePricing (
uint256 indexed batchId,
address indexed collateral,
uint256 totalBuySpend,
uint256 totalBuyReturn,
uint256 totalSellSpend,
uint256 totalSellReturn
);
/***** external function *****/
/**
* @notice Initialize market maker
* @param _controller The address of the controller contract
* @param _tokenManager The address of the [bonded token] token manager contract
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom fees are to be sent]
* @param _formula The address of the BancorFormula [computation] contract
* @param _batchBlocks The number of blocks batches are to last
* @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE]
*/
function initialize(
IAragonFundraisingController _controller,
TokenManager _tokenManager,
IBancorFormula _formula,
Vault _reserve,
address _beneficiary,
uint256 _batchBlocks,
uint256 _buyFeePct,
uint256 _sellFeePct
)
external
onlyInit
{
initialized();
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA);
require(isContract(_formula), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS);
require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE);
require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING);
controller = _controller;
tokenManager = _tokenManager;
token = ERC20(tokenManager.token());
formula = _formula;
reserve = _reserve;
beneficiary = _beneficiary;
batchBlocks = _batchBlocks;
buyFeePct = _buyFeePct;
sellFeePct = _sellFeePct;
}
/* generic settings related function */
/**
* @notice Open market making [enabling users to open buy and sell orders]
*/
function open() external auth(OPEN_ROLE) {
require(!isOpen, ERROR_ALREADY_OPEN);
_open();
}
/**
* @notice Update formula to `_formula`
* @param _formula The address of the new BancorFormula [computation] contract
*/
function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) {
require(isContract(_formula), ERROR_CONTRACT_IS_EOA);
_updateFormula(_formula);
}
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary [to whom fees are to be sent]
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
_updateBeneficiary(_beneficiary);
}
/**
* @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`%
* @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE]
*/
function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) {
require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE);
_updateFees(_buyFeePct, _sellFeePct);
}
/* collateral tokens related functions */
/**
* @notice Add `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE]
*/
function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage)
external
auth(ADD_COLLATERAL_TOKEN_ROLE)
{
require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL);
require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED);
require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO);
_addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/**
* @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be un-whitelisted
*/
function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
_removeCollateralToken(_collateral);
}
/**
* @notice Update `_collateral.symbol(): string` collateralization settings
* @param _collateral The address of the collateral token whose collateralization settings are to be updated
* @param _virtualSupply The new virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The new virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE]
*/
function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage)
external
auth(UPDATE_COLLATERAL_TOKEN_ROLE)
{
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO);
_updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/* market making related functions */
/**
* @notice Open a buy order worth `@tokenAmount(_collateral, _value)`
* @param _buyer The address of the buyer
* @param _collateral The address of the collateral token to be spent
* @param _value The amount of collateral token to be spent
*/
function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) {
require(isOpen, ERROR_NOT_OPEN);
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED);
require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE);
_openBuyOrder(_buyer, _collateral, _value);
}
/**
* @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string`
* @param _seller The address of the seller
* @param _collateral The address of the collateral token to be returned
* @param _amount The amount of bonded token to be spent
*/
function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) {
require(isOpen, ERROR_NOT_OPEN);
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED);
require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT);
_openSellOrder(_seller, _collateral, _amount);
}
/**
* @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId`
* @param _buyer The address of the user whose buy orders are to be claimed
* @param _batchId The id of the batch in which buy orders are to be claimed
* @param _collateral The address of the collateral token against which buy orders are to be claimed
*/
function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER);
require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED);
require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM);
_claimBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId`
* @param _seller The address of the user whose sell orders are to be claimed
* @param _batchId The id of the batch in which sell orders are to be claimed
* @param _collateral The address of the collateral token against which sell orders are to be claimed
*/
function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER);
require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED);
require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM);
_claimSellOrder(_seller, _batchId, _collateral);
}
/**
* @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId`
* @param _buyer The address of the user whose cancelled buy orders are to be claimed
* @param _batchId The id of the batch in which cancelled buy orders are to be claimed
* @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed
*/
function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED);
require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM);
_claimCancelledBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId`
* @param _seller The address of the user whose cancelled sell orders are to be claimed
* @param _batchId The id of the batch in which cancelled sell orders are to be claimed
* @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed
*/
function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED);
require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM);
_claimCancelledSellOrder(_seller, _batchId, _collateral);
}
/***** public view functions *****/
function getCurrentBatchId() public view isInitialized returns (uint256) {
return _currentBatchId();
}
function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) {
Collateral storage collateral = collaterals[_collateral];
return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage);
}
function getBatch(uint256 _batchId, address _collateral)
public view isInitialized
returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256)
{
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return (
batch.initialized,
batch.cancelled,
batch.supply,
batch.balance,
batch.reserveRatio,
batch.slippage,
batch.totalBuySpend,
batch.totalBuyReturn,
batch.totalSellSpend,
batch.totalSellReturn
);
}
function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) {
return _staticPricePPM(_supply, _balance, _reserveRatio);
}
/***** internal functions *****/
/* computation functions */
function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) {
return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio)));
}
function _currentBatchId() internal view returns (uint256) {
return (block.number.div(batchBlocks)).mul(batchBlocks);
}
/* check functions */
function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) {
return _beneficiary != address(0);
}
function _feeIsValid(uint256 _fee) internal pure returns (bool) {
return _fee < PCT_BASE;
}
function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) {
return _reserveRatio <= PPM;
}
function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) {
return _tokenManager.maxAccountTokens() == uint256(-1);
}
function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) {
if (_value == 0) {
return false;
}
if (_collateral == ETH) {
return _msgValue == _value;
}
return (
_msgValue == 0 &&
controller.balanceOf(_buyer, _collateral) >= _value &&
ERC20(_collateral).allowance(_buyer, address(this)) >= _value
);
}
function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) {
return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount;
}
function _collateralIsWhitelisted(address _collateral) internal view returns (bool) {
return collaterals[_collateral].whitelisted;
}
function _batchIsOver(uint256 _batchId) internal view returns (bool) {
return _batchId < _currentBatchId();
}
function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) {
return metaBatches[_batchId].batches[_collateral].cancelled;
}
function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return batch.buyers[_user] > 0;
}
function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return batch.sellers[_user] > 0;
}
function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) {
return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral];
}
function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) {
uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio);
uint256 maximumSlippage = _batch.slippage;
// if static price is zero let's consider that every slippage is valid
if (staticPricePPM == 0) {
return true;
}
return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage);
}
function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) {
/**
* NOTE
* the case where starting price is zero is handled
* in the meta function _slippageIsValid()
*/
/**
* NOTE
* slippage is valid if:
* totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE)
* totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM
*/
if (
_batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >=
_batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM))
) {
return true;
}
return false;
}
function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) {
/**
* NOTE
* the case where starting price is zero is handled
* in the meta function _slippageIsValid()
*/
// if allowed sell slippage >= 100%
// then any sell slippage is valid
if (_maximumSlippage >= PCT_BASE) {
return true;
}
/**
* NOTE
* slippage is valid if
* totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend
* totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend
* totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE
* totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend
*/
if (
_batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >=
_startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend)
) {
return true;
}
return false;
}
/* initialization functions */
function _currentBatch(address _collateral) internal returns (uint256, Batch storage) {
uint256 batchId = _currentBatchId();
MetaBatch storage metaBatch = metaBatches[batchId];
Batch storage batch = metaBatch.batches[_collateral];
if (!metaBatch.initialized) {
/**
* NOTE
* all collateral batches should be initialized with the same supply to
* avoid price manipulation between different collaterals in the same meta-batch
* we don't need to do the same with collateral balances as orders against one collateral
* can't affect the pool's balance against another collateral and tap is a step-function
* of the meta-batch duration
*/
/**
* NOTE
* realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization)
* 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted
* should not be taken into account in the price computation [they are already a part of the batched pricing computation]
* 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders]
* is for buy orders from previous meta-batches to be claimed [and tokens to be minted]:
* as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization)
*/
metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted);
metaBatch.buyFeePct = buyFeePct;
metaBatch.sellFeePct = sellFeePct;
metaBatch.formula = formula;
metaBatch.initialized = true;
emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula);
}
if (!batch.initialized) {
/**
* NOTE
* supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization)
* virtualSupply can technically be updated during a batch: the on-going batch will still use
* its value at the time of initialization [it's up to the updater to act wisely]
*/
/**
* NOTE
* balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization)
* 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed
* should not be taken into account in the price computation [they are already a part of the batched price computation]
* 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders]
* is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration:
* as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization)
* 3. virtualBalance can technically be updated during a batch: the on-going batch will still use
* its value at the time of initialization [it's up to the updater to act wisely]
*/
controller.updateTappedAmount(_collateral);
batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply);
batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]);
batch.reserveRatio = collaterals[_collateral].reserveRatio;
batch.slippage = collaterals[_collateral].slippage;
batch.initialized = true;
emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage);
}
return (batchId, batch);
}
/* state modifiying functions */
function _open() internal {
isOpen = true;
emit Open();
}
function _updateBeneficiary(address _beneficiary) internal {
beneficiary = _beneficiary;
emit UpdateBeneficiary(_beneficiary);
}
function _updateFormula(IBancorFormula _formula) internal {
formula = _formula;
emit UpdateFormula(address(_formula));
}
function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal {
buyFeePct = _buyFeePct;
sellFeePct = _sellFeePct;
emit UpdateFees(_buyFeePct, _sellFeePct);
}
function _cancelCurrentBatch(address _collateral) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
if (!batch.cancelled) {
batch.cancelled = true;
// bought bonds are cancelled but sold bonds are due back
// bought collaterals are cancelled but sold collaterals are due back
tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn);
emit CancelBatch(batchId, _collateral);
}
}
function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage)
internal
{
collaterals[_collateral].whitelisted = true;
collaterals[_collateral].virtualSupply = _virtualSupply;
collaterals[_collateral].virtualBalance = _virtualBalance;
collaterals[_collateral].reserveRatio = _reserveRatio;
collaterals[_collateral].slippage = _slippage;
emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
function _removeCollateralToken(address _collateral) internal {
_cancelCurrentBatch(_collateral);
Collateral storage collateral = collaterals[_collateral];
delete collateral.whitelisted;
delete collateral.virtualSupply;
delete collateral.virtualBalance;
delete collateral.reserveRatio;
delete collateral.slippage;
emit RemoveCollateralToken(_collateral);
}
function _updateCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
)
internal
{
collaterals[_collateral].virtualSupply = _virtualSupply;
collaterals[_collateral].virtualBalance = _virtualBalance;
collaterals[_collateral].reserveRatio = _reserveRatio;
collaterals[_collateral].slippage = _slippage;
emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
// deduct fee
uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE);
uint256 value = _value.sub(fee);
// collect fee and collateral
if (fee > 0) {
_transfer(_buyer, beneficiary, _collateral, fee);
}
_transfer(_buyer, address(reserve), _collateral, value);
// save batch
uint256 deprecatedBuyReturn = batch.totalBuyReturn;
uint256 deprecatedSellReturn = batch.totalSellReturn;
// update batch
batch.totalBuySpend = batch.totalBuySpend.add(value);
batch.buyers[_buyer] = batch.buyers[_buyer].add(value);
// update pricing
_updatePricing(batch, batchId, _collateral);
// update the amount of tokens to be minted and collaterals to be claimed
tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn);
// sanity checks
require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT);
emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value);
}
function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
// burn bonds
tokenManager.burn(_seller, _amount);
// save batch
uint256 deprecatedBuyReturn = batch.totalBuyReturn;
uint256 deprecatedSellReturn = batch.totalSellReturn;
// update batch
batch.totalSellSpend = batch.totalSellSpend.add(_amount);
batch.sellers[_seller] = batch.sellers[_seller].add(_amount);
// update pricing
_updatePricing(batch, batchId, _collateral);
// update the amount of tokens to be minted and collaterals to be claimed
tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn);
// sanity checks
require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT);
require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE);
emit OpenSellOrder(_seller, batchId, _collateral, _amount);
}
function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend);
batch.buyers[_buyer] = 0;
if (buyReturn > 0) {
tokensToBeMinted = tokensToBeMinted.sub(buyReturn);
tokenManager.mint(_buyer, buyReturn);
}
emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn);
}
function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend);
uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE);
uint256 value = saleReturn.sub(fee);
batch.sellers[_seller] = 0;
if (value > 0) {
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn);
reserve.transfer(_collateral, _seller, value);
}
if (fee > 0) {
reserve.transfer(_collateral, beneficiary, fee);
}
emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value);
}
function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 value = batch.buyers[_buyer];
batch.buyers[_buyer] = 0;
if (value > 0) {
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value);
reserve.transfer(_collateral, _buyer, value);
}
emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value);
}
function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 amount = batch.sellers[_seller];
batch.sellers[_seller] = 0;
if (amount > 0) {
tokensToBeMinted = tokensToBeMinted.sub(amount);
tokenManager.mint(_seller, amount);
}
emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount);
}
function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal {
// the situation where there are no buy nor sell orders can't happen [keep commented]
// if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0)
// return;
// static price is the current exact price in collateral
// per token according to the initial state of the batch
// [expressed in PPM for precision sake]
uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio);
// [NOTE]
// if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend
// so totalSellReturn will be zero and totalBuyReturn will be
// computed normally along the formula
// 1. we want to find out if buy orders are worth more sell orders [or vice-versa]
// 2. we thus check the return of sell orders at the current exact price
// 3. if the return of sell orders is larger than the pending buys,
// there are more sells than buys [and vice-versa]
uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM));
if (resultOfSell > batch.totalBuySpend) {
// >> sell orders are worth more than buy orders
// 1. first we execute all pending buy orders at the current exact
// price because there is at least one sell order for each buy order
// 2. then the final sell return is the addition of this first
// matched return with the remaining bonding curve return
// the number of tokens bought as a result of all buy orders matched at the
// current exact price [which is less than the total amount of tokens to be sold]
batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM);
// the number of tokens left over to be sold along the curve which is the difference
// between the original total sell order and the result of all the buy orders
uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn);
// the amount of collateral generated by selling tokens left over to be sold
// along the bonding curve in the batch initial state [as if the buy orders
// never existed and the sell order was just smaller than originally thought]
uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell);
// the total result of all sells is the original amount of buys which were matched
// plus the remaining sells which were executed along the bonding curve
batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn);
} else {
// >> buy orders are worth more than sell orders
// 1. first we execute all pending sell orders at the current exact
// price because there is at least one buy order for each sell order
// 2. then the final buy return is the addition of this first
// matched return with the remaining bonding curve return
// the number of collaterals bought as a result of all sell orders matched at the
// current exact price [which is less than the total amount of collateral to be spent]
batch.totalSellReturn = resultOfSell;
// the number of collaterals left over to be spent along the curve which is the difference
// between the original total buy order and the result of all the sell orders
uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell);
// the amount of tokens generated by selling collaterals left over to be spent
// along the bonding curve in the batch initial state [as if the sell orders
// never existed and the buy order was just smaller than originally thought]
uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy);
// the total result of all buys is the original amount of buys which were matched
// plus the remaining buys which were executed along the bonding curve
batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn);
}
emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn);
}
function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal {
if (_collateralToken == ETH) {
_to.transfer(_amount);
} else {
require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED);
}
}
}
// File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol
pragma solidity 0.4.24;
contract IPresale {
function open() external;
function close() external;
function contribute(address _contributor, uint256 _value) external payable;
function refund(address _contributor, uint256 _vestedPurchaseId) external;
function contributionToTokens(uint256 _value) public view returns (uint256);
function contributionToken() public view returns (address);
}
// File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol
pragma solidity 0.4.24;
contract ITap {
function updateBeneficiary(address _beneficiary) external;
function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external;
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external;
function addTappedToken(address _token, uint256 _rate, uint256 _floor) external;
function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external;
function resetTappedToken(address _token) external;
function updateTappedAmount(address _token) external;
function withdraw(address _token) external;
function getMaximumWithdrawal(address _token) public view returns (uint256);
function rates(address _token) public view returns (uint256);
}
// File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol
pragma solidity 0.4.24;
contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE");
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE");
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE");
bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE");
bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE");
bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE");
bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE");
bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE");
bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE");
bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE");
bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE");
*/
bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822;
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d;
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2;
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d;
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207;
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1;
bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207;
bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416;
bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2;
bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6;
bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07;
bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7;
bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0;
bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec;
uint256 public constant TO_RESET_CAP = 10;
string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS";
IPresale public presale;
BatchedBancorMarketMaker public marketMaker;
Agent public reserve;
ITap public tap;
address[] public toReset;
/***** external functions *****/
/**
* @notice Initialize Aragon Fundraising controller
* @param _presale The address of the presale contract
* @param _marketMaker The address of the market maker contract
* @param _reserve The address of the reserve [pool] contract
* @param _tap The address of the tap contract
* @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open]
*/
function initialize(
IPresale _presale,
BatchedBancorMarketMaker _marketMaker,
Agent _reserve,
ITap _tap,
address[] _toReset
)
external
onlyInit
{
require(isContract(_presale), ERROR_CONTRACT_IS_EOA);
require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(isContract(_tap), ERROR_CONTRACT_IS_EOA);
require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS);
initialized();
presale = _presale;
marketMaker = _marketMaker;
reserve = _reserve;
tap = _tap;
for (uint256 i = 0; i < _toReset.length; i++) {
require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS);
toReset.push(_toReset[i]);
}
}
/* generic settings related function */
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
marketMaker.updateBeneficiary(_beneficiary);
tap.updateBeneficiary(_beneficiary);
}
/**
* @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`%
* @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE]
*/
function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) {
marketMaker.updateFees(_buyFeePct, _sellFeePct);
}
/* presale related functions */
/**
* @notice Open presale
*/
function openPresale() external auth(OPEN_PRESALE_ROLE) {
presale.open();
}
/**
* @notice Close presale and open trading
*/
function closePresale() external isInitialized {
presale.close();
}
/**
* @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)`
* @param _value The amount of contribution token to be spent
*/
function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) {
presale.contribute.value(msg.value)(msg.sender, _value);
}
/**
* @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId`
* @param _contributor The address of the contributor whose presale contribution is to be refunded
* @param _vestedPurchaseId The id of the contribution to be refunded
*/
function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized {
presale.refund(_contributor, _vestedPurchaseId);
}
/* market making related functions */
/**
* @notice Open trading [enabling users to open buy and sell orders]
*/
function openTrading() external auth(OPEN_TRADING_ROLE) {
for (uint256 i = 0; i < toReset.length; i++) {
if (tap.rates(toReset[i]) != uint256(0)) {
tap.resetTappedToken(toReset[i]);
}
}
marketMaker.open();
}
/**
* @notice Open a buy order worth `@tokenAmount(_collateral, _value)`
* @param _collateral The address of the collateral token to be spent
* @param _value The amount of collateral token to be spent
*/
function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) {
marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value);
}
/**
* @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string`
* @param _collateral The address of the collateral token to be returned
* @param _amount The amount of bonded token to be spent
*/
function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) {
marketMaker.openSellOrder(msg.sender, _collateral, _amount);
}
/**
* @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId`
* @param _buyer The address of the user whose buy orders are to be claimed
* @param _batchId The id of the batch in which buy orders are to be claimed
* @param _collateral The address of the collateral token against which buy orders are to be claimed
*/
function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized {
marketMaker.claimBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId`
* @param _seller The address of the user whose sell orders are to be claimed
* @param _batchId The id of the batch in which sell orders are to be claimed
* @param _collateral The address of the collateral token against which sell orders are to be claimed
*/
function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized {
marketMaker.claimSellOrder(_seller, _batchId, _collateral);
}
/* collateral tokens related functions */
/**
* @notice Add `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE]
* @param _rate The rate at which that token is to be tapped [in wei / block]
* @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function addCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage,
uint256 _rate,
uint256 _floor
)
external
auth(ADD_COLLATERAL_TOKEN_ROLE)
{
marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
if (_collateral != ETH) {
reserve.addProtectedToken(_collateral);
}
if (_rate > 0) {
tap.addTappedToken(_collateral, _rate, _floor);
}
}
/**
* @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past]
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE]
*/
function reAddCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
)
external
auth(ADD_COLLATERAL_TOKEN_ROLE)
{
marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/**
* @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be un-whitelisted
*/
function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) {
marketMaker.removeCollateralToken(_collateral);
// the token should still be tapped to avoid being locked
// the token should still be protected to avoid being spent
}
/**
* @notice Update `_collateral.symbol(): string` collateralization settings
* @param _collateral The address of the collateral token whose collateralization settings are to be updated
* @param _virtualSupply The new virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The new virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE]
*/
function updateCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
)
external
auth(UPDATE_COLLATERAL_TOKEN_ROLE)
{
marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/* tap related functions */
/**
* @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`%
* @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) {
tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct);
}
/**
* @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`%
* @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) {
tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct);
}
/**
* @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token to be tapped
* @param _rate The rate at which that token is to be tapped [in wei / block]
* @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) {
tap.addTappedToken(_token, _rate, _floor);
}
/**
* @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token whose tap is to be updated
* @param _rate The new rate at which that token is to be tapped [in wei / block]
* @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) {
tap.updateTappedToken(_token, _rate, _floor);
}
/**
* @notice Update tapped amount for `_token.symbol(): string`
* @param _token The address of the token whose tapped amount is to be updated
*/
function updateTappedAmount(address _token) external {
tap.updateTappedAmount(_token);
}
/**
* @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary
* @param _token The address of the token to be transfered from the reserve to the beneficiary
*/
function withdraw(address _token) external auth(WITHDRAW_ROLE) {
tap.withdraw(_token);
}
/***** public view functions *****/
function token() public view isInitialized returns (address) {
return marketMaker.token();
}
function contributionToken() public view isInitialized returns (address) {
return presale.contributionToken();
}
function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) {
return tap.getMaximumWithdrawal(_token);
}
function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) {
return marketMaker.collateralsToBeClaimed(_collateral);
}
function balanceOf(address _who, address _token) public view isInitialized returns (uint256) {
uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who);
if (_who == address(reserve)) {
return balance.sub(tap.getMaximumWithdrawal(_token));
} else {
return balance;
}
}
/***** internal functions *****/
function _tokenIsContractOrETH(address _token) internal view returns (bool) {
return isContract(_token) || _token == ETH;
}
}
// File: @ablack/fundraising-presale/contracts/Presale.sol
pragma solidity ^0.4.24;
contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using SafeMath64 for uint64;
/**
Hardcoded constants to save gas
bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE");
bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE");
*/
bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4;
bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07;
uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4
string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN";
string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL";
string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE";
string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD";
string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT";
string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE";
string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE";
string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE";
string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE";
string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND";
string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED";
enum State {
Pending, // presale is idle and pending to be started
Funding, // presale has started and contributors can purchase tokens
Refunding, // presale has not reached goal within period and contributors can claim refunds
GoalReached, // presale has reached goal within period and trading is ready to be open
Closed // presale has reached goal within period, has been closed and trading has been open
}
IAragonFundraisingController public controller;
TokenManager public tokenManager;
ERC20 public token;
address public reserve;
address public beneficiary;
address public contributionToken;
uint256 public goal;
uint64 public period;
uint256 public exchangeRate;
uint64 public vestingCliffPeriod;
uint64 public vestingCompletePeriod;
uint256 public supplyOfferedPct;
uint256 public fundingForBeneficiaryPct;
uint64 public openDate;
bool public isClosed;
uint64 public vestingCliffDate;
uint64 public vestingCompleteDate;
uint256 public totalRaised;
mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent)
event SetOpenDate (uint64 date);
event Close ();
event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId);
event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId);
/***** external function *****/
/**
* @notice Initialize presale
* @param _controller The address of the controller contract
* @param _tokenManager The address of the [bonded] token manager contract
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent]
* @param _contributionToken The address of the token to be used to contribute
* @param _goal The goal to be reached by the end of that presale [in contribution token wei]
* @param _period The period within which to accept contribution for that presale
* @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM]
* @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed
* @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested
* @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM]
* @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM]
* @param _openDate The date upon which that presale is to be open [ignored if 0]
*/
function initialize(
IAragonFundraisingController _controller,
TokenManager _tokenManager,
address _reserve,
address _beneficiary,
address _contributionToken,
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate
)
external
onlyInit
{
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY);
require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN);
require(_goal > 0, ERROR_INVALID_GOAL);
require(_period > 0, ERROR_INVALID_TIME_PERIOD);
require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE);
require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD);
require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD);
require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT);
require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT);
initialized();
controller = _controller;
tokenManager = _tokenManager;
token = ERC20(_tokenManager.token());
reserve = _reserve;
beneficiary = _beneficiary;
contributionToken = _contributionToken;
goal = _goal;
period = _period;
exchangeRate = _exchangeRate;
vestingCliffPeriod = _vestingCliffPeriod;
vestingCompletePeriod = _vestingCompletePeriod;
supplyOfferedPct = _supplyOfferedPct;
fundingForBeneficiaryPct = _fundingForBeneficiaryPct;
if (_openDate != 0) {
_setOpenDate(_openDate);
}
}
/**
* @notice Open presale [enabling users to contribute]
*/
function open() external auth(OPEN_ROLE) {
require(state() == State.Pending, ERROR_INVALID_STATE);
require(openDate == 0, ERROR_INVALID_STATE);
_open();
}
/**
* @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)`
* @param _contributor The address of the contributor
* @param _value The amount of contribution token to be spent
*/
function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) {
require(state() == State.Funding, ERROR_INVALID_STATE);
require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE);
if (contributionToken == ETH) {
require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE);
} else {
require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE);
}
_contribute(_contributor, _value);
}
/**
* @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId`
* @param _contributor The address of the contributor whose presale contribution is to be refunded
* @param _vestedPurchaseId The id of the contribution to be refunded
*/
function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized {
require(state() == State.Refunding, ERROR_INVALID_STATE);
_refund(_contributor, _vestedPurchaseId);
}
/**
* @notice Close presale and open trading
*/
function close() external nonReentrant isInitialized {
require(state() == State.GoalReached, ERROR_INVALID_STATE);
_close();
}
/***** public view functions *****/
/**
* @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)`
* @param _value The amount of contribution tokens to be used in that computation
*/
function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) {
return _value.mul(exchangeRate).div(PPM);
}
function contributionToken() public view isInitialized returns (address) {
return contributionToken;
}
/**
* @notice Returns the current state of that presale
*/
function state() public view isInitialized returns (State) {
if (openDate == 0 || openDate > getTimestamp64()) {
return State.Pending;
}
if (totalRaised >= goal) {
if (isClosed) {
return State.Closed;
} else {
return State.GoalReached;
}
}
if (_timeSinceOpen() < period) {
return State.Funding;
} else {
return State.Refunding;
}
}
/***** internal functions *****/
function _timeSinceOpen() internal view returns (uint64) {
if (openDate == 0) {
return 0;
} else {
return getTimestamp64().sub(openDate);
}
}
function _setOpenDate(uint64 _date) internal {
require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD);
openDate = _date;
_setVestingDatesWhenOpenDateIsKnown();
emit SetOpenDate(_date);
}
function _setVestingDatesWhenOpenDateIsKnown() internal {
vestingCliffDate = openDate.add(vestingCliffPeriod);
vestingCompleteDate = openDate.add(vestingCompletePeriod);
}
function _open() internal {
_setOpenDate(getTimestamp64());
}
function _contribute(address _contributor, uint256 _value) internal {
uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value;
if (contributionToken == ETH && _value > value) {
msg.sender.transfer(_value.sub(value));
}
// (contributor) ~~~> contribution tokens ~~~> (presale)
if (contributionToken != ETH) {
require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE);
require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE);
_transfer(contributionToken, _contributor, address(this), value);
}
// (mint ✨) ~~~> project tokens ~~~> (contributor)
uint256 tokensToSell = contributionToTokens(value);
tokenManager.issue(tokensToSell);
uint256 vestedPurchaseId = tokenManager.assignVested(
_contributor,
tokensToSell,
openDate,
vestingCliffDate,
vestingCompleteDate,
true /* revokable */
);
totalRaised = totalRaised.add(value);
// register contribution tokens spent in this purchase for a possible upcoming refund
contributions[_contributor][vestedPurchaseId] = value;
emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId);
}
function _refund(address _contributor, uint256 _vestedPurchaseId) internal {
// recall how much contribution tokens are to be refund for this purchase
uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId];
require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND);
contributions[_contributor][_vestedPurchaseId] = 0;
// (presale) ~~~> contribution tokens ~~~> (contributor)
_transfer(contributionToken, address(this), _contributor, tokensToRefund);
/**
* NOTE
* the following lines assume that _contributor has not transfered any of its vested tokens
* for now TokenManager does not handle switching the transferrable status of its underlying token
* there is thus no way to enforce non-transferrability during the presale phase only
* this will be updated in a later version
*/
// (contributor) ~~~> project tokens ~~~> (token manager)
(uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId);
tokenManager.revokeVesting(_contributor, _vestedPurchaseId);
// (token manager) ~~~> project tokens ~~~> (burn 💥)
tokenManager.burn(address(tokenManager), tokensSold);
emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId);
}
function _close() internal {
isClosed = true;
// (presale) ~~~> contribution tokens ~~~> (beneficiary)
uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM);
if (fundsForBeneficiary > 0) {
_transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary);
}
// (presale) ~~~> contribution tokens ~~~> (reserve)
uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this));
_transfer(contributionToken, address(this), reserve, tokensForReserve);
// (mint ✨) ~~~> project tokens ~~~> (beneficiary)
uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct);
tokenManager.issue(tokensForBeneficiary);
tokenManager.assignVested(
beneficiary,
tokensForBeneficiary,
openDate,
vestingCliffDate,
vestingCompleteDate,
false /* revokable */
);
// open trading
controller.openTrading();
emit Close();
}
function _transfer(address _token, address _from, address _to, uint256 _amount) internal {
if (_token == ETH) {
require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED);
require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED);
_to.transfer(_amount);
} else {
if (_from == address(this)) {
require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED);
} else {
require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED);
}
}
}
}
// File: @ablack/fundraising-tap/contracts/Tap.sol
pragma solidity 0.4.24;
contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE");
bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE");
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE");
bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE");
bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE");
bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE");
bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE");
bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE");
*/
bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30;
bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7;
bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207;
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1;
bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc;
bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd;
bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288;
bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e;
bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec;
uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18
string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS";
string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT";
string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN";
string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE";
string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE";
string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED";
string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED";
string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO";
IAragonFundraisingController public controller;
Vault public reserve;
address public beneficiary;
uint256 public batchBlocks;
uint256 public maximumTapRateIncreasePct;
uint256 public maximumTapFloorDecreasePct;
mapping (address => uint256) public tappedAmounts;
mapping (address => uint256) public rates;
mapping (address => uint256) public floors;
mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers]
mapping (address => uint256) public lastTapUpdates; // timestamps
event UpdateBeneficiary (address indexed beneficiary);
event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct);
event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct);
event AddTappedToken (address indexed token, uint256 rate, uint256 floor);
event RemoveTappedToken (address indexed token);
event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor);
event ResetTappedToken (address indexed token);
event UpdateTappedAmount (address indexed token, uint256 tappedAmount);
event Withdraw (address indexed token, uint256 amount);
/***** external functions *****/
/**
* @notice Initialize tap
* @param _controller The address of the controller contract
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn]
* @param _batchBlocks The number of blocks batches are to last
* @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE]
* @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE]
*/
function initialize(
IAragonFundraisingController _controller,
Vault _reserve,
address _beneficiary,
uint256 _batchBlocks,
uint256 _maximumTapRateIncreasePct,
uint256 _maximumTapFloorDecreasePct
)
external
onlyInit
{
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS);
require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT);
initialized();
controller = _controller;
reserve = _reserve;
beneficiary = _beneficiary;
batchBlocks = _batchBlocks;
maximumTapRateIncreasePct = _maximumTapRateIncreasePct;
maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct;
}
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn]
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
_updateBeneficiary(_beneficiary);
}
/**
* @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`%
* @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) {
_updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct);
}
/**
* @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`%
* @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) {
require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT);
_updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct);
}
/**
* @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token to be tapped
* @param _rate The rate at which that token is to be tapped [in wei / block]
* @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) {
require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN);
require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED);
require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE);
_addTappedToken(_token, _rate, _floor);
}
/**
* @notice Remove tap for `_token.symbol(): string`
* @param _token The address of the token to be un-tapped
*/
function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
_removeTappedToken(_token);
}
/**
* @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token whose tap is to be updated
* @param _rate The new rate at which that token is to be tapped [in wei / block]
* @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE);
require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE);
_updateTappedToken(_token, _rate, _floor);
}
/**
* @notice Reset tap timestamps for `_token.symbol(): string`
* @param _token The address of the token whose tap timestamps are to be reset
*/
function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
_resetTappedToken(_token);
}
/**
* @notice Update tapped amount for `_token.symbol(): string`
* @param _token The address of the token whose tapped amount is to be updated
*/
function updateTappedAmount(address _token) external {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
_updateTappedAmount(_token);
}
/**
* @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()`
* @param _token The address of the token to be transfered
*/
function withdraw(address _token) external auth(WITHDRAW_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
uint256 amount = _updateTappedAmount(_token);
require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO);
_withdraw(_token, amount);
}
/***** public view functions *****/
function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) {
return _tappedAmount(_token);
}
function rates(address _token) public view isInitialized returns (uint256) {
return rates[_token];
}
/***** internal functions *****/
/* computation functions */
function _currentBatchId() internal view returns (uint256) {
return (block.number.div(batchBlocks)).mul(batchBlocks);
}
function _tappedAmount(address _token) internal view returns (uint256) {
uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]);
uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve);
uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]);
uint256 tappedAmount = tappedAmounts[_token].add(flow);
/**
* whatever happens enough collateral should be
* kept in the reserve pool to guarantee that
* its balance is kept above the floor once
* all pending sell orders are claimed
*/
/**
* the reserve's balance is already below the balance to be kept
* the tapped amount should be reset to zero
*/
if (balance <= toBeKept) {
return 0;
}
/**
* the reserve's balance minus the upcoming tap flow would be below the balance to be kept
* the flow should be reduced to balance - toBeKept
*/
if (balance <= toBeKept.add(tappedAmount)) {
return balance.sub(toBeKept);
}
/**
* the reserve's balance minus the upcoming flow is above the balance to be kept
* the flow can be added to the tapped amount
*/
return tappedAmount;
}
/* check functions */
function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) {
return _beneficiary != address(0);
}
function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) {
return _maximumTapFloorDecreasePct <= PCT_BASE;
}
function _tokenIsContractOrETH(address _token) internal view returns (bool) {
return isContract(_token) || _token == ETH;
}
function _tokenIsTapped(address _token) internal view returns (bool) {
return rates[_token] != uint256(0);
}
function _tapRateIsValid(uint256 _rate) internal pure returns (bool) {
return _rate != 0;
}
function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) {
return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor);
}
function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) {
uint256 rate = rates[_token];
if (_rate <= rate) {
return true;
}
if (getTimestamp() < lastTapUpdates[_token] + 30 days) {
return false;
}
if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) {
return true;
}
return false;
}
function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) {
uint256 floor = floors[_token];
if (_floor >= floor) {
return true;
}
if (getTimestamp() < lastTapUpdates[_token] + 30 days) {
return false;
}
if (maximumTapFloorDecreasePct >= PCT_BASE) {
return true;
}
if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) {
return true;
}
return false;
}
/* state modifying functions */
function _updateTappedAmount(address _token) internal returns (uint256) {
uint256 tappedAmount = _tappedAmount(_token);
lastTappedAmountUpdates[_token] = _currentBatchId();
tappedAmounts[_token] = tappedAmount;
emit UpdateTappedAmount(_token, tappedAmount);
return tappedAmount;
}
function _updateBeneficiary(address _beneficiary) internal {
beneficiary = _beneficiary;
emit UpdateBeneficiary(_beneficiary);
}
function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal {
maximumTapRateIncreasePct = _maximumTapRateIncreasePct;
emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct);
}
function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal {
maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct;
emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct);
}
function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal {
/**
* NOTE
* 1. if _token is tapped in the middle of a batch it will
* reach the next batch faster than what it normally takes
* to go through a batch [e.g. one block later]
* 2. this will allow for a higher withdrawal than expected
* a few blocks after _token is tapped
* 3. this is not a problem because this extra amount is
* static [at most rates[_token] * batchBlocks] and does
* not increase in time
*/
rates[_token] = _rate;
floors[_token] = _floor;
lastTappedAmountUpdates[_token] = _currentBatchId();
lastTapUpdates[_token] = getTimestamp();
emit AddTappedToken(_token, _rate, _floor);
}
function _removeTappedToken(address _token) internal {
delete tappedAmounts[_token];
delete rates[_token];
delete floors[_token];
delete lastTappedAmountUpdates[_token];
delete lastTapUpdates[_token];
emit RemoveTappedToken(_token);
}
function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal {
/**
* NOTE
* withdraw before updating to keep the reserve
* actual balance [balance - virtual withdrawal]
* continuous in time [though a floor update can
* still break this continuity]
*/
uint256 amount = _updateTappedAmount(_token);
if (amount > 0) {
_withdraw(_token, amount);
}
rates[_token] = _rate;
floors[_token] = _floor;
lastTapUpdates[_token] = getTimestamp();
emit UpdateTappedToken(_token, _rate, _floor);
}
function _resetTappedToken(address _token) internal {
tappedAmounts[_token] = 0;
lastTappedAmountUpdates[_token] = _currentBatchId();
lastTapUpdates[_token] = getTimestamp();
emit ResetTappedToken(_token);
}
function _withdraw(address _token, uint256 _amount) internal {
tappedAmounts[_token] = tappedAmounts[_token].sub(_amount);
reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error
emit Withdraw(_token, _amount);
}
}
// File: contracts/AavegotchiTBCTemplate.sol
pragma solidity 0.4.24;
contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate {
string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS";
string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE";
bool private constant BOARD_TRANSFERABLE = false;
uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0);
uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1);
bool private constant SHARE_TRANSFERABLE = true;
uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18);
uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0);
uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days);
uint256 private constant BUY_FEE_PCT = 0;
uint256 private constant SELL_FEE_PCT = 0;
uint32 private constant DAI_RESERVE_RATIO = 333333; // 33%
uint32 private constant ANT_RESERVE_RATIO = 10000; // 1%
bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d;
bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5;
bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0;
bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac;
bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc;
struct Cache {
address dao;
address boardTokenManager;
address boardVoting;
address vault;
address finance;
address shareVoting;
address shareTokenManager;
address reserve;
address presale;
address marketMaker;
address tap;
address controller;
}
address[] public collaterals;
mapping (address => Cache) private cache;
constructor(
DAOFactory _daoFactory,
ENS _ens,
MiniMeTokenFactory _miniMeFactory,
IFIFSResolvingRegistrar _aragonID,
address _dai,
address _ant
)
BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID)
public
{
_ensureAragonIdIsValid(_aragonID);
_ensureMiniMeFactoryIsValid(_miniMeFactory);
require(isContract(_dai), ERROR_BAD_SETTINGS);
require(isContract(_ant), ERROR_BAD_SETTINGS);
require(_dai != _ant, ERROR_BAD_SETTINGS);
collaterals.push(_dai);
collaterals.push(_ant);
}
/***** external functions *****/
function prepareInstance(
string _boardTokenName,
string _boardTokenSymbol,
address[] _boardMembers,
uint64[3] _boardVotingSettings,
uint64 _financePeriod
)
external
{
require(_boardMembers.length > 0, ERROR_BAD_SETTINGS);
require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS);
// deploy DAO
(Kernel dao, ACL acl) = _createDAO();
// deploy board token
MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS);
// install board apps
TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod);
// mint board tokens
_mintTokens(acl, tm, _boardMembers, 1);
// cache DAO
_cacheDao(dao);
}
function installShareApps(
string _shareTokenName,
string _shareTokenSymbol,
uint64[3] _shareVotingSettings
)
external
{
require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS);
_ensureBoardAppsCache();
Kernel dao = _daoCache();
// deploy share token
MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS);
// install share apps
_installShareApps(dao, shareToken, _shareVotingSettings);
// setup board apps permissions [now that share apps have been installed]
_setupBoardPermissions(dao);
}
function installFundraisingApps(
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate,
uint256 _batchBlocks,
uint256 _maxTapRateIncreasePct,
uint256 _maxTapFloorDecreasePct
)
external
{
_ensureShareAppsCache();
Kernel dao = _daoCache();
// install fundraising apps
_installFundraisingApps(
dao,
_goal,
_period,
_exchangeRate,
_vestingCliffPeriod,
_vestingCompletePeriod,
_supplyOfferedPct,
_fundingForBeneficiaryPct,
_openDate,
_batchBlocks,
_maxTapRateIncreasePct,
_maxTapFloorDecreasePct
);
// setup share apps permissions [now that fundraising apps have been installed]
_setupSharePermissions(dao);
// setup fundraising apps permissions
_setupFundraisingPermissions(dao);
}
function finalizeInstance(
string _id,
uint256[2] _virtualSupplies,
uint256[2] _virtualBalances,
uint256[2] _slippages,
uint256 _rateDAI,
uint256 _floorDAI
)
external
{
require(bytes(_id).length > 0, ERROR_BAD_SETTINGS);
require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS);
require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS);
require(_slippages.length == 2, ERROR_BAD_SETTINGS);
_ensureFundraisingAppsCache();
Kernel dao = _daoCache();
ACL acl = ACL(dao.acl());
(, Voting shareVoting) = _shareAppsCache();
// setup collaterals
_setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI);
// setup EVM script registry permissions
_createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting);
// clear DAO permissions
_transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting);
// register id
_registerID(_id, address(dao));
// clear cache
_clearCache();
}
/***** internal apps installation functions *****/
function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod)
internal
returns (TokenManager)
{
TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT);
Voting voting = _installVotingApp(_dao, _token, _votingSettings);
Vault vault = _installVaultApp(_dao);
Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod);
_cacheBoardApps(tm, voting, vault, finance);
return tm;
}
function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings)
internal
{
TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT);
Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings);
_cacheShareApps(tm, voting);
}
function _installFundraisingApps(
Kernel _dao,
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate,
uint256 _batchBlocks,
uint256 _maxTapRateIncreasePct,
uint256 _maxTapFloorDecreasePct
)
internal
{
_proxifyFundraisingApps(_dao);
_initializePresale(
_goal,
_period,
_exchangeRate,
_vestingCliffPeriod,
_vestingCompletePeriod,
_supplyOfferedPct,
_fundingForBeneficiaryPct,
_openDate
);
_initializeMarketMaker(_batchBlocks);
_initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct);
_initializeController();
}
function _proxifyFundraisingApps(Kernel _dao) internal {
Agent reserve = _installNonDefaultAgentApp(_dao);
Presale presale = Presale(_registerApp(_dao, PRESALE_ID));
BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID));
Tap tap = Tap(_registerApp(_dao, TAP_ID));
AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID));
_cacheFundraisingApps(reserve, presale, marketMaker, tap, controller);
}
/***** internal apps initialization functions *****/
function _initializePresale(
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate
)
internal
{
_presaleCache().initialize(
_controllerCache(),
_shareTMCache(),
_reserveCache(),
_vaultCache(),
collaterals[0],
_goal,
_period,
_exchangeRate,
_vestingCliffPeriod,
_vestingCompletePeriod,
_supplyOfferedPct,
_fundingForBeneficiaryPct,
_openDate
);
}
function _initializeMarketMaker(uint256 _batchBlocks) internal {
IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID));
(,, Vault beneficiary,) = _boardAppsCache();
(TokenManager shareTM,) = _shareAppsCache();
(Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache();
marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT);
}
function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal {
(,, Vault beneficiary,) = _boardAppsCache();
(Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache();
tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct);
}
function _initializeController() internal {
(Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache();
address[] memory toReset = new address[](1);
toReset[0] = collaterals[0];
controller.initialize(presale, marketMaker, reserve, tap, toReset);
}
/***** internal setup functions *****/
function _setupCollaterals(
Kernel _dao,
uint256[2] _virtualSupplies,
uint256[2] _virtualBalances,
uint256[2] _slippages,
uint256 _rateDAI,
uint256 _floorDAI
)
internal
{
ACL acl = ACL(_dao.acl());
(, Voting shareVoting) = _shareAppsCache();
(,,,, AragonFundraisingController controller) = _fundraisingAppsCache();
// create and grant ADD_COLLATERAL_TOKEN_ROLE to this template
_createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE());
// add DAI both as a protected collateral and a tapped token
controller.addCollateralToken(
collaterals[0],
_virtualSupplies[0],
_virtualBalances[0],
DAI_RESERVE_RATIO,
_slippages[0],
_rateDAI,
_floorDAI
);
// add ANT as a protected collateral [but not as a tapped token]
controller.addCollateralToken(
collaterals[1],
_virtualSupplies[1],
_virtualBalances[1],
ANT_RESERVE_RATIO,
_slippages[1],
0,
0
);
// transfer ADD_COLLATERAL_TOKEN_ROLE
_transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);
}
/***** internal permissions functions *****/
function _setupBoardPermissions(Kernel _dao) internal {
ACL acl = ACL(_dao.acl());
(TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache();
(, Voting shareVoting) = _shareAppsCache();
// token manager
_createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting);
// voting
_createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting);
// vault
_createVaultPermissions(acl, vault, finance, shareVoting);
// finance
_createFinancePermissions(acl, finance, boardVoting, shareVoting);
_createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting);
}
function _setupSharePermissions(Kernel _dao) internal {
ACL acl = ACL(_dao.acl());
(TokenManager boardTM,,,) = _boardAppsCache();
(TokenManager shareTM, Voting shareVoting) = _shareAppsCache();
(, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache();
// token manager
address[] memory grantees = new address[](2);
grantees[0] = address(marketMaker);
grantees[1] = address(presale);
acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting);
acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting);
acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting);
acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting);
_createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting);
// voting
_createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting);
}
function _setupFundraisingPermissions(Kernel _dao) internal {
ACL acl = ACL(_dao.acl());
(, Voting boardVoting,,) = _boardAppsCache();
(, Voting shareVoting) = _shareAppsCache();
(Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache();
// reserve
address[] memory grantees = new address[](2);
grantees[0] = address(tap);
grantees[1] = address(marketMaker);
acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting);
acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting);
_createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting);
// presale
acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting);
acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting);
// market maker
acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting);
// tap
acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting);
// controller
// ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added]
acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting);
// acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting);
acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting);
acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting);
}
/***** internal cache functions *****/
function _cacheDao(Kernel _dao) internal {
Cache storage c = cache[msg.sender];
c.dao = address(_dao);
}
function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal {
Cache storage c = cache[msg.sender];
c.boardTokenManager = address(_boardTM);
c.boardVoting = address(_boardVoting);
c.vault = address(_vault);
c.finance = address(_finance);
}
function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal {
Cache storage c = cache[msg.sender];
c.shareTokenManager = address(_shareTM);
c.shareVoting = address(_shareVoting);
}
function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal {
Cache storage c = cache[msg.sender];
c.reserve = address(_reserve);
c.presale = address(_presale);
c.marketMaker = address(_marketMaker);
c.tap = address(_tap);
c.controller = address(_controller);
}
function _daoCache() internal view returns (Kernel dao) {
Cache storage c = cache[msg.sender];
dao = Kernel(c.dao);
}
function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) {
Cache storage c = cache[msg.sender];
boardTM = TokenManager(c.boardTokenManager);
boardVoting = Voting(c.boardVoting);
vault = Vault(c.vault);
finance = Finance(c.finance);
}
function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) {
Cache storage c = cache[msg.sender];
shareTM = TokenManager(c.shareTokenManager);
shareVoting = Voting(c.shareVoting);
}
function _fundraisingAppsCache() internal view returns (
Agent reserve,
Presale presale,
BatchedBancorMarketMaker marketMaker,
Tap tap,
AragonFundraisingController controller
)
{
Cache storage c = cache[msg.sender];
reserve = Agent(c.reserve);
presale = Presale(c.presale);
marketMaker = BatchedBancorMarketMaker(c.marketMaker);
tap = Tap(c.tap);
controller = AragonFundraisingController(c.controller);
}
function _clearCache() internal {
Cache storage c = cache[msg.sender];
delete c.dao;
delete c.boardTokenManager;
delete c.boardVoting;
delete c.vault;
delete c.finance;
delete c.shareVoting;
delete c.shareTokenManager;
delete c.reserve;
delete c.presale;
delete c.marketMaker;
delete c.tap;
delete c.controller;
}
/**
* NOTE
* the following functions are only needed for the presale
* initialization function [which we can't compile otherwise
* because of a `stack too deep` error]
*/
function _vaultCache() internal view returns (Vault vault) {
Cache storage c = cache[msg.sender];
vault = Vault(c.vault);
}
function _shareTMCache() internal view returns (TokenManager shareTM) {
Cache storage c = cache[msg.sender];
shareTM = TokenManager(c.shareTokenManager);
}
function _reserveCache() internal view returns (Agent reserve) {
Cache storage c = cache[msg.sender];
reserve = Agent(c.reserve);
}
function _presaleCache() internal view returns (Presale presale) {
Cache storage c = cache[msg.sender];
presale = Presale(c.presale);
}
function _controllerCache() internal view returns (AragonFundraisingController controller) {
Cache storage c = cache[msg.sender];
controller = AragonFundraisingController(c.controller);
}
/***** internal check functions *****/
function _ensureBoardAppsCache() internal view {
Cache storage c = cache[msg.sender];
require(
c.boardTokenManager != address(0) &&
c.boardVoting != address(0) &&
c.vault != address(0) &&
c.finance != address(0),
ERROR_MISSING_CACHE
);
}
function _ensureShareAppsCache() internal view {
Cache storage c = cache[msg.sender];
require(
c.shareTokenManager != address(0) &&
c.shareVoting != address(0),
ERROR_MISSING_CACHE
);
}
function _ensureFundraisingAppsCache() internal view {
Cache storage c = cache[msg.sender];
require(
c.reserve != address(0) &&
c.presale != address(0) &&
c.marketMaker != address(0) &&
c.tap != address(0) &&
c.controller != address(0),
ERROR_MISSING_CACHE
);
}
/***** internal utils functions *****/
function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) {
address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId));
emit InstalledApp(proxy, _appId);
return proxy;
}
} | add x^19 * (33! / 19!)
| xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; | 451,550 | [
1,
1289,
619,
66,
3657,
225,
261,
3707,
5,
342,
5342,
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,
14087,
273,
261,
27005,
380,
389,
92,
13,
1671,
389,
14548,
31,
400,
1011,
14087,
380,
374,
92,
12648,
9449,
23,
323,
69,
2138,
24852,
2733,
73,
7616,
26021,
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
] |
./partial_match/1/0xa249ee8255dF0AA00A15262b16BCA3eFD66c3E4C/sources/StablesPool.sol | Update reward variables of the given pool to be up-to-date. | function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number);
pool.accBsdPerShare = pool.accBsdPerShare.add(_generatedReward.div(poolLength).mul(1e18).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 4,083,318 | [
1,
1891,
19890,
3152,
434,
326,
864,
2845,
358,
506,
731,
17,
869,
17,
712,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
2864,
12,
11890,
5034,
389,
6610,
13,
1071,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
309,
261,
2629,
18,
2696,
1648,
2845,
18,
2722,
17631,
1060,
1768,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
2845,
18,
9953,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
9953,
3088,
1283,
422,
374,
13,
288,
203,
5411,
2845,
18,
2722,
17631,
1060,
1768,
273,
1203,
18,
2696,
31,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
389,
11168,
17631,
1060,
273,
336,
7823,
17631,
1060,
12,
6011,
18,
2722,
17631,
1060,
1768,
16,
1203,
18,
2696,
1769,
203,
3639,
2845,
18,
8981,
38,
6427,
2173,
9535,
273,
2845,
18,
8981,
38,
6427,
2173,
9535,
18,
1289,
24899,
11168,
17631,
1060,
18,
2892,
12,
6011,
1782,
2934,
16411,
12,
21,
73,
2643,
2934,
2892,
12,
9953,
3088,
1283,
10019,
203,
3639,
2845,
18,
2722,
17631,
1060,
1768,
273,
1203,
18,
2696,
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
] |
./full_match/1/0x9D6d4e2AfAB382ae9B52807a4B36A8d2Afc78b07/sources/contracts/PositionNFTs.sol | * @dev Mints NFT for sender, without it user can not use WiseLending protocol/ | function mintPosition()
external
{
_mintPositionForUser(
msg.sender
);
}
| 8,488,278 | [
1,
49,
28142,
423,
4464,
364,
5793,
16,
2887,
518,
729,
848,
486,
999,
678,
784,
48,
2846,
1771,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
2555,
1435,
203,
3639,
3903,
203,
565,
288,
203,
3639,
389,
81,
474,
2555,
19894,
12,
203,
5411,
1234,
18,
15330,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//! DappReg is a Dapp Registry :)
//!
//! Copyright 2016 Jaco Greef, Parity Technologies Ltd.
//!
//! 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.22;
import "./Owned.sol";
contract DappReg is Owned {
// id - shared to be the same accross all contracts for a specific dapp (including GithuHint for the repo)
// owner - that guy
// deleted - whether the dapp has been unregistered and should be ignored
// meta - meta information for the dapp
struct Dapp {
bytes32 id;
address owner;
bool deleted;
mapping (bytes32 => bytes32) meta;
}
event MetaChanged(bytes32 indexed id, bytes32 indexed key, bytes32 value);
event OwnerChanged(bytes32 indexed id, address indexed owner);
event Registered(bytes32 indexed id, address indexed owner);
event Unregistered(bytes32 indexed id);
mapping (bytes32 => Dapp) dapps;
bytes32[] ids;
uint public fee = 1 ether;
modifier whenFeePaid {
require(msg.value >= fee);
_;
}
modifier onlyDappOwner(bytes32 _id) {
require(dapps[_id].owner == msg.sender);
_;
}
modifier eitherOwner(bytes32 _id) {
require(dapps[_id].owner == msg.sender || owner == msg.sender);
_;
}
modifier whenIdFree(bytes32 _id) {
require(dapps[_id].id == 0);
_;
}
modifier whenActive(bytes32 _id) {
require(!dapps[_id].deleted);
_;
}
// add apps
function register(bytes32 _id)
external
payable
whenFeePaid
whenIdFree(_id)
{
ids.push(_id);
dapps[_id] = Dapp(_id, msg.sender, false);
emit Registered(_id, msg.sender);
}
// remove apps
function unregister(bytes32 _id)
external
whenActive(_id)
eitherOwner(_id)
{
dapps[_id].deleted = true;
emit Unregistered(_id);
}
// set meta information
function setMeta(bytes32 _id, bytes32 _key, bytes32 _value)
external
whenActive(_id)
onlyDappOwner(_id)
{
dapps[_id].meta[_key] = _value;
emit MetaChanged(_id, _key, _value);
}
// set the dapp owner
function setDappOwner(bytes32 _id, address _owner)
external
whenActive(_id)
onlyDappOwner(_id)
{
dapps[_id].owner = _owner;
emit OwnerChanged(_id, _owner);
}
// set the registration fee
function setFee(uint _fee)
external
onlyOwner
{
fee = _fee;
}
// retrieve funds paid
function drain()
external
onlyOwner
{
msg.sender.transfer(address(this).balance);
}
// returns the count of the dapps we have
function count()
external
view
returns (uint)
{
return ids.length;
}
// a dapp from the list
function at(uint _index)
external
view
whenActive(ids[_index])
returns (bytes32 id, address owner)
{
Dapp storage d = dapps[ids[_index]];
id = d.id;
owner = d.owner;
}
// get with the id
function get(bytes32 _id)
external
view
whenActive(_id)
returns (bytes32 id, address owner)
{
Dapp storage d = dapps[_id];
id = d.id;
owner = d.owner;
}
// get meta information
function meta(bytes32 _id, bytes32 _key)
external
view
whenActive(_id)
returns (bytes32)
{
return dapps[_id].meta[_key];
}
}
| set the registration fee | function setFee(uint _fee)
external
onlyOwner
{
fee = _fee;
}
| 7,231,083 | [
1,
542,
326,
7914,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
915,
444,
14667,
12,
11890,
389,
21386,
13,
203,
202,
202,
9375,
203,
202,
202,
3700,
5541,
203,
202,
95,
203,
202,
202,
21386,
273,
389,
21386,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xE45f944e04A8E8617Bb705e33C80B74E806d1e60/sources/PreCrowdsale.sol | * @dev Fallback function which invokes the processContribution function @param _tokenAddress TKRP Token address @param _to preCrowdsale owner address/ | function PreCrowdsale(address _tokenAddress, address _to) {
token = TKRPToken(_tokenAddress);
preCrowdsaleOwner = _to;
}
| 4,007,952 | [
1,
12355,
445,
1492,
18058,
326,
1207,
442,
4027,
445,
225,
389,
2316,
1887,
399,
47,
54,
52,
3155,
1758,
225,
389,
869,
675,
39,
492,
2377,
5349,
3410,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2962,
39,
492,
2377,
5349,
12,
2867,
389,
2316,
1887,
16,
1758,
389,
869,
13,
288,
203,
3639,
1147,
273,
399,
47,
54,
52,
1345,
24899,
2316,
1887,
1769,
203,
3639,
675,
39,
492,
2377,
5349,
5541,
273,
389,
869,
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
] |
/* solium-disable-next-line linebreak-style */
pragma solidity ^0.4.24;
// Implements a simple ownership model with 2-phase transfer.
contract Owned {
address public owner;
address public proposedOwner;
constructor() public
{
owner = msg.sender;
}
modifier onlyOwner() {
require(isOwner(msg.sender) == true, 'Require owner to execute transaction');
_;
}
function isOwner(address _address) public view returns (bool) {
return (_address == owner);
}
function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool success) {
require(_proposedOwner != address(0), 'Require proposedOwner != address(0)');
require(_proposedOwner != address(this), 'Require proposedOwner != address(this)');
require(_proposedOwner != owner, 'Require proposedOwner != owner');
proposedOwner = _proposedOwner;
return true;
}
function completeOwnershipTransfer() public returns (bool success) {
require(msg.sender == proposedOwner, 'Require msg.sender == proposedOwner');
owner = msg.sender;
proposedOwner = address(0);
return true;
}
}
// ----------------------------------------------------------------------------
// OpsManaged - Implements an Owner and Ops Permission Model
// ----------------------------------------------------------------------------
contract OpsManaged is Owned {
address public opsAddress;
constructor() public
Owned()
{
}
modifier onlyOwnerOrOps() {
require(isOwnerOrOps(msg.sender), 'Require only owner or ops');
_;
}
function isOps(address _address) public view returns (bool) {
return (opsAddress != address(0) && _address == opsAddress);
}
function isOwnerOrOps(address _address) public view returns (bool) {
return (isOwner(_address) || isOps(_address));
}
function setOpsAddress(address _newOpsAddress) public onlyOwner returns (bool success) {
require(_newOpsAddress != owner, 'Require newOpsAddress != owner');
require(_newOpsAddress != address(this), 'Require newOpsAddress != address(this)');
opsAddress = _newOpsAddress;
return true;
}
}
// ----------------------------------------------------------------------------
// Finalizable - Implement Finalizable (Crowdsale) model
// ----------------------------------------------------------------------------
contract Finalizable is OpsManaged {
FinalizableState public finalized;
enum FinalizableState {
None,
Finalized
}
event Finalized();
constructor() public OpsManaged()
{
finalized = FinalizableState.None;
}
function finalize() public onlyOwner returns (bool success) {
require(finalized == FinalizableState.None, 'Require !finalized');
finalized = FinalizableState.Finalized;
emit Finalized();
return true;
}
}
// ----------------------------------------------------------------------------
// Math - Implement Math Library
// ----------------------------------------------------------------------------
library Math {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 r = a + b;
require(r >= a, 'Require r >= a');
return r;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, 'Require a >= b');
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 r = a * b;
require(r / a == b, 'Require r / a == b');
return r;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
}
// ----------------------------------------------------------------------------
// ERC20Interface - Standard ERC20 Interface Definition
// Based on the final ERC20 specification at:
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function balanceOf(address _owner) public view returns (uint256 balance);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
// ----------------------------------------------------------------------------
// ERC20Token - Standard ERC20 Implementation
// ----------------------------------------------------------------------------
contract ERC20Token is ERC20Interface {
using Math for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping(address => uint256) internal balances;
mapping(address => mapping (address => uint256)) allowed;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply, address _initialTokenHolder) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
// The initial balance of tokens is assigned to the given token holder address.
balances[_initialTokenHolder] = _totalSupply;
allowed[_initialTokenHolder][_initialTokenHolder] = balances[_initialTokenHolder];
// Per EIP20, the constructor should fire a Transfer event if tokens are assigned to an account.
emit Transfer(0x0, _initialTokenHolder, _totalSupply);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
}
// ----------------------------------------------------------------------------
// FinalizableToken - Extension to ERC20Token with ops and finalization
// ----------------------------------------------------------------------------
//
// ERC20 token with the following additions:
// 1. Owner/Ops Ownership
// 2. Finalization
//
contract FinalizableToken is ERC20Token, OpsManaged, Finalizable {
using Math for uint256;
// The constructor will assign the initial token supply to the owner (msg.sender).
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public
ERC20Token(_name, _symbol, _decimals, _totalSupply, msg.sender)
Finalizable()
{
}
function transfer(address _to, uint256 _value) public returns (bool success) {
validateTransfer(msg.sender, _to);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
validateTransfer(msg.sender, _to);
return super.transferFrom(_from, _to, _value);
}
function validateTransfer(address _sender, address _to) internal view {
// Once the token is finalized, everybody can transfer tokens.
if (finalized == FinalizableState.Finalized) {
return;
}
if (isOwner(_to)) {
return;
}
// Before the token is finalized, only owner and ops are allowed to initiate transfers.
// This allows them to move tokens while the sale is still in private sale.
require(isOwnerOrOps(_sender), 'Require is owner or ops allowed to initiate transfer');
}
}
// ----------------------------------------------------------------------------
// PBTT Token Contract Configuration
// ----------------------------------------------------------------------------
contract PBTTTokenConfig {
string internal constant TOKEN_SYMBOL = 'PBTT';
string internal constant TOKEN_NAME = 'Purple Butterfly Token (PBTT)';
uint8 internal constant TOKEN_DECIMALS = 3;
uint256 internal constant DECIMALSFACTOR = 10**uint256(TOKEN_DECIMALS);
uint256 internal constant TOKEN_TOTALSUPPLY = 1000000000 * DECIMALSFACTOR;
}
// ----------------------------------------------------------------------------
// PBTT Token Contract
// ----------------------------------------------------------------------------
contract PBTTToken is FinalizableToken, PBTTTokenConfig {
uint256 public buyPriceEth = 0.0002 ether; // Buy price for PBTT
uint256 public sellPriceEth = 0.0001 ether; // Sell price for PBTT
uint256 public gasForPBTT = 0.005 ether; // Eth from contract against PBTT to pay tx (10 times sellPriceEth)
uint256 public PBTTForGas = 1; // PBTT to contract against eth to pay tx
uint256 public gasReserve = 1 ether; // Eth amount that remains in the contract for gas and can't be sold
// Minimal eth balance of sender and recipient, ensure that no account receiving
// the token has less than the necessary Ether to pay the fees
uint256 public minBalanceForAccounts = 0.005 ether;
uint256 public totalTokenSold = 0;
enum HaltState {
Unhalted,
Halted
}
HaltState public halts;
constructor() public
FinalizableToken(TOKEN_NAME, TOKEN_SYMBOL, TOKEN_DECIMALS, TOKEN_TOTALSUPPLY)
{
halts = HaltState.Unhalted;
finalized = FinalizableState.None;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(halts == HaltState.Unhalted, 'Require smart contract is not in halted state');
// Prevents drain and spam
require(_value >= PBTTForGas, 'Token amount is not enough to transfer');
if (!isOwnerOrOps(msg.sender) && _to == address(this)) {
// Trade PBTT against eth by sending to the token contract
sellPBTTAgainstEther(_value);
return true;
} else {
if(isOwnerOrOps(msg.sender)) {
return super.transferFrom(owner, _to, _value);
}
return super.transfer(_to, _value);
}
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(halts == HaltState.Unhalted, 'Require smart contract is not in halted state');
return super.transferFrom(_from, _to, _value);
}
//Change PPBT Selling and Buy Price
function setEtherPrices(uint256 newBuyPriceEth, uint256 newSellPriceEth) public onlyOwnerOrOps {
// Set prices to buy and sell PBTT
buyPriceEth = newBuyPriceEth;
sellPriceEth = newSellPriceEth;
}
function setGasForPBTT(uint256 newGasAmountInWei) public onlyOwnerOrOps {
gasForPBTT = newGasAmountInWei;
}
//set PBTT to contract against eth to pay tx
function setPBTTForGas(uint256 newPBTTAmount) public onlyOwnerOrOps {
PBTTForGas = newPBTTAmount;
}
function setGasReserve(uint256 newGasReserveInWei) public onlyOwnerOrOps {
gasReserve = newGasReserveInWei;
}
function setMinBalance(uint256 minimumBalanceInWei) public onlyOwnerOrOps {
minBalanceForAccounts = minimumBalanceInWei;
}
function getTokenRemaining() public view returns (uint256 total){
return (TOKEN_TOTALSUPPLY.div(DECIMALSFACTOR)).sub(totalTokenSold);
}
/* User buys PBTT and pays in Ether */
function buyPBTTAgainstEther() private returns (uint256 tokenAmount) {
// Avoid dividing 0, sending small amounts and spam
require(buyPriceEth > 0, 'buyPriceEth must be > 0');
require(msg.value >= buyPriceEth, 'Transfer money must be enough for 1 token');
// Calculate the amount of PBTT
tokenAmount = (msg.value.mul(DECIMALSFACTOR)).div(buyPriceEth);
// Check if it has enough to sell
require(balances[owner] >= tokenAmount, 'Not enough token balance');
// Add the amount to buyer's balance
balances[msg.sender] = balances[msg.sender].add(tokenAmount);
// Subtract amount from PBTT balance
balances[owner] = balances[owner].sub(tokenAmount);
// Execute an event reflecting the change
emit Transfer(owner, msg.sender, tokenAmount);
totalTokenSold = totalTokenSold + tokenAmount;
return tokenAmount;
}
function sellPBTTAgainstEther(uint256 amount) private returns (uint256 revenue) {
// Avoid selling and spam
require(sellPriceEth > 0, 'sellPriceEth must be > 0');
require(amount >= PBTTForGas, 'Sell token amount must be larger than PBTTForGas value');
// Check if the sender has enough to sell
require(balances[msg.sender] >= amount, 'Token balance is not enough to sold');
require(msg.sender.balance >= minBalanceForAccounts, 'Seller balance must be enough to pay the transaction fee');
// Revenue = eth that will be send to the user
revenue = (amount.div(DECIMALSFACTOR)).mul(sellPriceEth);
// Keep min amount of eth in contract to provide gas for transactions
uint256 remaining = address(this).balance.sub(revenue);
require(remaining >= gasReserve, 'Remaining contract balance is not enough for reserved');
// Add the token amount to owner balance
balances[owner] = balances[owner].add(amount);
// Subtract the amount from seller's token balance
balances[msg.sender] = balances[msg.sender].sub(amount);
// transfer eth
// 'msg.sender.transfer' means the contract sends ether to 'msg.sender'
// It's important to do this last to avoid recursion attacks
msg.sender.transfer(revenue);
// Execute an event reflecting on the change
emit Transfer(msg.sender, owner, amount);
return revenue;
}
// Allows a token holder to burn tokens. Once burned, tokens are permanently
// removed from the total supply.
function burn(uint256 _amount) public returns (bool success) {
require(_amount > 0, 'Token amount to burn must be larger than 0');
address account = msg.sender;
require(_amount <= balanceOf(account), 'You cannot burn token you dont have');
balances[account] = balances[account].sub(_amount);
totalSupply = totalSupply.sub(_amount);
return true;
}
// Allows the owner to reclaim tokens that are assigned to the token contract itself.
function reclaimTokens() public onlyOwner returns (bool success) {
address account = address(this);
uint256 amount = balanceOf(account);
if (amount == 0) {
return false;
}
balances[account] = balances[account].sub(amount);
balances[owner] = balances[owner].add(amount);
return true;
}
// Allows the owner to withdraw that are assigned to the token contract itself.
function withdrawFundToOwner() public onlyOwner {
// transfer to owner
uint256 eth = address(this).balance;
owner.transfer(eth);
}
// Allows the owner to withdraw all fund from contract to owner's specific adress
function withdrawFundToAddress(address _ownerOtherAdress) public onlyOwner {
// transfer to owner
uint256 eth = address(this).balance;
_ownerOtherAdress.transfer(eth);
}
/* Halts or unhalts direct trades without the sell/buy functions below */
function haltsTrades() public onlyOwnerOrOps returns (bool success) {
halts = HaltState.Halted;
return true;
}
function unhaltsTrades() public onlyOwnerOrOps returns (bool success) {
halts = HaltState.Unhalted;
return true;
}
function() public payable {
if(msg.sender != owner) {
require(finalized == FinalizableState.Finalized, 'Require smart contract is finalized');
require(halts == HaltState.Unhalted, 'Require smart contract is not halted');
buyPBTTAgainstEther();
}
}
} | ---------------------------------------------------------------------------- PBTT Token Contract ---------------------------------------------------------------------------- Minimal eth balance of sender and recipient, ensure that no account receiving the token has less than the necessary Ether to pay the fees | contract PBTTToken is FinalizableToken, PBTTTokenConfig {
uint256 public minBalanceForAccounts = 0.005 ether;
uint256 public totalTokenSold = 0;
enum HaltState {
Unhalted,
Halted
}
HaltState public halts;
constructor() public
FinalizableToken(TOKEN_NAME, TOKEN_SYMBOL, TOKEN_DECIMALS, TOKEN_TOTALSUPPLY)
{
halts = HaltState.Unhalted;
finalized = FinalizableState.None;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(halts == HaltState.Unhalted, 'Require smart contract is not in halted state');
require(_value >= PBTTForGas, 'Token amount is not enough to transfer');
if (!isOwnerOrOps(msg.sender) && _to == address(this)) {
sellPBTTAgainstEther(_value);
return true;
if(isOwnerOrOps(msg.sender)) {
return super.transferFrom(owner, _to, _value);
}
return super.transfer(_to, _value);
}
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(halts == HaltState.Unhalted, 'Require smart contract is not in halted state');
require(_value >= PBTTForGas, 'Token amount is not enough to transfer');
if (!isOwnerOrOps(msg.sender) && _to == address(this)) {
sellPBTTAgainstEther(_value);
return true;
if(isOwnerOrOps(msg.sender)) {
return super.transferFrom(owner, _to, _value);
}
return super.transfer(_to, _value);
}
}
} else {
function transfer(address _to, uint256 _value) public returns (bool success) {
require(halts == HaltState.Unhalted, 'Require smart contract is not in halted state');
require(_value >= PBTTForGas, 'Token amount is not enough to transfer');
if (!isOwnerOrOps(msg.sender) && _to == address(this)) {
sellPBTTAgainstEther(_value);
return true;
if(isOwnerOrOps(msg.sender)) {
return super.transferFrom(owner, _to, _value);
}
return super.transfer(_to, _value);
}
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(halts == HaltState.Unhalted, 'Require smart contract is not in halted state');
return super.transferFrom(_from, _to, _value);
}
function setEtherPrices(uint256 newBuyPriceEth, uint256 newSellPriceEth) public onlyOwnerOrOps {
buyPriceEth = newBuyPriceEth;
sellPriceEth = newSellPriceEth;
}
function setGasForPBTT(uint256 newGasAmountInWei) public onlyOwnerOrOps {
gasForPBTT = newGasAmountInWei;
}
function setPBTTForGas(uint256 newPBTTAmount) public onlyOwnerOrOps {
PBTTForGas = newPBTTAmount;
}
function setGasReserve(uint256 newGasReserveInWei) public onlyOwnerOrOps {
gasReserve = newGasReserveInWei;
}
function setMinBalance(uint256 minimumBalanceInWei) public onlyOwnerOrOps {
minBalanceForAccounts = minimumBalanceInWei;
}
function getTokenRemaining() public view returns (uint256 total){
return (TOKEN_TOTALSUPPLY.div(DECIMALSFACTOR)).sub(totalTokenSold);
}
function buyPBTTAgainstEther() private returns (uint256 tokenAmount) {
require(buyPriceEth > 0, 'buyPriceEth must be > 0');
require(msg.value >= buyPriceEth, 'Transfer money must be enough for 1 token');
tokenAmount = (msg.value.mul(DECIMALSFACTOR)).div(buyPriceEth);
require(balances[owner] >= tokenAmount, 'Not enough token balance');
balances[msg.sender] = balances[msg.sender].add(tokenAmount);
balances[owner] = balances[owner].sub(tokenAmount);
emit Transfer(owner, msg.sender, tokenAmount);
totalTokenSold = totalTokenSold + tokenAmount;
return tokenAmount;
}
function sellPBTTAgainstEther(uint256 amount) private returns (uint256 revenue) {
require(sellPriceEth > 0, 'sellPriceEth must be > 0');
require(amount >= PBTTForGas, 'Sell token amount must be larger than PBTTForGas value');
require(balances[msg.sender] >= amount, 'Token balance is not enough to sold');
require(msg.sender.balance >= minBalanceForAccounts, 'Seller balance must be enough to pay the transaction fee');
revenue = (amount.div(DECIMALSFACTOR)).mul(sellPriceEth);
uint256 remaining = address(this).balance.sub(revenue);
require(remaining >= gasReserve, 'Remaining contract balance is not enough for reserved');
balances[owner] = balances[owner].add(amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
msg.sender.transfer(revenue);
emit Transfer(msg.sender, owner, amount);
return revenue;
}
function burn(uint256 _amount) public returns (bool success) {
require(_amount > 0, 'Token amount to burn must be larger than 0');
address account = msg.sender;
require(_amount <= balanceOf(account), 'You cannot burn token you dont have');
balances[account] = balances[account].sub(_amount);
totalSupply = totalSupply.sub(_amount);
return true;
}
function reclaimTokens() public onlyOwner returns (bool success) {
address account = address(this);
uint256 amount = balanceOf(account);
if (amount == 0) {
return false;
}
balances[account] = balances[account].sub(amount);
balances[owner] = balances[owner].add(amount);
return true;
}
function reclaimTokens() public onlyOwner returns (bool success) {
address account = address(this);
uint256 amount = balanceOf(account);
if (amount == 0) {
return false;
}
balances[account] = balances[account].sub(amount);
balances[owner] = balances[owner].add(amount);
return true;
}
function withdrawFundToOwner() public onlyOwner {
uint256 eth = address(this).balance;
owner.transfer(eth);
}
function withdrawFundToAddress(address _ownerOtherAdress) public onlyOwner {
uint256 eth = address(this).balance;
_ownerOtherAdress.transfer(eth);
}
function haltsTrades() public onlyOwnerOrOps returns (bool success) {
halts = HaltState.Halted;
return true;
}
function unhaltsTrades() public onlyOwnerOrOps returns (bool success) {
halts = HaltState.Unhalted;
return true;
}
function() public payable {
if(msg.sender != owner) {
require(finalized == FinalizableState.Finalized, 'Require smart contract is finalized');
require(halts == HaltState.Unhalted, 'Require smart contract is not halted');
buyPBTTAgainstEther();
}
}
function() public payable {
if(msg.sender != owner) {
require(finalized == FinalizableState.Finalized, 'Require smart contract is finalized');
require(halts == HaltState.Unhalted, 'Require smart contract is not halted');
buyPBTTAgainstEther();
}
}
} | 1,027,783 | [
1,
5802,
7620,
20819,
1470,
3155,
13456,
8879,
13849,
5444,
2840,
13750,
11013,
434,
5793,
471,
8027,
16,
3387,
716,
1158,
2236,
15847,
326,
1147,
711,
5242,
2353,
326,
4573,
512,
1136,
358,
8843,
326,
1656,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
20819,
1470,
1345,
353,
16269,
6934,
1345,
16,
20819,
1470,
1345,
809,
288,
203,
4202,
203,
203,
565,
2254,
5034,
1071,
1131,
13937,
1290,
13971,
273,
374,
18,
28564,
225,
2437,
31,
8227,
203,
565,
2254,
5034,
1071,
2078,
1345,
55,
1673,
273,
374,
31,
203,
377,
203,
565,
2792,
670,
2390,
1119,
288,
7010,
3639,
1351,
22314,
2344,
16,
203,
3639,
670,
287,
2344,
540,
203,
565,
289,
203,
203,
565,
670,
2390,
1119,
1071,
18389,
87,
31,
203,
203,
565,
3885,
1435,
1071,
203,
3639,
16269,
6934,
1345,
12,
8412,
67,
1985,
16,
14275,
67,
22093,
16,
14275,
67,
23816,
55,
16,
14275,
67,
28624,
13272,
23893,
13,
203,
565,
288,
203,
3639,
18389,
87,
273,
670,
2390,
1119,
18,
984,
22314,
2344,
31,
203,
3639,
727,
1235,
273,
16269,
6934,
1119,
18,
7036,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
2583,
12,
76,
2390,
87,
422,
670,
2390,
1119,
18,
984,
22314,
2344,
16,
296,
8115,
13706,
6835,
353,
486,
316,
19514,
2344,
919,
8284,
203,
203,
3639,
2583,
24899,
1132,
1545,
20819,
1470,
1290,
27998,
16,
296,
1345,
3844,
353,
486,
7304,
358,
7412,
8284,
7010,
1850,
203,
3639,
309,
16051,
291,
5541,
1162,
8132,
12,
3576,
18,
15330,
13,
597,
389,
869,
422,
1758,
12,
2211,
3719,
288,
203,
5411,
357,
80,
20724,
1470,
23530,
334,
41,
1136,
24899,
1132,
1769,
17311,
203,
5411,
327,
638,
31,
2
] |
./partial_match/1/0xc612a114eDc487AcBd09538e5668c6B94C800CEb/sources/PEPEXToken.sol | * @dev Interface of the ERC20 standard as defined in the EIP./ | interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
pragma solidity ^0.8.0;
}
| 15,534,135 | [
1,
1358,
434,
326,
4232,
39,
3462,
4529,
487,
2553,
316,
326,
512,
2579,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
654,
39,
3462,
288,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
7412,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
1135,
261,
6430,
1769,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0x96C92C59A182EBBdfDa5a2d4B15e28f95631414B/sources/Moon.sol | * @notice Constructs the Basis Bond ERC-20 contract./ | constructor() public ERC20('MOON', 'MOON') {
_mint(msg.sender, 10**7 * (10**18));
}
| 11,212,648 | [
1,
13262,
326,
605,
17247,
605,
1434,
4232,
39,
17,
3462,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1071,
4232,
39,
3462,
2668,
5980,
673,
2187,
296,
5980,
673,
6134,
288,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
1728,
636,
27,
380,
261,
2163,
636,
2643,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
import "./FishBreeding.sol";
/// @title all functions related to creating fishs
contract FishMinting is FishBreeding {
// Limits the number of fishs the contract owner can ever create.
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_CREATION_LIMIT = 45000;
// Constants for gen0 auctions.
uint256 public constant GEN0_STARTING_PRICE = 10 finney;
// Counts the number of fishs the contract owner has created.
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
/// @dev we can create promo fishs, up to a limit. Only callable by COO
/// @param _genes the encoded genes of the fish to be created, any value is accepted
/// @param _owner the future owner of the created fishs. Default to contract COO
function createPromofish(uint256 _genes, address _owner) external onlyOwner {
address fishOwner = _owner;
if (fishOwner == address(0)) {
fishOwner = owner;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createFish(_genes,0, 0, 0, fishOwner);
}
/// @dev Creates a new gen0 fish with the given genes and
/// creates an auction for it.
function createGen0Sale(uint256 _genes) external onlyOwner {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint256 fishId = _createFish(_genes,0, 0, 0, address(this));
_createSale(
fishId,
_computeNextGen0Price(),
address(this)
);
gen0CreatedCount++;
}
/// @dev Creates a new gen0 fish with the random given genes and
/// creates an auction for it.
function createRandomGen0Sale() external onlyOwner {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint256 _genes = uint256(keccak256(block.number, block.timestamp));
uint256 fishId = _createFish(_genes,0, 0, 0, address(this));
_createSale(
fishId,
_computeNextGen0Price(),
address(this)
);
gen0CreatedCount++;
}
/// @dev Computes the next gen0 auction starting price, given
/// the average of the past 5 prices + 50%.
function _computeNextGen0Price() internal view returns (uint256) {
uint256 avePrice = averageGen0SalePrice();
// Sanity check to ensure we don't overflow arithmetic
require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
// We never auction for less than starting price
if (nextPrice < GEN0_STARTING_PRICE) {
nextPrice = GEN0_STARTING_PRICE;
}
return nextPrice;
}
} | @dev we can create promo fishs, up to a limit. Only callable by COO @param _genes the encoded genes of the fish to be created, any value is accepted @param _owner the future owner of the created fishs. Default to contract COO | function createPromofish(uint256 _genes, address _owner) external onlyOwner {
address fishOwner = _owner;
if (fishOwner == address(0)) {
fishOwner = owner;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createFish(_genes,0, 0, 0, fishOwner);
}
| 5,525,538 | [
1,
1814,
848,
752,
3012,
83,
284,
1468,
87,
16,
731,
358,
279,
1800,
18,
5098,
4140,
635,
7910,
51,
225,
389,
18036,
326,
3749,
11423,
434,
326,
284,
1468,
358,
506,
2522,
16,
1281,
460,
353,
8494,
225,
389,
8443,
326,
3563,
3410,
434,
326,
2522,
284,
1468,
87,
18,
2989,
358,
6835,
7910,
51,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
752,
13224,
792,
1468,
12,
11890,
5034,
389,
18036,
16,
1758,
389,
8443,
13,
3903,
1338,
5541,
288,
203,
3639,
1758,
284,
1468,
5541,
273,
389,
8443,
31,
203,
3639,
309,
261,
22905,
5541,
422,
1758,
12,
20,
3719,
288,
203,
5411,
284,
1468,
5541,
273,
3410,
31,
203,
3639,
289,
203,
3639,
2583,
12,
17401,
83,
6119,
1380,
411,
453,
3942,
51,
67,
5458,
2689,
67,
8283,
1769,
203,
203,
3639,
3012,
83,
6119,
1380,
9904,
31,
203,
3639,
389,
2640,
42,
1468,
24899,
18036,
16,
20,
16,
374,
16,
374,
16,
284,
1468,
5541,
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
] |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./lib/ReEncryptionValidator.sol";
import "./lib/SignatureVerifier.sol";
import "./StakingEscrow.sol";
import "./proxy/Upgradeable.sol";
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/math/Math.sol";
/**
* @title Adjudicator
* @notice Supervises stakers' behavior and punishes when something's wrong.
* @dev |v2.1.2|
*/
contract Adjudicator is Upgradeable {
using SafeMath for uint256;
using UmbralDeserializer for bytes;
event CFragEvaluated(
bytes32 indexed evaluationHash,
address indexed investigator,
bool correctness
);
event IncorrectCFragVerdict(
bytes32 indexed evaluationHash,
address indexed worker,
address indexed staker
);
// used only for upgrading
bytes32 constant RESERVED_CAPSULE_AND_CFRAG_BYTES = bytes32(0);
address constant RESERVED_ADDRESS = address(0);
StakingEscrow public immutable escrow;
SignatureVerifier.HashAlgorithm public immutable hashAlgorithm;
uint256 public immutable basePenalty;
uint256 public immutable penaltyHistoryCoefficient;
uint256 public immutable percentagePenaltyCoefficient;
uint256 public immutable rewardCoefficient;
mapping (address => uint256) public penaltyHistory;
mapping (bytes32 => bool) public evaluatedCFrags;
/**
* @param _escrow Escrow contract
* @param _hashAlgorithm Hashing algorithm
* @param _basePenalty Base for the penalty calculation
* @param _penaltyHistoryCoefficient Coefficient for calculating the penalty depending on the history
* @param _percentagePenaltyCoefficient Coefficient for calculating the percentage penalty
* @param _rewardCoefficient Coefficient for calculating the reward
*/
constructor(
StakingEscrow _escrow,
SignatureVerifier.HashAlgorithm _hashAlgorithm,
uint256 _basePenalty,
uint256 _penaltyHistoryCoefficient,
uint256 _percentagePenaltyCoefficient,
uint256 _rewardCoefficient
) {
// Sanity checks.
require(_escrow.secondsPerPeriod() > 0 && // This contract has an escrow, and it's not the null address.
// The reward and penalty coefficients are set.
_percentagePenaltyCoefficient != 0 &&
_rewardCoefficient != 0);
escrow = _escrow;
hashAlgorithm = _hashAlgorithm;
basePenalty = _basePenalty;
percentagePenaltyCoefficient = _percentagePenaltyCoefficient;
penaltyHistoryCoefficient = _penaltyHistoryCoefficient;
rewardCoefficient = _rewardCoefficient;
}
/**
* @notice Submit proof that a worker created wrong CFrag
* @param _capsuleBytes Serialized capsule
* @param _cFragBytes Serialized CFrag
* @param _cFragSignature Signature of CFrag by worker
* @param _taskSignature Signature of task specification by Bob
* @param _requesterPublicKey Bob's signing public key, also known as "stamp"
* @param _workerPublicKey Worker's signing public key, also known as "stamp"
* @param _workerIdentityEvidence Signature of worker's public key by worker's eth-key
* @param _preComputedData Additional pre-computed data for CFrag correctness verification
*/
function evaluateCFrag(
bytes memory _capsuleBytes,
bytes memory _cFragBytes,
bytes memory _cFragSignature,
bytes memory _taskSignature,
bytes memory _requesterPublicKey,
bytes memory _workerPublicKey,
bytes memory _workerIdentityEvidence,
bytes memory _preComputedData
)
public
{
// 1. Check that CFrag is not evaluated yet
bytes32 evaluationHash = SignatureVerifier.hash(
abi.encodePacked(_capsuleBytes, _cFragBytes), hashAlgorithm);
require(!evaluatedCFrags[evaluationHash], "This CFrag has already been evaluated.");
evaluatedCFrags[evaluationHash] = true;
// 2. Verify correctness of re-encryption
bool cFragIsCorrect = ReEncryptionValidator.validateCFrag(_capsuleBytes, _cFragBytes, _preComputedData);
emit CFragEvaluated(evaluationHash, msg.sender, cFragIsCorrect);
// 3. Verify associated public keys and signatures
require(ReEncryptionValidator.checkSerializedCoordinates(_workerPublicKey),
"Staker's public key is invalid");
require(ReEncryptionValidator.checkSerializedCoordinates(_requesterPublicKey),
"Requester's public key is invalid");
UmbralDeserializer.PreComputedData memory precomp = _preComputedData.toPreComputedData();
// Verify worker's signature of CFrag
require(SignatureVerifier.verify(
_cFragBytes,
abi.encodePacked(_cFragSignature, precomp.lostBytes[1]),
_workerPublicKey,
hashAlgorithm),
"CFrag signature is invalid"
);
// Verify worker's signature of taskSignature and that it corresponds to cfrag.proof.metadata
UmbralDeserializer.CapsuleFrag memory cFrag = _cFragBytes.toCapsuleFrag();
require(SignatureVerifier.verify(
_taskSignature,
abi.encodePacked(cFrag.proof.metadata, precomp.lostBytes[2]),
_workerPublicKey,
hashAlgorithm),
"Task signature is invalid"
);
// Verify that _taskSignature is bob's signature of the task specification.
// A task specification is: capsule + ursula pubkey + alice address + blockhash
bytes32 stampXCoord;
assembly {
stampXCoord := mload(add(_workerPublicKey, 32))
}
bytes memory stamp = abi.encodePacked(precomp.lostBytes[4], stampXCoord);
require(SignatureVerifier.verify(
abi.encodePacked(_capsuleBytes,
stamp,
_workerIdentityEvidence,
precomp.alicesKeyAsAddress,
bytes32(0)),
abi.encodePacked(_taskSignature, precomp.lostBytes[3]),
_requesterPublicKey,
hashAlgorithm),
"Specification signature is invalid"
);
// 4. Extract worker address from stamp signature.
address worker = SignatureVerifier.recover(
SignatureVerifier.hashEIP191(stamp, byte(0x45)), // Currently, we use version E (0x45) of EIP191 signatures
_workerIdentityEvidence);
address staker = escrow.stakerFromWorker(worker);
require(staker != address(0), "Worker must be related to a staker");
// 5. Check that staker can be slashed
uint256 stakerValue = escrow.getAllTokens(staker);
require(stakerValue > 0, "Staker has no tokens");
// 6. If CFrag was incorrect, slash staker
if (!cFragIsCorrect) {
(uint256 penalty, uint256 reward) = calculatePenaltyAndReward(staker, stakerValue);
escrow.slashStaker(staker, penalty, msg.sender, reward);
emit IncorrectCFragVerdict(evaluationHash, worker, staker);
}
}
/**
* @notice Calculate penalty to the staker and reward to the investigator
* @param _staker Staker's address
* @param _stakerValue Amount of tokens that belong to the staker
*/
function calculatePenaltyAndReward(address _staker, uint256 _stakerValue)
internal returns (uint256 penalty, uint256 reward)
{
penalty = basePenalty.add(penaltyHistoryCoefficient.mul(penaltyHistory[_staker]));
penalty = Math.min(penalty, _stakerValue.div(percentagePenaltyCoefficient));
reward = penalty.div(rewardCoefficient);
// TODO add maximum condition or other overflow protection or other penalty condition (#305?)
penaltyHistory[_staker] = penaltyHistory[_staker].add(1);
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
bytes32 evaluationCFragHash = SignatureVerifier.hash(
abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256);
require(delegateGet(_testTarget, this.evaluatedCFrags.selector, evaluationCFragHash) ==
(evaluatedCFrags[evaluationCFragHash] ? 1 : 0));
require(delegateGet(_testTarget, this.penaltyHistory.selector, bytes32(bytes20(RESERVED_ADDRESS))) ==
penaltyHistory[RESERVED_ADDRESS]);
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade`
function finishUpgrade(address _target) public override virtual {
super.finishUpgrade(_target);
// preparation for the verifyState method
bytes32 evaluationCFragHash = SignatureVerifier.hash(
abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256);
evaluatedCFrags[evaluationCFragHash] = true;
penaltyHistory[RESERVED_ADDRESS] = 123;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./UmbralDeserializer.sol";
import "./SignatureVerifier.sol";
/**
* @notice Validates re-encryption correctness.
*/
library ReEncryptionValidator {
using UmbralDeserializer for bytes;
//------------------------------//
// Umbral-specific constants //
//------------------------------//
// See parameter `u` of `UmbralParameters` class in pyUmbral
// https://github.com/nucypher/pyUmbral/blob/master/umbral/params.py
uint8 public constant UMBRAL_PARAMETER_U_SIGN = 0x02;
uint256 public constant UMBRAL_PARAMETER_U_XCOORD = 0x03c98795773ff1c241fc0b1cced85e80f8366581dda5c9452175ebd41385fa1f;
uint256 public constant UMBRAL_PARAMETER_U_YCOORD = 0x7880ed56962d7c0ae44d6f14bb53b5fe64b31ea44a41d0316f3a598778f0f936;
//------------------------------//
// SECP256K1-specific constants //
//------------------------------//
// Base field order
uint256 constant FIELD_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
// -2 mod FIELD_ORDER
uint256 constant MINUS_2 = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2d;
// (-1/2) mod FIELD_ORDER
uint256 constant MINUS_ONE_HALF = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff7ffffe17;
//
/**
* @notice Check correctness of re-encryption
* @param _capsuleBytes Capsule
* @param _cFragBytes Capsule frag
* @param _precomputedBytes Additional precomputed data
*/
function validateCFrag(
bytes memory _capsuleBytes,
bytes memory _cFragBytes,
bytes memory _precomputedBytes
)
internal pure returns (bool)
{
UmbralDeserializer.Capsule memory _capsule = _capsuleBytes.toCapsule();
UmbralDeserializer.CapsuleFrag memory _cFrag = _cFragBytes.toCapsuleFrag();
UmbralDeserializer.PreComputedData memory _precomputed = _precomputedBytes.toPreComputedData();
// Extract Alice's address and check that it corresponds to the one provided
address alicesAddress = SignatureVerifier.recover(
_precomputed.hashedKFragValidityMessage,
abi.encodePacked(_cFrag.proof.kFragSignature, _precomputed.lostBytes[0])
);
require(alicesAddress == _precomputed.alicesKeyAsAddress, "Bad KFrag signature");
// Compute proof's challenge scalar h, used in all ZKP verification equations
uint256 h = computeProofChallengeScalar(_capsule, _cFrag);
//////
// Verifying 1st equation: z*E == h*E_1 + E_2
//////
// Input validation: E
require(checkCompressedPoint(
_capsule.pointE.sign,
_capsule.pointE.xCoord,
_precomputed.pointEyCoord),
"Precomputed Y coordinate of E doesn't correspond to compressed E point"
);
// Input validation: z*E
require(isOnCurve(_precomputed.pointEZxCoord, _precomputed.pointEZyCoord),
"Point zE is not a valid EC point"
);
require(ecmulVerify(
_capsule.pointE.xCoord, // E_x
_precomputed.pointEyCoord, // E_y
_cFrag.proof.bnSig, // z
_precomputed.pointEZxCoord, // zE_x
_precomputed.pointEZyCoord), // zE_y
"Precomputed z*E value is incorrect"
);
// Input validation: E1
require(checkCompressedPoint(
_cFrag.pointE1.sign, // E1_sign
_cFrag.pointE1.xCoord, // E1_x
_precomputed.pointE1yCoord), // E1_y
"Precomputed Y coordinate of E1 doesn't correspond to compressed E1 point"
);
// Input validation: h*E1
require(isOnCurve(_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord),
"Point h*E1 is not a valid EC point"
);
require(ecmulVerify(
_cFrag.pointE1.xCoord, // E1_x
_precomputed.pointE1yCoord, // E1_y
h,
_precomputed.pointE1HxCoord, // hE1_x
_precomputed.pointE1HyCoord), // hE1_y
"Precomputed h*E1 value is incorrect"
);
// Input validation: E2
require(checkCompressedPoint(
_cFrag.proof.pointE2.sign, // E2_sign
_cFrag.proof.pointE2.xCoord, // E2_x
_precomputed.pointE2yCoord), // E2_y
"Precomputed Y coordinate of E2 doesn't correspond to compressed E2 point"
);
bool equation_holds = eqAffineJacobian(
[_precomputed.pointEZxCoord, _precomputed.pointEZyCoord],
addAffineJacobian(
[_cFrag.proof.pointE2.xCoord, _precomputed.pointE2yCoord],
[_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord]
)
);
if (!equation_holds){
return false;
}
//////
// Verifying 2nd equation: z*V == h*V_1 + V_2
//////
// Input validation: V
require(checkCompressedPoint(
_capsule.pointV.sign,
_capsule.pointV.xCoord,
_precomputed.pointVyCoord),
"Precomputed Y coordinate of V doesn't correspond to compressed V point"
);
// Input validation: z*V
require(isOnCurve(_precomputed.pointVZxCoord, _precomputed.pointVZyCoord),
"Point zV is not a valid EC point"
);
require(ecmulVerify(
_capsule.pointV.xCoord, // V_x
_precomputed.pointVyCoord, // V_y
_cFrag.proof.bnSig, // z
_precomputed.pointVZxCoord, // zV_x
_precomputed.pointVZyCoord), // zV_y
"Precomputed z*V value is incorrect"
);
// Input validation: V1
require(checkCompressedPoint(
_cFrag.pointV1.sign, // V1_sign
_cFrag.pointV1.xCoord, // V1_x
_precomputed.pointV1yCoord), // V1_y
"Precomputed Y coordinate of V1 doesn't correspond to compressed V1 point"
);
// Input validation: h*V1
require(isOnCurve(_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord),
"Point h*V1 is not a valid EC point"
);
require(ecmulVerify(
_cFrag.pointV1.xCoord, // V1_x
_precomputed.pointV1yCoord, // V1_y
h,
_precomputed.pointV1HxCoord, // h*V1_x
_precomputed.pointV1HyCoord), // h*V1_y
"Precomputed h*V1 value is incorrect"
);
// Input validation: V2
require(checkCompressedPoint(
_cFrag.proof.pointV2.sign, // V2_sign
_cFrag.proof.pointV2.xCoord, // V2_x
_precomputed.pointV2yCoord), // V2_y
"Precomputed Y coordinate of V2 doesn't correspond to compressed V2 point"
);
equation_holds = eqAffineJacobian(
[_precomputed.pointVZxCoord, _precomputed.pointVZyCoord],
addAffineJacobian(
[_cFrag.proof.pointV2.xCoord, _precomputed.pointV2yCoord],
[_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord]
)
);
if (!equation_holds){
return false;
}
//////
// Verifying 3rd equation: z*U == h*U_1 + U_2
//////
// We don't have to validate U since it's fixed and hard-coded
// Input validation: z*U
require(isOnCurve(_precomputed.pointUZxCoord, _precomputed.pointUZyCoord),
"Point z*U is not a valid EC point"
);
require(ecmulVerify(
UMBRAL_PARAMETER_U_XCOORD, // U_x
UMBRAL_PARAMETER_U_YCOORD, // U_y
_cFrag.proof.bnSig, // z
_precomputed.pointUZxCoord, // zU_x
_precomputed.pointUZyCoord), // zU_y
"Precomputed z*U value is incorrect"
);
// Input validation: U1 (a.k.a. KFragCommitment)
require(checkCompressedPoint(
_cFrag.proof.pointKFragCommitment.sign, // U1_sign
_cFrag.proof.pointKFragCommitment.xCoord, // U1_x
_precomputed.pointU1yCoord), // U1_y
"Precomputed Y coordinate of U1 doesn't correspond to compressed U1 point"
);
// Input validation: h*U1
require(isOnCurve(_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord),
"Point h*U1 is not a valid EC point"
);
require(ecmulVerify(
_cFrag.proof.pointKFragCommitment.xCoord, // U1_x
_precomputed.pointU1yCoord, // U1_y
h,
_precomputed.pointU1HxCoord, // h*V1_x
_precomputed.pointU1HyCoord), // h*V1_y
"Precomputed h*V1 value is incorrect"
);
// Input validation: U2 (a.k.a. KFragPok ("proof of knowledge"))
require(checkCompressedPoint(
_cFrag.proof.pointKFragPok.sign, // U2_sign
_cFrag.proof.pointKFragPok.xCoord, // U2_x
_precomputed.pointU2yCoord), // U2_y
"Precomputed Y coordinate of U2 doesn't correspond to compressed U2 point"
);
equation_holds = eqAffineJacobian(
[_precomputed.pointUZxCoord, _precomputed.pointUZyCoord],
addAffineJacobian(
[_cFrag.proof.pointKFragPok.xCoord, _precomputed.pointU2yCoord],
[_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord]
)
);
return equation_holds;
}
function computeProofChallengeScalar(
UmbralDeserializer.Capsule memory _capsule,
UmbralDeserializer.CapsuleFrag memory _cFrag
) internal pure returns (uint256) {
// Compute h = hash_to_bignum(e, e1, e2, v, v1, v2, u, u1, u2, metadata)
bytes memory hashInput = abi.encodePacked(
// Point E
_capsule.pointE.sign,
_capsule.pointE.xCoord,
// Point E1
_cFrag.pointE1.sign,
_cFrag.pointE1.xCoord,
// Point E2
_cFrag.proof.pointE2.sign,
_cFrag.proof.pointE2.xCoord
);
hashInput = abi.encodePacked(
hashInput,
// Point V
_capsule.pointV.sign,
_capsule.pointV.xCoord,
// Point V1
_cFrag.pointV1.sign,
_cFrag.pointV1.xCoord,
// Point V2
_cFrag.proof.pointV2.sign,
_cFrag.proof.pointV2.xCoord
);
hashInput = abi.encodePacked(
hashInput,
// Point U
bytes1(UMBRAL_PARAMETER_U_SIGN),
bytes32(UMBRAL_PARAMETER_U_XCOORD),
// Point U1
_cFrag.proof.pointKFragCommitment.sign,
_cFrag.proof.pointKFragCommitment.xCoord,
// Point U2
_cFrag.proof.pointKFragPok.sign,
_cFrag.proof.pointKFragPok.xCoord,
// Re-encryption metadata
_cFrag.proof.metadata
);
uint256 h = extendedKeccakToBN(hashInput);
return h;
}
function extendedKeccakToBN (bytes memory _data) internal pure returns (uint256) {
bytes32 upper;
bytes32 lower;
// Umbral prepends to the data a customization string of 64-bytes.
// In the case of hash_to_curvebn is 'hash_to_curvebn', padded with zeroes.
bytes memory input = abi.encodePacked(bytes32("hash_to_curvebn"), bytes32(0x00), _data);
(upper, lower) = (keccak256(abi.encodePacked(uint8(0x00), input)),
keccak256(abi.encodePacked(uint8(0x01), input)));
// Let n be the order of secp256k1's group (n = 2^256 - 0x1000003D1)
// n_minus_1 = n - 1
// delta = 2^256 mod n_minus_1
uint256 delta = 0x14551231950b75fc4402da1732fc9bec0;
uint256 n_minus_1 = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140;
uint256 upper_half = mulmod(uint256(upper), delta, n_minus_1);
return 1 + addmod(upper_half, uint256(lower), n_minus_1);
}
/// @notice Tests if a compressed point is valid, wrt to its corresponding Y coordinate
/// @param _pointSign The sign byte from the compressed notation: 0x02 if the Y coord is even; 0x03 otherwise
/// @param _pointX The X coordinate of an EC point in affine representation
/// @param _pointY The Y coordinate of an EC point in affine representation
/// @return true iff _pointSign and _pointX are the compressed representation of (_pointX, _pointY)
function checkCompressedPoint(
uint8 _pointSign,
uint256 _pointX,
uint256 _pointY
) internal pure returns(bool) {
bool correct_sign = _pointY % 2 == _pointSign - 2;
return correct_sign && isOnCurve(_pointX, _pointY);
}
/// @notice Tests if the given serialized coordinates represent a valid EC point
/// @param _coords The concatenation of serialized X and Y coordinates
/// @return true iff coordinates X and Y are a valid point
function checkSerializedCoordinates(bytes memory _coords) internal pure returns(bool) {
require(_coords.length == 64, "Serialized coordinates should be 64 B");
uint256 coordX;
uint256 coordY;
assembly {
coordX := mload(add(_coords, 32))
coordY := mload(add(_coords, 64))
}
return isOnCurve(coordX, coordY);
}
/// @notice Tests if a point is on the secp256k1 curve
/// @param Px The X coordinate of an EC point in affine representation
/// @param Py The Y coordinate of an EC point in affine representation
/// @return true if (Px, Py) is a valid secp256k1 point; false otherwise
function isOnCurve(uint256 Px, uint256 Py) internal pure returns (bool) {
uint256 p = FIELD_ORDER;
if (Px >= p || Py >= p){
return false;
}
uint256 y2 = mulmod(Py, Py, p);
uint256 x3_plus_7 = addmod(mulmod(mulmod(Px, Px, p), Px, p), 7, p);
return y2 == x3_plus_7;
}
// https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/4
function ecmulVerify(
uint256 x1,
uint256 y1,
uint256 scalar,
uint256 qx,
uint256 qy
) internal pure returns(bool) {
uint256 curve_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
address signer = ecrecover(0, uint8(27 + (y1 % 2)), bytes32(x1), bytes32(mulmod(scalar, x1, curve_order)));
address xyAddress = address(uint256(keccak256(abi.encodePacked(qx, qy))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return xyAddress == signer;
}
/// @notice Equality test of two points, in affine and Jacobian coordinates respectively
/// @param P An EC point in affine coordinates
/// @param Q An EC point in Jacobian coordinates
/// @return true if P and Q represent the same point in affine coordinates; false otherwise
function eqAffineJacobian(
uint256[2] memory P,
uint256[3] memory Q
) internal pure returns(bool){
uint256 Qz = Q[2];
if(Qz == 0){
return false; // Q is zero but P isn't.
}
uint256 p = FIELD_ORDER;
uint256 Q_z_squared = mulmod(Qz, Qz, p);
return mulmod(P[0], Q_z_squared, p) == Q[0] && mulmod(P[1], mulmod(Q_z_squared, Qz, p), p) == Q[1];
}
/// @notice Adds two points in affine coordinates, with the result in Jacobian
/// @dev Based on the addition formulas from http://www.hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/addition/add-2001-b.op3
/// @param P An EC point in affine coordinates
/// @param Q An EC point in affine coordinates
/// @return R An EC point in Jacobian coordinates with the sum, represented by an array of 3 uint256
function addAffineJacobian(
uint[2] memory P,
uint[2] memory Q
) internal pure returns (uint[3] memory R) {
uint256 p = FIELD_ORDER;
uint256 a = P[0];
uint256 c = P[1];
uint256 t0 = Q[0];
uint256 t1 = Q[1];
if ((a == t0) && (c == t1)){
return doubleJacobian([a, c, 1]);
}
uint256 d = addmod(t1, p-c, p); // d = t1 - c
uint256 b = addmod(t0, p-a, p); // b = t0 - a
uint256 e = mulmod(b, b, p); // e = b^2
uint256 f = mulmod(e, b, p); // f = b^3
uint256 g = mulmod(a, e, p);
R[0] = addmod(mulmod(d, d, p), p-addmod(mulmod(2, g, p), f, p), p);
R[1] = addmod(mulmod(d, addmod(g, p-R[0], p), p), p-mulmod(c, f, p), p);
R[2] = b;
}
/// @notice Point doubling in Jacobian coordinates
/// @param P An EC point in Jacobian coordinates.
/// @return Q An EC point in Jacobian coordinates
function doubleJacobian(uint[3] memory P) internal pure returns (uint[3] memory Q) {
uint256 z = P[2];
if (z == 0)
return Q;
uint256 p = FIELD_ORDER;
uint256 x = P[0];
uint256 _2y = mulmod(2, P[1], p);
uint256 _4yy = mulmod(_2y, _2y, p);
uint256 s = mulmod(_4yy, x, p);
uint256 m = mulmod(3, mulmod(x, x, p), p);
uint256 t = addmod(mulmod(m, m, p), mulmod(MINUS_2, s, p),p);
Q[0] = t;
Q[1] = addmod(mulmod(m, addmod(s, p - t, p), p), mulmod(MINUS_ONE_HALF, mulmod(_4yy, _4yy, p), p), p);
Q[2] = mulmod(_2y, z, p);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @notice Deserialization library for Umbral objects
*/
library UmbralDeserializer {
struct Point {
uint8 sign;
uint256 xCoord;
}
struct Capsule {
Point pointE;
Point pointV;
uint256 bnSig;
}
struct CorrectnessProof {
Point pointE2;
Point pointV2;
Point pointKFragCommitment;
Point pointKFragPok;
uint256 bnSig;
bytes kFragSignature; // 64 bytes
bytes metadata; // any length
}
struct CapsuleFrag {
Point pointE1;
Point pointV1;
bytes32 kFragId;
Point pointPrecursor;
CorrectnessProof proof;
}
struct PreComputedData {
uint256 pointEyCoord;
uint256 pointEZxCoord;
uint256 pointEZyCoord;
uint256 pointE1yCoord;
uint256 pointE1HxCoord;
uint256 pointE1HyCoord;
uint256 pointE2yCoord;
uint256 pointVyCoord;
uint256 pointVZxCoord;
uint256 pointVZyCoord;
uint256 pointV1yCoord;
uint256 pointV1HxCoord;
uint256 pointV1HyCoord;
uint256 pointV2yCoord;
uint256 pointUZxCoord;
uint256 pointUZyCoord;
uint256 pointU1yCoord;
uint256 pointU1HxCoord;
uint256 pointU1HyCoord;
uint256 pointU2yCoord;
bytes32 hashedKFragValidityMessage;
address alicesKeyAsAddress;
bytes5 lostBytes;
}
uint256 constant BIGNUM_SIZE = 32;
uint256 constant POINT_SIZE = 33;
uint256 constant SIGNATURE_SIZE = 64;
uint256 constant CAPSULE_SIZE = 2 * POINT_SIZE + BIGNUM_SIZE;
uint256 constant CORRECTNESS_PROOF_SIZE = 4 * POINT_SIZE + BIGNUM_SIZE + SIGNATURE_SIZE;
uint256 constant CAPSULE_FRAG_SIZE = 3 * POINT_SIZE + BIGNUM_SIZE;
uint256 constant FULL_CAPSULE_FRAG_SIZE = CAPSULE_FRAG_SIZE + CORRECTNESS_PROOF_SIZE;
uint256 constant PRECOMPUTED_DATA_SIZE = (20 * BIGNUM_SIZE) + 32 + 20 + 5;
/**
* @notice Deserialize to capsule (not activated)
*/
function toCapsule(bytes memory _capsuleBytes)
internal pure returns (Capsule memory capsule)
{
require(_capsuleBytes.length == CAPSULE_SIZE);
uint256 pointer = getPointer(_capsuleBytes);
pointer = copyPoint(pointer, capsule.pointE);
pointer = copyPoint(pointer, capsule.pointV);
capsule.bnSig = uint256(getBytes32(pointer));
}
/**
* @notice Deserialize to correctness proof
* @param _pointer Proof bytes memory pointer
* @param _proofBytesLength Proof bytes length
*/
function toCorrectnessProof(uint256 _pointer, uint256 _proofBytesLength)
internal pure returns (CorrectnessProof memory proof)
{
require(_proofBytesLength >= CORRECTNESS_PROOF_SIZE);
_pointer = copyPoint(_pointer, proof.pointE2);
_pointer = copyPoint(_pointer, proof.pointV2);
_pointer = copyPoint(_pointer, proof.pointKFragCommitment);
_pointer = copyPoint(_pointer, proof.pointKFragPok);
proof.bnSig = uint256(getBytes32(_pointer));
_pointer += BIGNUM_SIZE;
proof.kFragSignature = new bytes(SIGNATURE_SIZE);
// TODO optimize, just two mload->mstore (#1500)
_pointer = copyBytes(_pointer, proof.kFragSignature, SIGNATURE_SIZE);
if (_proofBytesLength > CORRECTNESS_PROOF_SIZE) {
proof.metadata = new bytes(_proofBytesLength - CORRECTNESS_PROOF_SIZE);
copyBytes(_pointer, proof.metadata, proof.metadata.length);
}
}
/**
* @notice Deserialize to correctness proof
*/
function toCorrectnessProof(bytes memory _proofBytes)
internal pure returns (CorrectnessProof memory proof)
{
uint256 pointer = getPointer(_proofBytes);
return toCorrectnessProof(pointer, _proofBytes.length);
}
/**
* @notice Deserialize to CapsuleFrag
*/
function toCapsuleFrag(bytes memory _cFragBytes)
internal pure returns (CapsuleFrag memory cFrag)
{
uint256 cFragBytesLength = _cFragBytes.length;
require(cFragBytesLength >= FULL_CAPSULE_FRAG_SIZE);
uint256 pointer = getPointer(_cFragBytes);
pointer = copyPoint(pointer, cFrag.pointE1);
pointer = copyPoint(pointer, cFrag.pointV1);
cFrag.kFragId = getBytes32(pointer);
pointer += BIGNUM_SIZE;
pointer = copyPoint(pointer, cFrag.pointPrecursor);
cFrag.proof = toCorrectnessProof(pointer, cFragBytesLength - CAPSULE_FRAG_SIZE);
}
/**
* @notice Deserialize to precomputed data
*/
function toPreComputedData(bytes memory _preComputedData)
internal pure returns (PreComputedData memory data)
{
require(_preComputedData.length == PRECOMPUTED_DATA_SIZE);
uint256 initial_pointer = getPointer(_preComputedData);
uint256 pointer = initial_pointer;
data.pointEyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointEZxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointEZyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointE1yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointE1HxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointE1HyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointE2yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointVyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointVZxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointVZyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointV1yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointV1HxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointV1HyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointV2yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointUZxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointUZyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointU1yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointU1HxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointU1HyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointU2yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.hashedKFragValidityMessage = getBytes32(pointer);
pointer += 32;
data.alicesKeyAsAddress = address(bytes20(getBytes32(pointer)));
pointer += 20;
// Lost bytes: a bytes5 variable holding the following byte values:
// 0: kfrag signature recovery value v
// 1: cfrag signature recovery value v
// 2: metadata signature recovery value v
// 3: specification signature recovery value v
// 4: ursula pubkey sign byte
data.lostBytes = bytes5(getBytes32(pointer));
pointer += 5;
require(pointer == initial_pointer + PRECOMPUTED_DATA_SIZE);
}
// TODO extract to external library if needed (#1500)
/**
* @notice Get the memory pointer for start of array
*/
function getPointer(bytes memory _bytes) internal pure returns (uint256 pointer) {
assembly {
pointer := add(_bytes, 32) // skip array length
}
}
/**
* @notice Copy point data from memory in the pointer position
*/
function copyPoint(uint256 _pointer, Point memory _point)
internal pure returns (uint256 resultPointer)
{
// TODO optimize, copy to point memory directly (#1500)
uint8 temp;
uint256 xCoord;
assembly {
temp := byte(0, mload(_pointer))
xCoord := mload(add(_pointer, 1))
}
_point.sign = temp;
_point.xCoord = xCoord;
resultPointer = _pointer + POINT_SIZE;
}
/**
* @notice Read 1 byte from memory in the pointer position
*/
function getByte(uint256 _pointer) internal pure returns (byte result) {
bytes32 word;
assembly {
word := mload(_pointer)
}
result = word[0];
return result;
}
/**
* @notice Read 32 bytes from memory in the pointer position
*/
function getBytes32(uint256 _pointer) internal pure returns (bytes32 result) {
assembly {
result := mload(_pointer)
}
}
/**
* @notice Copy bytes from the source pointer to the target array
* @dev Assumes that enough memory has been allocated to store in target.
* Also assumes that '_target' was the last thing that was allocated
* @param _bytesPointer Source memory pointer
* @param _target Target array
* @param _bytesLength Number of bytes to copy
*/
function copyBytes(uint256 _bytesPointer, bytes memory _target, uint256 _bytesLength)
internal
pure
returns (uint256 resultPointer)
{
// Exploiting the fact that '_target' was the last thing to be allocated,
// we can write entire words, and just overwrite any excess.
assembly {
// evm operations on words
let words := div(add(_bytesLength, 31), 32)
let source := _bytesPointer
let destination := add(_target, 32)
for
{ let i := 0 } // start at arr + 32 -> first byte corresponds to length
lt(i, words)
{ i := add(i, 1) }
{
let offset := mul(i, 32)
mstore(add(destination, offset), mload(add(source, offset)))
}
mstore(add(_target, add(32, mload(_target))), 0)
}
resultPointer = _bytesPointer + _bytesLength;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @notice Library to recover address and verify signatures
* @dev Simple wrapper for `ecrecover`
*/
library SignatureVerifier {
enum HashAlgorithm {KECCAK256, SHA256, RIPEMD160}
// Header for Version E as defined by EIP191. First byte ('E') is also the version
bytes25 constant EIP191_VERSION_E_HEADER = "Ethereum Signed Message:\n";
/**
* @notice Recover signer address from hash and signature
* @param _hash 32 bytes message hash
* @param _signature Signature of hash - 32 bytes r + 32 bytes s + 1 byte v (could be 0, 1, 27, 28)
*/
function recover(bytes32 _hash, bytes memory _signature)
internal
pure
returns (address)
{
require(_signature.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28);
return ecrecover(_hash, v, r, s);
}
/**
* @notice Transform public key to address
* @param _publicKey secp256k1 public key
*/
function toAddress(bytes memory _publicKey) internal pure returns (address) {
return address(uint160(uint256(keccak256(_publicKey))));
}
/**
* @notice Hash using one of pre built hashing algorithm
* @param _message Signed message
* @param _algorithm Hashing algorithm
*/
function hash(bytes memory _message, HashAlgorithm _algorithm)
internal
pure
returns (bytes32 result)
{
if (_algorithm == HashAlgorithm.KECCAK256) {
result = keccak256(_message);
} else if (_algorithm == HashAlgorithm.SHA256) {
result = sha256(_message);
} else {
result = ripemd160(_message);
}
}
/**
* @notice Verify ECDSA signature
* @dev Uses one of pre built hashing algorithm
* @param _message Signed message
* @param _signature Signature of message hash
* @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes)
* @param _algorithm Hashing algorithm
*/
function verify(
bytes memory _message,
bytes memory _signature,
bytes memory _publicKey,
HashAlgorithm _algorithm
)
internal
pure
returns (bool)
{
require(_publicKey.length == 64);
return toAddress(_publicKey) == recover(hash(_message, _algorithm), _signature);
}
/**
* @notice Hash message according to EIP191 signature specification
* @dev It always assumes Keccak256 is used as hashing algorithm
* @dev Only supports version 0 and version E (0x45)
* @param _message Message to sign
* @param _version EIP191 version to use
*/
function hashEIP191(
bytes memory _message,
byte _version
)
internal
view
returns (bytes32 result)
{
if(_version == byte(0x00)){ // Version 0: Data with intended validator
address validator = address(this);
return keccak256(abi.encodePacked(byte(0x19), byte(0x00), validator, _message));
} else if (_version == byte(0x45)){ // Version E: personal_sign messages
uint256 length = _message.length;
require(length > 0, "Empty message not allowed for version E");
// Compute text-encoded length of message
uint256 digits = 0;
while (length != 0) {
digits++;
length /= 10;
}
bytes memory lengthAsText = new bytes(digits);
length = _message.length;
uint256 index = digits - 1;
while (length != 0) {
lengthAsText[index--] = byte(uint8(48 + length % 10));
length /= 10;
}
return keccak256(abi.encodePacked(byte(0x19), EIP191_VERSION_E_HEADER, lengthAsText, _message));
} else {
revert("Unsupported EIP191 version");
}
}
/**
* @notice Verify EIP191 signature
* @dev It always assumes Keccak256 is used as hashing algorithm
* @dev Only supports version 0 and version E (0x45)
* @param _message Signed message
* @param _signature Signature of message hash
* @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes)
* @param _version EIP191 version to use
*/
function verifyEIP191(
bytes memory _message,
bytes memory _signature,
bytes memory _publicKey,
byte _version
)
internal
view
returns (bool)
{
require(_publicKey.length == 64);
return toAddress(_publicKey) == recover(hashEIP191(_message, _version), _signature);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../aragon/interfaces/IERC900History.sol";
import "./Issuer.sol";
import "./lib/Bits.sol";
import "./lib/Snapshot.sol";
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/token/ERC20/SafeERC20.sol";
/**
* @notice PolicyManager interface
*/
interface PolicyManagerInterface {
function secondsPerPeriod() external view returns (uint32);
function register(address _node, uint16 _period) external;
function migrate(address _node) external;
function ping(
address _node,
uint16 _processedPeriod1,
uint16 _processedPeriod2,
uint16 _periodToSetDefault
) external;
}
/**
* @notice Adjudicator interface
*/
interface AdjudicatorInterface {
function rewardCoefficient() external view returns (uint32);
}
/**
* @notice WorkLock interface
*/
interface WorkLockInterface {
function token() external view returns (NuCypherToken);
}
/**
* @title StakingEscrowStub
* @notice Stub is used to deploy main StakingEscrow after all other contract and make some variables immutable
* @dev |v1.0.0|
*/
contract StakingEscrowStub is Upgradeable {
using AdditionalMath for uint32;
NuCypherToken public immutable token;
uint32 public immutable genesisSecondsPerPeriod;
uint32 public immutable secondsPerPeriod;
uint16 public immutable minLockedPeriods;
uint256 public immutable minAllowableLockedTokens;
uint256 public immutable maxAllowableLockedTokens;
/**
* @notice Predefines some variables for use when deploying other contracts
* @param _token Token contract
* @param _genesisHoursPerPeriod Size of period in hours at genesis
* @param _hoursPerPeriod Size of period in hours
* @param _minLockedPeriods Min amount of periods during which tokens can be locked
* @param _minAllowableLockedTokens Min amount of tokens that can be locked
* @param _maxAllowableLockedTokens Max amount of tokens that can be locked
*/
constructor(
NuCypherToken _token,
uint32 _genesisHoursPerPeriod,
uint32 _hoursPerPeriod,
uint16 _minLockedPeriods,
uint256 _minAllowableLockedTokens,
uint256 _maxAllowableLockedTokens
) {
require(_token.totalSupply() > 0 &&
_hoursPerPeriod != 0 &&
_genesisHoursPerPeriod != 0 &&
_genesisHoursPerPeriod <= _hoursPerPeriod &&
_minLockedPeriods > 1 &&
_maxAllowableLockedTokens != 0);
token = _token;
secondsPerPeriod = _hoursPerPeriod.mul32(1 hours);
genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours);
minLockedPeriods = _minLockedPeriods;
minAllowableLockedTokens = _minAllowableLockedTokens;
maxAllowableLockedTokens = _maxAllowableLockedTokens;
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
// we have to use real values even though this is a stub
require(address(delegateGet(_testTarget, this.token.selector)) == address(token));
// TODO uncomment after merging this PR #2579
// require(uint32(delegateGet(_testTarget, this.genesisSecondsPerPeriod.selector)) == genesisSecondsPerPeriod);
require(uint32(delegateGet(_testTarget, this.secondsPerPeriod.selector)) == secondsPerPeriod);
require(uint16(delegateGet(_testTarget, this.minLockedPeriods.selector)) == minLockedPeriods);
require(delegateGet(_testTarget, this.minAllowableLockedTokens.selector) == minAllowableLockedTokens);
require(delegateGet(_testTarget, this.maxAllowableLockedTokens.selector) == maxAllowableLockedTokens);
}
}
/**
* @title StakingEscrow
* @notice Contract holds and locks stakers tokens.
* Each staker that locks their tokens will receive some compensation
* @dev |v5.7.1|
*/
contract StakingEscrow is Issuer, IERC900History {
using AdditionalMath for uint256;
using AdditionalMath for uint16;
using Bits for uint256;
using SafeMath for uint256;
using Snapshot for uint128[];
using SafeERC20 for NuCypherToken;
/**
* @notice Signals that tokens were deposited
* @param staker Staker address
* @param value Amount deposited (in NuNits)
* @param periods Number of periods tokens will be locked
*/
event Deposited(address indexed staker, uint256 value, uint16 periods);
/**
* @notice Signals that tokens were stake locked
* @param staker Staker address
* @param value Amount locked (in NuNits)
* @param firstPeriod Starting lock period
* @param periods Number of periods tokens will be locked
*/
event Locked(address indexed staker, uint256 value, uint16 firstPeriod, uint16 periods);
/**
* @notice Signals that a sub-stake was divided
* @param staker Staker address
* @param oldValue Old sub-stake value (in NuNits)
* @param lastPeriod Final locked period of old sub-stake
* @param newValue New sub-stake value (in NuNits)
* @param periods Number of periods to extend sub-stake
*/
event Divided(
address indexed staker,
uint256 oldValue,
uint16 lastPeriod,
uint256 newValue,
uint16 periods
);
/**
* @notice Signals that two sub-stakes were merged
* @param staker Staker address
* @param value1 Value of first sub-stake (in NuNits)
* @param value2 Value of second sub-stake (in NuNits)
* @param lastPeriod Final locked period of merged sub-stake
*/
event Merged(address indexed staker, uint256 value1, uint256 value2, uint16 lastPeriod);
/**
* @notice Signals that a sub-stake was prolonged
* @param staker Staker address
* @param value Value of sub-stake
* @param lastPeriod Final locked period of old sub-stake
* @param periods Number of periods sub-stake was extended
*/
event Prolonged(address indexed staker, uint256 value, uint16 lastPeriod, uint16 periods);
/**
* @notice Signals that tokens were withdrawn to the staker
* @param staker Staker address
* @param value Amount withdraws (in NuNits)
*/
event Withdrawn(address indexed staker, uint256 value);
/**
* @notice Signals that the worker associated with the staker made a commitment to next period
* @param staker Staker address
* @param period Period committed to
* @param value Amount of tokens staked for the committed period
*/
event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value);
/**
* @notice Signals that tokens were minted for previous periods
* @param staker Staker address
* @param period Previous period tokens minted for
* @param value Amount minted (in NuNits)
*/
event Minted(address indexed staker, uint16 indexed period, uint256 value);
/**
* @notice Signals that the staker was slashed
* @param staker Staker address
* @param penalty Slashing penalty
* @param investigator Investigator address
* @param reward Value of reward provided to investigator (in NuNits)
*/
event Slashed(address indexed staker, uint256 penalty, address indexed investigator, uint256 reward);
/**
* @notice Signals that the restake parameter was activated/deactivated
* @param staker Staker address
* @param reStake Updated parameter value
*/
event ReStakeSet(address indexed staker, bool reStake);
/**
* @notice Signals that a worker was bonded to the staker
* @param staker Staker address
* @param worker Worker address
* @param startPeriod Period bonding occurred
*/
event WorkerBonded(address indexed staker, address indexed worker, uint16 indexed startPeriod);
/**
* @notice Signals that the winddown parameter was activated/deactivated
* @param staker Staker address
* @param windDown Updated parameter value
*/
event WindDownSet(address indexed staker, bool windDown);
/**
* @notice Signals that the snapshot parameter was activated/deactivated
* @param staker Staker address
* @param snapshotsEnabled Updated parameter value
*/
event SnapshotSet(address indexed staker, bool snapshotsEnabled);
/**
* @notice Signals that the staker migrated their stake to the new period length
* @param staker Staker address
* @param period Period when migration happened
*/
event Migrated(address indexed staker, uint16 indexed period);
/// internal event
event WorkMeasurementSet(address indexed staker, bool measureWork);
struct SubStakeInfo {
uint16 firstPeriod;
uint16 lastPeriod;
uint16 unlockingDuration;
uint128 lockedValue;
}
struct Downtime {
uint16 startPeriod;
uint16 endPeriod;
}
struct StakerInfo {
uint256 value;
/*
* Stores periods that are committed but not yet rewarded.
* In order to optimize storage, only two values are used instead of an array.
* commitToNextPeriod() method invokes mint() method so there can only be two committed
* periods that are not yet rewarded: the current and the next periods.
*/
uint16 currentCommittedPeriod;
uint16 nextCommittedPeriod;
uint16 lastCommittedPeriod;
uint16 stub1; // former slot for lockReStakeUntilPeriod
uint256 completedWork;
uint16 workerStartPeriod; // period when worker was bonded
address worker;
uint256 flags; // uint256 to acquire whole slot and minimize operations on it
uint256 reservedSlot1;
uint256 reservedSlot2;
uint256 reservedSlot3;
uint256 reservedSlot4;
uint256 reservedSlot5;
Downtime[] pastDowntime;
SubStakeInfo[] subStakes;
uint128[] history;
}
// used only for upgrading
uint16 internal constant RESERVED_PERIOD = 0;
uint16 internal constant MAX_CHECKED_VALUES = 5;
// to prevent high gas consumption in loops for slashing
uint16 public constant MAX_SUB_STAKES = 30;
uint16 internal constant MAX_UINT16 = 65535;
// indices for flags
uint8 internal constant RE_STAKE_DISABLED_INDEX = 0;
uint8 internal constant WIND_DOWN_INDEX = 1;
uint8 internal constant MEASURE_WORK_INDEX = 2;
uint8 internal constant SNAPSHOTS_DISABLED_INDEX = 3;
uint8 internal constant MIGRATED_INDEX = 4;
uint16 public immutable minLockedPeriods;
uint16 public immutable minWorkerPeriods;
uint256 public immutable minAllowableLockedTokens;
uint256 public immutable maxAllowableLockedTokens;
PolicyManagerInterface public immutable policyManager;
AdjudicatorInterface public immutable adjudicator;
WorkLockInterface public immutable workLock;
mapping (address => StakerInfo) public stakerInfo;
address[] public stakers;
mapping (address => address) public stakerFromWorker;
mapping (uint16 => uint256) stub4; // former slot for lockedPerPeriod
uint128[] public balanceHistory;
address stub1; // former slot for PolicyManager
address stub2; // former slot for Adjudicator
address stub3; // former slot for WorkLock
mapping (uint16 => uint256) _lockedPerPeriod;
// only to make verifyState from previous version work, temporary
// TODO remove after upgrade #2579
function lockedPerPeriod(uint16 _period) public view returns (uint256) {
return _period != RESERVED_PERIOD ? _lockedPerPeriod[_period] : 111;
}
/**
* @notice Constructor sets address of token contract and coefficients for minting
* @param _token Token contract
* @param _policyManager Policy Manager contract
* @param _adjudicator Adjudicator contract
* @param _workLock WorkLock contract. Zero address if there is no WorkLock
* @param _genesisHoursPerPeriod Size of period in hours at genesis
* @param _hoursPerPeriod Size of period in hours
* @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays,
* only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2.
* See Equation 10 in Staking Protocol & Economics paper
* @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent
* to which a stake's lock duration affects the subsidy it receives. Affects stakers differently.
* Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent
* to which a stake's lock duration affects the subsidy it receives. Affects stakers differently.
* Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier)
* where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration
* no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _firstPhaseTotalSupply Total supply for the first phase
* @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1.
* See Equation 7 in Staking Protocol & Economics paper.
* @param _minLockedPeriods Min amount of periods during which tokens can be locked
* @param _minAllowableLockedTokens Min amount of tokens that can be locked
* @param _maxAllowableLockedTokens Max amount of tokens that can be locked
* @param _minWorkerPeriods Min amount of periods while a worker can't be changed
*/
constructor(
NuCypherToken _token,
PolicyManagerInterface _policyManager,
AdjudicatorInterface _adjudicator,
WorkLockInterface _workLock,
uint32 _genesisHoursPerPeriod,
uint32 _hoursPerPeriod,
uint256 _issuanceDecayCoefficient,
uint256 _lockDurationCoefficient1,
uint256 _lockDurationCoefficient2,
uint16 _maximumRewardedPeriods,
uint256 _firstPhaseTotalSupply,
uint256 _firstPhaseMaxIssuance,
uint16 _minLockedPeriods,
uint256 _minAllowableLockedTokens,
uint256 _maxAllowableLockedTokens,
uint16 _minWorkerPeriods
)
Issuer(
_token,
_genesisHoursPerPeriod,
_hoursPerPeriod,
_issuanceDecayCoefficient,
_lockDurationCoefficient1,
_lockDurationCoefficient2,
_maximumRewardedPeriods,
_firstPhaseTotalSupply,
_firstPhaseMaxIssuance
)
{
// constant `1` in the expression `_minLockedPeriods > 1` uses to simplify the `lock` method
require(_minLockedPeriods > 1 && _maxAllowableLockedTokens != 0);
minLockedPeriods = _minLockedPeriods;
minAllowableLockedTokens = _minAllowableLockedTokens;
maxAllowableLockedTokens = _maxAllowableLockedTokens;
minWorkerPeriods = _minWorkerPeriods;
require((_policyManager.secondsPerPeriod() == _hoursPerPeriod * (1 hours) ||
_policyManager.secondsPerPeriod() == _genesisHoursPerPeriod * (1 hours)) &&
_adjudicator.rewardCoefficient() != 0 &&
(address(_workLock) == address(0) || _workLock.token() == _token));
policyManager = _policyManager;
adjudicator = _adjudicator;
workLock = _workLock;
}
/**
* @dev Checks the existence of a staker in the contract
*/
modifier onlyStaker()
{
StakerInfo storage info = stakerInfo[msg.sender];
require((info.value > 0 || info.nextCommittedPeriod != 0) &&
info.flags.bitSet(MIGRATED_INDEX));
_;
}
//------------------------Main getters------------------------
/**
* @notice Get all tokens belonging to the staker
*/
function getAllTokens(address _staker) external view returns (uint256) {
return stakerInfo[_staker].value;
}
/**
* @notice Get all flags for the staker
*/
function getFlags(address _staker)
external view returns (
bool windDown,
bool reStake,
bool measureWork,
bool snapshots,
bool migrated
)
{
StakerInfo storage info = stakerInfo[_staker];
windDown = info.flags.bitSet(WIND_DOWN_INDEX);
reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX);
measureWork = info.flags.bitSet(MEASURE_WORK_INDEX);
snapshots = !info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX);
migrated = info.flags.bitSet(MIGRATED_INDEX);
}
/**
* @notice Get the start period. Use in the calculation of the last period of the sub stake
* @param _info Staker structure
* @param _currentPeriod Current period
*/
function getStartPeriod(StakerInfo storage _info, uint16 _currentPeriod)
internal view returns (uint16)
{
// if the next period (after current) is committed
if (_info.flags.bitSet(WIND_DOWN_INDEX) && _info.nextCommittedPeriod > _currentPeriod) {
return _currentPeriod + 1;
}
return _currentPeriod;
}
/**
* @notice Get the last period of the sub stake
* @param _subStake Sub stake structure
* @param _startPeriod Pre-calculated start period
*/
function getLastPeriodOfSubStake(SubStakeInfo storage _subStake, uint16 _startPeriod)
internal view returns (uint16)
{
if (_subStake.lastPeriod != 0) {
return _subStake.lastPeriod;
}
uint32 lastPeriod = uint32(_startPeriod) + _subStake.unlockingDuration;
if (lastPeriod > uint32(MAX_UINT16)) {
return MAX_UINT16;
}
return uint16(lastPeriod);
}
/**
* @notice Get the last period of the sub stake
* @param _staker Staker
* @param _index Stake index
*/
function getLastPeriodOfSubStake(address _staker, uint256 _index)
public view returns (uint16)
{
StakerInfo storage info = stakerInfo[_staker];
SubStakeInfo storage subStake = info.subStakes[_index];
uint16 startPeriod = getStartPeriod(info, getCurrentPeriod());
return getLastPeriodOfSubStake(subStake, startPeriod);
}
/**
* @notice Get the value of locked tokens for a staker in a specified period
* @dev Information may be incorrect for rewarded or not committed surpassed period
* @param _info Staker structure
* @param _currentPeriod Current period
* @param _period Next period
*/
function getLockedTokens(StakerInfo storage _info, uint16 _currentPeriod, uint16 _period)
internal view returns (uint256 lockedValue)
{
lockedValue = 0;
uint16 startPeriod = getStartPeriod(_info, _currentPeriod);
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
if (subStake.firstPeriod <= _period &&
getLastPeriodOfSubStake(subStake, startPeriod) >= _period) {
lockedValue += subStake.lockedValue;
}
}
}
/**
* @notice Get the value of locked tokens for a staker in a future period
* @dev This function is used by PreallocationEscrow so its signature can't be updated.
* @param _staker Staker
* @param _offsetPeriods Amount of periods that will be added to the current period
*/
function getLockedTokens(address _staker, uint16 _offsetPeriods)
external view returns (uint256 lockedValue)
{
StakerInfo storage info = stakerInfo[_staker];
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod.add16(_offsetPeriods);
return getLockedTokens(info, currentPeriod, nextPeriod);
}
/**
* @notice Get the last committed staker's period
* @param _staker Staker
*/
function getLastCommittedPeriod(address _staker) public view returns (uint16) {
StakerInfo storage info = stakerInfo[_staker];
return info.nextCommittedPeriod != 0 ? info.nextCommittedPeriod : info.lastCommittedPeriod;
}
/**
* @notice Get the value of locked tokens for active stakers in (getCurrentPeriod() + _offsetPeriods) period
* as well as stakers and their locked tokens
* @param _offsetPeriods Amount of periods for locked tokens calculation
* @param _startIndex Start index for looking in stakers array
* @param _maxStakers Max stakers for looking, if set 0 then all will be used
* @return allLockedTokens Sum of locked tokens for active stakers
* @return activeStakers Array of stakers and their locked tokens. Stakers addresses stored as uint256
* @dev Note that activeStakers[0] in an array of uint256, but you want addresses. Careful when used directly!
*/
function getActiveStakers(uint16 _offsetPeriods, uint256 _startIndex, uint256 _maxStakers)
external view returns (uint256 allLockedTokens, uint256[2][] memory activeStakers)
{
require(_offsetPeriods > 0);
uint256 endIndex = stakers.length;
require(_startIndex < endIndex);
if (_maxStakers != 0 && _startIndex + _maxStakers < endIndex) {
endIndex = _startIndex + _maxStakers;
}
activeStakers = new uint256[2][](endIndex - _startIndex);
allLockedTokens = 0;
uint256 resultIndex = 0;
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod.add16(_offsetPeriods);
for (uint256 i = _startIndex; i < endIndex; i++) {
address staker = stakers[i];
StakerInfo storage info = stakerInfo[staker];
if (info.currentCommittedPeriod != currentPeriod &&
info.nextCommittedPeriod != currentPeriod) {
continue;
}
uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod);
if (lockedTokens != 0) {
activeStakers[resultIndex][0] = uint256(staker);
activeStakers[resultIndex++][1] = lockedTokens;
allLockedTokens += lockedTokens;
}
}
assembly {
mstore(activeStakers, resultIndex)
}
}
/**
* @notice Get worker using staker's address
*/
function getWorkerFromStaker(address _staker) external view returns (address) {
return stakerInfo[_staker].worker;
}
/**
* @notice Get work that completed by the staker
*/
function getCompletedWork(address _staker) external view returns (uint256) {
return stakerInfo[_staker].completedWork;
}
/**
* @notice Find index of downtime structure that includes specified period
* @dev If specified period is outside all downtime periods, the length of the array will be returned
* @param _staker Staker
* @param _period Specified period number
*/
function findIndexOfPastDowntime(address _staker, uint16 _period) external view returns (uint256 index) {
StakerInfo storage info = stakerInfo[_staker];
for (index = 0; index < info.pastDowntime.length; index++) {
if (_period <= info.pastDowntime[index].endPeriod) {
return index;
}
}
}
//------------------------Main methods------------------------
/**
* @notice Start or stop measuring the work of a staker
* @param _staker Staker
* @param _measureWork Value for `measureWork` parameter
* @return Work that was previously done
*/
function setWorkMeasurement(address _staker, bool _measureWork) external returns (uint256) {
require(msg.sender == address(workLock));
StakerInfo storage info = stakerInfo[_staker];
if (info.flags.bitSet(MEASURE_WORK_INDEX) == _measureWork) {
return info.completedWork;
}
info.flags = info.flags.toggleBit(MEASURE_WORK_INDEX);
emit WorkMeasurementSet(_staker, _measureWork);
return info.completedWork;
}
/**
* @notice Bond worker
* @param _worker Worker address. Must be a real address, not a contract
*/
function bondWorker(address _worker) external onlyStaker {
StakerInfo storage info = stakerInfo[msg.sender];
// Specified worker is already bonded with this staker
require(_worker != info.worker);
uint16 currentPeriod = getCurrentPeriod();
if (info.worker != address(0)) { // If this staker had a worker ...
// Check that enough time has passed to change it
require(currentPeriod >= info.workerStartPeriod.add16(minWorkerPeriods));
// Remove the old relation "worker->staker"
stakerFromWorker[info.worker] = address(0);
}
if (_worker != address(0)) {
// Specified worker is already in use
require(stakerFromWorker[_worker] == address(0));
// Specified worker is a staker
require(stakerInfo[_worker].subStakes.length == 0 || _worker == msg.sender);
// Set new worker->staker relation
stakerFromWorker[_worker] = msg.sender;
}
// Bond new worker (or unbond if _worker == address(0))
info.worker = _worker;
info.workerStartPeriod = currentPeriod;
emit WorkerBonded(msg.sender, _worker, currentPeriod);
}
/**
* @notice Set `reStake` parameter. If true then all staking rewards will be added to locked stake
* @param _reStake Value for parameter
*/
function setReStake(bool _reStake) external {
StakerInfo storage info = stakerInfo[msg.sender];
if (info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == !_reStake) {
return;
}
info.flags = info.flags.toggleBit(RE_STAKE_DISABLED_INDEX);
emit ReStakeSet(msg.sender, _reStake);
}
/**
* @notice Deposit tokens from WorkLock contract
* @param _staker Staker address
* @param _value Amount of tokens to deposit
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function depositFromWorkLock(
address _staker,
uint256 _value,
uint16 _unlockingDuration
)
external
{
require(msg.sender == address(workLock));
StakerInfo storage info = stakerInfo[_staker];
if (!info.flags.bitSet(WIND_DOWN_INDEX) && info.subStakes.length == 0) {
info.flags = info.flags.toggleBit(WIND_DOWN_INDEX);
emit WindDownSet(_staker, true);
}
// WorkLock still uses the genesis period length (24h)
_unlockingDuration = recalculatePeriod(_unlockingDuration);
deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration);
}
/**
* @notice Set `windDown` parameter.
* If true then stake's duration will be decreasing in each period with `commitToNextPeriod()`
* @param _windDown Value for parameter
*/
function setWindDown(bool _windDown) external {
StakerInfo storage info = stakerInfo[msg.sender];
if (info.flags.bitSet(WIND_DOWN_INDEX) == _windDown) {
return;
}
info.flags = info.flags.toggleBit(WIND_DOWN_INDEX);
emit WindDownSet(msg.sender, _windDown);
// duration adjustment if next period is committed
uint16 nextPeriod = getCurrentPeriod() + 1;
if (info.nextCommittedPeriod != nextPeriod) {
return;
}
// adjust sub-stakes duration for the new value of winding down parameter
for (uint256 index = 0; index < info.subStakes.length; index++) {
SubStakeInfo storage subStake = info.subStakes[index];
// sub-stake does not have fixed last period when winding down is disabled
if (!_windDown && subStake.lastPeriod == nextPeriod) {
subStake.lastPeriod = 0;
subStake.unlockingDuration = 1;
continue;
}
// this sub-stake is no longer affected by winding down parameter
if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) {
continue;
}
subStake.unlockingDuration = _windDown ? subStake.unlockingDuration - 1 : subStake.unlockingDuration + 1;
if (subStake.unlockingDuration == 0) {
subStake.lastPeriod = nextPeriod;
}
}
}
/**
* @notice Activate/deactivate taking snapshots of balances
* @param _enableSnapshots True to activate snapshots, False to deactivate
*/
function setSnapshots(bool _enableSnapshots) external {
StakerInfo storage info = stakerInfo[msg.sender];
if (info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX) == !_enableSnapshots) {
return;
}
uint256 lastGlobalBalance = uint256(balanceHistory.lastValue());
if(_enableSnapshots){
info.history.addSnapshot(info.value);
balanceHistory.addSnapshot(lastGlobalBalance + info.value);
} else {
info.history.addSnapshot(0);
balanceHistory.addSnapshot(lastGlobalBalance - info.value);
}
info.flags = info.flags.toggleBit(SNAPSHOTS_DISABLED_INDEX);
emit SnapshotSet(msg.sender, _enableSnapshots);
}
/**
* @notice Adds a new snapshot to both the staker and global balance histories,
* assuming the staker's balance was already changed
* @param _info Reference to affected staker's struct
* @param _addition Variance in balance. It can be positive or negative.
*/
function addSnapshot(StakerInfo storage _info, int256 _addition) internal {
if(!_info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX)){
_info.history.addSnapshot(_info.value);
uint256 lastGlobalBalance = uint256(balanceHistory.lastValue());
balanceHistory.addSnapshot(lastGlobalBalance.addSigned(_addition));
}
}
/**
* @notice Implementation of the receiveApproval(address,uint256,address,bytes) method
* (see NuCypherToken contract). Deposit all tokens that were approved to transfer
* @param _from Staker
* @param _value Amount of tokens to deposit
* @param _tokenContract Token contract address
* @notice (param _extraData) Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function receiveApproval(
address _from,
uint256 _value,
address _tokenContract,
bytes calldata /* _extraData */
)
external
{
require(_tokenContract == address(token) && msg.sender == address(token));
// Copy first 32 bytes from _extraData, according to calldata memory layout:
//
// 0x00: method signature 4 bytes
// 0x04: _from 32 bytes after encoding
// 0x24: _value 32 bytes after encoding
// 0x44: _tokenContract 32 bytes after encoding
// 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter)
// 0x84: _extraData length 32 bytes
// 0xA4: _extraData data Length determined by previous variable
//
// See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples
uint256 payloadSize;
uint256 payload;
assembly {
payloadSize := calldataload(0x84)
payload := calldataload(0xA4)
}
payload = payload >> 8*(32 - payloadSize);
deposit(_from, _from, MAX_SUB_STAKES, _value, uint16(payload));
}
/**
* @notice Deposit tokens and create new sub-stake. Use this method to become a staker
* @param _staker Staker
* @param _value Amount of tokens to deposit
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function deposit(address _staker, uint256 _value, uint16 _unlockingDuration) external {
deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration);
}
/**
* @notice Deposit tokens and increase lock amount of an existing sub-stake
* @dev This is preferable way to stake tokens because will be fewer active sub-stakes in the result
* @param _index Index of the sub stake
* @param _value Amount of tokens which will be locked
*/
function depositAndIncrease(uint256 _index, uint256 _value) external onlyStaker {
require(_index < MAX_SUB_STAKES);
deposit(msg.sender, msg.sender, _index, _value, 0);
}
/**
* @notice Deposit tokens
* @dev Specify either index and zero periods (for an existing sub-stake)
* or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both
* @param _staker Staker
* @param _payer Owner of tokens
* @param _index Index of the sub stake
* @param _value Amount of tokens to deposit
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function deposit(address _staker, address _payer, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal {
require(_value != 0);
StakerInfo storage info = stakerInfo[_staker];
// A staker can't be a worker for another staker
require(stakerFromWorker[_staker] == address(0) || stakerFromWorker[_staker] == info.worker);
// initial stake of the staker
if (info.subStakes.length == 0 && info.lastCommittedPeriod == 0) {
stakers.push(_staker);
policyManager.register(_staker, getCurrentPeriod() - 1);
info.flags = info.flags.toggleBit(MIGRATED_INDEX);
}
require(info.flags.bitSet(MIGRATED_INDEX));
token.safeTransferFrom(_payer, address(this), _value);
info.value += _value;
lock(_staker, _index, _value, _unlockingDuration);
addSnapshot(info, int256(_value));
if (_index >= MAX_SUB_STAKES) {
emit Deposited(_staker, _value, _unlockingDuration);
} else {
uint16 lastPeriod = getLastPeriodOfSubStake(_staker, _index);
emit Deposited(_staker, _value, lastPeriod - getCurrentPeriod());
}
}
/**
* @notice Lock some tokens as a new sub-stake
* @param _value Amount of tokens which will be locked
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function lockAndCreate(uint256 _value, uint16 _unlockingDuration) external onlyStaker {
lock(msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration);
}
/**
* @notice Increase lock amount of an existing sub-stake
* @param _index Index of the sub-stake
* @param _value Amount of tokens which will be locked
*/
function lockAndIncrease(uint256 _index, uint256 _value) external onlyStaker {
require(_index < MAX_SUB_STAKES);
lock(msg.sender, _index, _value, 0);
}
/**
* @notice Lock some tokens as a stake
* @dev Specify either index and zero periods (for an existing sub-stake)
* or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both
* @param _staker Staker
* @param _index Index of the sub stake
* @param _value Amount of tokens which will be locked
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function lock(address _staker, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal {
if (_index < MAX_SUB_STAKES) {
require(_value > 0);
} else {
require(_value >= minAllowableLockedTokens && _unlockingDuration >= minLockedPeriods);
}
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
StakerInfo storage info = stakerInfo[_staker];
uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod);
uint256 requestedLockedTokens = _value.add(lockedTokens);
require(requestedLockedTokens <= info.value && requestedLockedTokens <= maxAllowableLockedTokens);
// next period is committed
if (info.nextCommittedPeriod == nextPeriod) {
_lockedPerPeriod[nextPeriod] += _value;
emit CommitmentMade(_staker, nextPeriod, _value);
}
// if index was provided then increase existing sub-stake
if (_index < MAX_SUB_STAKES) {
lockAndIncrease(info, currentPeriod, nextPeriod, _staker, _index, _value);
// otherwise create new
} else {
lockAndCreate(info, nextPeriod, _staker, _value, _unlockingDuration);
}
}
/**
* @notice Lock some tokens as a new sub-stake
* @param _info Staker structure
* @param _nextPeriod Next period
* @param _staker Staker
* @param _value Amount of tokens which will be locked
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function lockAndCreate(
StakerInfo storage _info,
uint16 _nextPeriod,
address _staker,
uint256 _value,
uint16 _unlockingDuration
)
internal
{
uint16 duration = _unlockingDuration;
// if winding down is enabled and next period is committed
// then sub-stakes duration were decreased
if (_info.nextCommittedPeriod == _nextPeriod && _info.flags.bitSet(WIND_DOWN_INDEX)) {
duration -= 1;
}
saveSubStake(_info, _nextPeriod, 0, duration, _value);
emit Locked(_staker, _value, _nextPeriod, _unlockingDuration);
}
/**
* @notice Increase lock amount of an existing sub-stake
* @dev Probably will be created a new sub-stake but it will be active only one period
* @param _info Staker structure
* @param _currentPeriod Current period
* @param _nextPeriod Next period
* @param _staker Staker
* @param _index Index of the sub-stake
* @param _value Amount of tokens which will be locked
*/
function lockAndIncrease(
StakerInfo storage _info,
uint16 _currentPeriod,
uint16 _nextPeriod,
address _staker,
uint256 _index,
uint256 _value
)
internal
{
SubStakeInfo storage subStake = _info.subStakes[_index];
(, uint16 lastPeriod) = checkLastPeriodOfSubStake(_info, subStake, _currentPeriod);
// create temporary sub-stake for current or previous committed periods
// to leave locked amount in this period unchanged
if (_info.currentCommittedPeriod != 0 &&
_info.currentCommittedPeriod <= _currentPeriod ||
_info.nextCommittedPeriod != 0 &&
_info.nextCommittedPeriod <= _currentPeriod)
{
saveSubStake(_info, subStake.firstPeriod, _currentPeriod, 0, subStake.lockedValue);
}
subStake.lockedValue += uint128(_value);
// all new locks should start from the next period
subStake.firstPeriod = _nextPeriod;
emit Locked(_staker, _value, _nextPeriod, lastPeriod - _currentPeriod);
}
/**
* @notice Checks that last period of sub-stake is greater than the current period
* @param _info Staker structure
* @param _subStake Sub-stake structure
* @param _currentPeriod Current period
* @return startPeriod Start period. Use in the calculation of the last period of the sub stake
* @return lastPeriod Last period of the sub stake
*/
function checkLastPeriodOfSubStake(
StakerInfo storage _info,
SubStakeInfo storage _subStake,
uint16 _currentPeriod
)
internal view returns (uint16 startPeriod, uint16 lastPeriod)
{
startPeriod = getStartPeriod(_info, _currentPeriod);
lastPeriod = getLastPeriodOfSubStake(_subStake, startPeriod);
// The sub stake must be active at least in the next period
require(lastPeriod > _currentPeriod);
}
/**
* @notice Save sub stake. First tries to override inactive sub stake
* @dev Inactive sub stake means that last period of sub stake has been surpassed and already rewarded
* @param _info Staker structure
* @param _firstPeriod First period of the sub stake
* @param _lastPeriod Last period of the sub stake
* @param _unlockingDuration Duration of the sub stake in periods
* @param _lockedValue Amount of locked tokens
*/
function saveSubStake(
StakerInfo storage _info,
uint16 _firstPeriod,
uint16 _lastPeriod,
uint16 _unlockingDuration,
uint256 _lockedValue
)
internal
{
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
if (subStake.lastPeriod != 0 &&
(_info.currentCommittedPeriod == 0 ||
subStake.lastPeriod < _info.currentCommittedPeriod) &&
(_info.nextCommittedPeriod == 0 ||
subStake.lastPeriod < _info.nextCommittedPeriod))
{
subStake.firstPeriod = _firstPeriod;
subStake.lastPeriod = _lastPeriod;
subStake.unlockingDuration = _unlockingDuration;
subStake.lockedValue = uint128(_lockedValue);
return;
}
}
require(_info.subStakes.length < MAX_SUB_STAKES);
_info.subStakes.push(SubStakeInfo(_firstPeriod, _lastPeriod, _unlockingDuration, uint128(_lockedValue)));
}
/**
* @notice Divide sub stake into two parts
* @param _index Index of the sub stake
* @param _newValue New sub stake value
* @param _additionalDuration Amount of periods for extending sub stake
*/
function divideStake(uint256 _index, uint256 _newValue, uint16 _additionalDuration) external onlyStaker {
StakerInfo storage info = stakerInfo[msg.sender];
require(_newValue >= minAllowableLockedTokens && _additionalDuration > 0);
SubStakeInfo storage subStake = info.subStakes[_index];
uint16 currentPeriod = getCurrentPeriod();
(, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod);
uint256 oldValue = subStake.lockedValue;
subStake.lockedValue = uint128(oldValue.sub(_newValue));
require(subStake.lockedValue >= minAllowableLockedTokens);
uint16 requestedPeriods = subStake.unlockingDuration.add16(_additionalDuration);
saveSubStake(info, subStake.firstPeriod, 0, requestedPeriods, _newValue);
emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _additionalDuration);
emit Locked(msg.sender, _newValue, subStake.firstPeriod, requestedPeriods);
}
/**
* @notice Prolong active sub stake
* @param _index Index of the sub stake
* @param _additionalDuration Amount of periods for extending sub stake
*/
function prolongStake(uint256 _index, uint16 _additionalDuration) external onlyStaker {
StakerInfo storage info = stakerInfo[msg.sender];
// Incorrect parameters
require(_additionalDuration > 0);
SubStakeInfo storage subStake = info.subStakes[_index];
uint16 currentPeriod = getCurrentPeriod();
(uint16 startPeriod, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod);
subStake.unlockingDuration = subStake.unlockingDuration.add16(_additionalDuration);
// if the sub stake ends in the next committed period then reset the `lastPeriod` field
if (lastPeriod == startPeriod) {
subStake.lastPeriod = 0;
}
// The extended sub stake must not be less than the minimum value
require(uint32(lastPeriod - currentPeriod) + _additionalDuration >= minLockedPeriods);
emit Locked(msg.sender, subStake.lockedValue, lastPeriod + 1, _additionalDuration);
emit Prolonged(msg.sender, subStake.lockedValue, lastPeriod, _additionalDuration);
}
/**
* @notice Merge two sub-stakes into one if their last periods are equal
* @dev It's possible that both sub-stakes will be active after this transaction.
* But only one of them will be active until next call `commitToNextPeriod` (in the next period)
* @param _index1 Index of the first sub-stake
* @param _index2 Index of the second sub-stake
*/
function mergeStake(uint256 _index1, uint256 _index2) external onlyStaker {
require(_index1 != _index2); // must be different sub-stakes
StakerInfo storage info = stakerInfo[msg.sender];
SubStakeInfo storage subStake1 = info.subStakes[_index1];
SubStakeInfo storage subStake2 = info.subStakes[_index2];
uint16 currentPeriod = getCurrentPeriod();
(, uint16 lastPeriod1) = checkLastPeriodOfSubStake(info, subStake1, currentPeriod);
(, uint16 lastPeriod2) = checkLastPeriodOfSubStake(info, subStake2, currentPeriod);
// both sub-stakes must have equal last period to be mergeable
require(lastPeriod1 == lastPeriod2);
emit Merged(msg.sender, subStake1.lockedValue, subStake2.lockedValue, lastPeriod1);
if (subStake1.firstPeriod == subStake2.firstPeriod) {
subStake1.lockedValue += subStake2.lockedValue;
subStake2.lastPeriod = 1;
subStake2.unlockingDuration = 0;
} else if (subStake1.firstPeriod > subStake2.firstPeriod) {
subStake1.lockedValue += subStake2.lockedValue;
subStake2.lastPeriod = subStake1.firstPeriod - 1;
subStake2.unlockingDuration = 0;
} else {
subStake2.lockedValue += subStake1.lockedValue;
subStake1.lastPeriod = subStake2.firstPeriod - 1;
subStake1.unlockingDuration = 0;
}
}
/**
* @notice Remove unused sub-stake to decrease gas cost for several methods
*/
function removeUnusedSubStake(uint16 _index) external onlyStaker {
StakerInfo storage info = stakerInfo[msg.sender];
uint256 lastIndex = info.subStakes.length - 1;
SubStakeInfo storage subStake = info.subStakes[_index];
require(subStake.lastPeriod != 0 &&
(info.currentCommittedPeriod == 0 ||
subStake.lastPeriod < info.currentCommittedPeriod) &&
(info.nextCommittedPeriod == 0 ||
subStake.lastPeriod < info.nextCommittedPeriod));
if (_index != lastIndex) {
SubStakeInfo storage lastSubStake = info.subStakes[lastIndex];
subStake.firstPeriod = lastSubStake.firstPeriod;
subStake.lastPeriod = lastSubStake.lastPeriod;
subStake.unlockingDuration = lastSubStake.unlockingDuration;
subStake.lockedValue = lastSubStake.lockedValue;
}
info.subStakes.pop();
}
/**
* @notice Withdraw available amount of tokens to staker
* @param _value Amount of tokens to withdraw
*/
function withdraw(uint256 _value) external onlyStaker {
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
StakerInfo storage info = stakerInfo[msg.sender];
// the max locked tokens in most cases will be in the current period
// but when the staker locks more then we should use the next period
uint256 lockedTokens = Math.max(getLockedTokens(info, currentPeriod, nextPeriod),
getLockedTokens(info, currentPeriod, currentPeriod));
require(_value <= info.value.sub(lockedTokens));
info.value -= _value;
addSnapshot(info, - int256(_value));
token.safeTransfer(msg.sender, _value);
emit Withdrawn(msg.sender, _value);
// unbond worker if staker withdraws last portion of NU
if (info.value == 0 &&
info.nextCommittedPeriod == 0 &&
info.worker != address(0))
{
stakerFromWorker[info.worker] = address(0);
info.worker = address(0);
emit WorkerBonded(msg.sender, address(0), currentPeriod);
}
}
/**
* @notice Make a commitment to the next period and mint for the previous period
*/
function commitToNextPeriod() external isInitialized {
address staker = stakerFromWorker[msg.sender];
StakerInfo storage info = stakerInfo[staker];
// Staker must have a stake to make a commitment
require(info.value > 0);
// Only worker with real address can make a commitment
require(msg.sender == tx.origin);
migrate(staker);
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
// the period has already been committed
require(info.nextCommittedPeriod != nextPeriod);
uint16 lastCommittedPeriod = getLastCommittedPeriod(staker);
(uint16 processedPeriod1, uint16 processedPeriod2) = mint(staker);
uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod);
require(lockedTokens > 0);
_lockedPerPeriod[nextPeriod] += lockedTokens;
info.currentCommittedPeriod = info.nextCommittedPeriod;
info.nextCommittedPeriod = nextPeriod;
decreaseSubStakesDuration(info, nextPeriod);
// staker was inactive for several periods
if (lastCommittedPeriod < currentPeriod) {
info.pastDowntime.push(Downtime(lastCommittedPeriod + 1, currentPeriod));
}
policyManager.ping(staker, processedPeriod1, processedPeriod2, nextPeriod);
emit CommitmentMade(staker, nextPeriod, lockedTokens);
}
/**
* @notice Migrate from the old period length to the new one. Can be done only once
* @param _staker Staker
*/
function migrate(address _staker) public {
StakerInfo storage info = stakerInfo[_staker];
// check that provided address is/was a staker
require(info.subStakes.length != 0 || info.lastCommittedPeriod != 0);
if (info.flags.bitSet(MIGRATED_INDEX)) {
return;
}
// reset state
info.currentCommittedPeriod = 0;
info.nextCommittedPeriod = 0;
// maintain case when no more sub-stakes and need to avoid re-registering this staker during deposit
info.lastCommittedPeriod = 1;
info.workerStartPeriod = recalculatePeriod(info.workerStartPeriod);
delete info.pastDowntime;
// recalculate all sub-stakes
uint16 currentPeriod = getCurrentPeriod();
for (uint256 i = 0; i < info.subStakes.length; i++) {
SubStakeInfo storage subStake = info.subStakes[i];
subStake.firstPeriod = recalculatePeriod(subStake.firstPeriod);
// sub-stake has fixed last period
if (subStake.lastPeriod != 0) {
subStake.lastPeriod = recalculatePeriod(subStake.lastPeriod);
if (subStake.lastPeriod == 0) {
subStake.lastPeriod = 1;
}
subStake.unlockingDuration = 0;
// sub-stake has no fixed ending but possible that with new period length will have
} else {
uint16 oldCurrentPeriod = uint16(block.timestamp / genesisSecondsPerPeriod);
uint16 lastPeriod = recalculatePeriod(oldCurrentPeriod + subStake.unlockingDuration);
subStake.unlockingDuration = lastPeriod - currentPeriod;
if (subStake.unlockingDuration == 0) {
subStake.lastPeriod = lastPeriod;
}
}
}
policyManager.migrate(_staker);
info.flags = info.flags.toggleBit(MIGRATED_INDEX);
emit Migrated(_staker, currentPeriod);
}
/**
* @notice Decrease sub-stakes duration if `windDown` is enabled
*/
function decreaseSubStakesDuration(StakerInfo storage _info, uint16 _nextPeriod) internal {
if (!_info.flags.bitSet(WIND_DOWN_INDEX)) {
return;
}
for (uint256 index = 0; index < _info.subStakes.length; index++) {
SubStakeInfo storage subStake = _info.subStakes[index];
if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) {
continue;
}
subStake.unlockingDuration--;
if (subStake.unlockingDuration == 0) {
subStake.lastPeriod = _nextPeriod;
}
}
}
/**
* @notice Mint tokens for previous periods if staker locked their tokens and made a commitment
*/
function mint() external onlyStaker {
// save last committed period to the storage if both periods will be empty after minting
// because we won't be able to calculate last committed period
// see getLastCommittedPeriod(address)
StakerInfo storage info = stakerInfo[msg.sender];
uint16 previousPeriod = getCurrentPeriod() - 1;
if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) {
info.lastCommittedPeriod = info.nextCommittedPeriod;
}
(uint16 processedPeriod1, uint16 processedPeriod2) = mint(msg.sender);
if (processedPeriod1 != 0 || processedPeriod2 != 0) {
policyManager.ping(msg.sender, processedPeriod1, processedPeriod2, 0);
}
}
/**
* @notice Mint tokens for previous periods if staker locked their tokens and made a commitment
* @param _staker Staker
* @return processedPeriod1 Processed period: currentCommittedPeriod or zero
* @return processedPeriod2 Processed period: nextCommittedPeriod or zero
*/
function mint(address _staker) internal returns (uint16 processedPeriod1, uint16 processedPeriod2) {
uint16 currentPeriod = getCurrentPeriod();
uint16 previousPeriod = currentPeriod - 1;
StakerInfo storage info = stakerInfo[_staker];
if (info.nextCommittedPeriod == 0 ||
info.currentCommittedPeriod == 0 &&
info.nextCommittedPeriod > previousPeriod ||
info.currentCommittedPeriod > previousPeriod) {
return (0, 0);
}
uint16 startPeriod = getStartPeriod(info, currentPeriod);
uint256 reward = 0;
bool reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX);
if (info.currentCommittedPeriod != 0) {
reward = mint(info, info.currentCommittedPeriod, currentPeriod, startPeriod, reStake);
processedPeriod1 = info.currentCommittedPeriod;
info.currentCommittedPeriod = 0;
if (reStake) {
_lockedPerPeriod[info.nextCommittedPeriod] += reward;
}
}
if (info.nextCommittedPeriod <= previousPeriod) {
reward += mint(info, info.nextCommittedPeriod, currentPeriod, startPeriod, reStake);
processedPeriod2 = info.nextCommittedPeriod;
info.nextCommittedPeriod = 0;
}
info.value += reward;
if (info.flags.bitSet(MEASURE_WORK_INDEX)) {
info.completedWork += reward;
}
addSnapshot(info, int256(reward));
emit Minted(_staker, previousPeriod, reward);
}
/**
* @notice Calculate reward for one period
* @param _info Staker structure
* @param _mintingPeriod Period for minting calculation
* @param _currentPeriod Current period
* @param _startPeriod Pre-calculated start period
*/
function mint(
StakerInfo storage _info,
uint16 _mintingPeriod,
uint16 _currentPeriod,
uint16 _startPeriod,
bool _reStake
)
internal returns (uint256 reward)
{
reward = 0;
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod);
if (subStake.firstPeriod <= _mintingPeriod && lastPeriod >= _mintingPeriod) {
uint256 subStakeReward = mint(
_currentPeriod,
subStake.lockedValue,
_lockedPerPeriod[_mintingPeriod],
lastPeriod.sub16(_mintingPeriod));
reward += subStakeReward;
if (_reStake) {
subStake.lockedValue += uint128(subStakeReward);
}
}
}
return reward;
}
//-------------------------Slashing-------------------------
/**
* @notice Slash the staker's stake and reward the investigator
* @param _staker Staker's address
* @param _penalty Penalty
* @param _investigator Investigator
* @param _reward Reward for the investigator
*/
function slashStaker(
address _staker,
uint256 _penalty,
address _investigator,
uint256 _reward
)
public isInitialized
{
require(msg.sender == address(adjudicator));
require(_penalty > 0);
StakerInfo storage info = stakerInfo[_staker];
require(info.flags.bitSet(MIGRATED_INDEX));
if (info.value <= _penalty) {
_penalty = info.value;
}
info.value -= _penalty;
if (_reward > _penalty) {
_reward = _penalty;
}
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
uint16 startPeriod = getStartPeriod(info, currentPeriod);
(uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex) =
getLockedTokensAndShortestSubStake(info, currentPeriod, nextPeriod, startPeriod);
// Decrease the stake if amount of locked tokens in the current period more than staker has
uint256 lockedTokens = currentLock + currentAndNextLock;
if (info.value < lockedTokens) {
decreaseSubStakes(info, lockedTokens - info.value, currentPeriod, startPeriod, shortestSubStakeIndex);
}
// Decrease the stake if amount of locked tokens in the next period more than staker has
if (nextLock > 0) {
lockedTokens = nextLock + currentAndNextLock -
(currentAndNextLock > info.value ? currentAndNextLock - info.value : 0);
if (info.value < lockedTokens) {
decreaseSubStakes(info, lockedTokens - info.value, nextPeriod, startPeriod, MAX_SUB_STAKES);
}
}
emit Slashed(_staker, _penalty, _investigator, _reward);
if (_penalty > _reward) {
unMint(_penalty - _reward);
}
// TODO change to withdrawal pattern (#1499)
if (_reward > 0) {
token.safeTransfer(_investigator, _reward);
}
addSnapshot(info, - int256(_penalty));
}
/**
* @notice Get the value of locked tokens for a staker in the current and the next period
* and find the shortest sub stake
* @param _info Staker structure
* @param _currentPeriod Current period
* @param _nextPeriod Next period
* @param _startPeriod Pre-calculated start period
* @return currentLock Amount of tokens that locked in the current period and unlocked in the next period
* @return nextLock Amount of tokens that locked in the next period and not locked in the current period
* @return currentAndNextLock Amount of tokens that locked in the current period and in the next period
* @return shortestSubStakeIndex Index of the shortest sub stake
*/
function getLockedTokensAndShortestSubStake(
StakerInfo storage _info,
uint16 _currentPeriod,
uint16 _nextPeriod,
uint16 _startPeriod
)
internal view returns (
uint256 currentLock,
uint256 nextLock,
uint256 currentAndNextLock,
uint256 shortestSubStakeIndex
)
{
uint16 minDuration = MAX_UINT16;
uint16 minLastPeriod = MAX_UINT16;
shortestSubStakeIndex = MAX_SUB_STAKES;
currentLock = 0;
nextLock = 0;
currentAndNextLock = 0;
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod);
if (lastPeriod < subStake.firstPeriod) {
continue;
}
if (subStake.firstPeriod <= _currentPeriod &&
lastPeriod >= _nextPeriod) {
currentAndNextLock += subStake.lockedValue;
} else if (subStake.firstPeriod <= _currentPeriod &&
lastPeriod >= _currentPeriod) {
currentLock += subStake.lockedValue;
} else if (subStake.firstPeriod <= _nextPeriod &&
lastPeriod >= _nextPeriod) {
nextLock += subStake.lockedValue;
}
uint16 duration = lastPeriod - subStake.firstPeriod;
if (subStake.firstPeriod <= _currentPeriod &&
lastPeriod >= _currentPeriod &&
(lastPeriod < minLastPeriod ||
lastPeriod == minLastPeriod && duration < minDuration))
{
shortestSubStakeIndex = i;
minDuration = duration;
minLastPeriod = lastPeriod;
}
}
}
/**
* @notice Decrease short sub stakes
* @param _info Staker structure
* @param _penalty Penalty rate
* @param _decreasePeriod The period when the decrease begins
* @param _startPeriod Pre-calculated start period
* @param _shortestSubStakeIndex Index of the shortest period
*/
function decreaseSubStakes(
StakerInfo storage _info,
uint256 _penalty,
uint16 _decreasePeriod,
uint16 _startPeriod,
uint256 _shortestSubStakeIndex
)
internal
{
SubStakeInfo storage shortestSubStake = _info.subStakes[0];
uint16 minSubStakeLastPeriod = MAX_UINT16;
uint16 minSubStakeDuration = MAX_UINT16;
while(_penalty > 0) {
if (_shortestSubStakeIndex < MAX_SUB_STAKES) {
shortestSubStake = _info.subStakes[_shortestSubStakeIndex];
minSubStakeLastPeriod = getLastPeriodOfSubStake(shortestSubStake, _startPeriod);
minSubStakeDuration = minSubStakeLastPeriod - shortestSubStake.firstPeriod;
_shortestSubStakeIndex = MAX_SUB_STAKES;
} else {
(shortestSubStake, minSubStakeDuration, minSubStakeLastPeriod) =
getShortestSubStake(_info, _decreasePeriod, _startPeriod);
}
if (minSubStakeDuration == MAX_UINT16) {
break;
}
uint256 appliedPenalty = _penalty;
if (_penalty < shortestSubStake.lockedValue) {
shortestSubStake.lockedValue -= uint128(_penalty);
saveOldSubStake(_info, shortestSubStake.firstPeriod, _penalty, _decreasePeriod);
_penalty = 0;
} else {
shortestSubStake.lastPeriod = _decreasePeriod - 1;
_penalty -= shortestSubStake.lockedValue;
appliedPenalty = shortestSubStake.lockedValue;
}
if (_info.currentCommittedPeriod >= _decreasePeriod &&
_info.currentCommittedPeriod <= minSubStakeLastPeriod)
{
_lockedPerPeriod[_info.currentCommittedPeriod] -= appliedPenalty;
}
if (_info.nextCommittedPeriod >= _decreasePeriod &&
_info.nextCommittedPeriod <= minSubStakeLastPeriod)
{
_lockedPerPeriod[_info.nextCommittedPeriod] -= appliedPenalty;
}
}
}
/**
* @notice Get the shortest sub stake
* @param _info Staker structure
* @param _currentPeriod Current period
* @param _startPeriod Pre-calculated start period
* @return shortestSubStake The shortest sub stake
* @return minSubStakeDuration Duration of the shortest sub stake
* @return minSubStakeLastPeriod Last period of the shortest sub stake
*/
function getShortestSubStake(
StakerInfo storage _info,
uint16 _currentPeriod,
uint16 _startPeriod
)
internal view returns (
SubStakeInfo storage shortestSubStake,
uint16 minSubStakeDuration,
uint16 minSubStakeLastPeriod
)
{
shortestSubStake = shortestSubStake;
minSubStakeDuration = MAX_UINT16;
minSubStakeLastPeriod = MAX_UINT16;
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod);
if (lastPeriod < subStake.firstPeriod) {
continue;
}
uint16 duration = lastPeriod - subStake.firstPeriod;
if (subStake.firstPeriod <= _currentPeriod &&
lastPeriod >= _currentPeriod &&
(lastPeriod < minSubStakeLastPeriod ||
lastPeriod == minSubStakeLastPeriod && duration < minSubStakeDuration))
{
shortestSubStake = subStake;
minSubStakeDuration = duration;
minSubStakeLastPeriod = lastPeriod;
}
}
}
/**
* @notice Save the old sub stake values to prevent decreasing reward for the previous period
* @dev Saving happens only if the previous period is committed
* @param _info Staker structure
* @param _firstPeriod First period of the old sub stake
* @param _lockedValue Locked value of the old sub stake
* @param _currentPeriod Current period, when the old sub stake is already unlocked
*/
function saveOldSubStake(
StakerInfo storage _info,
uint16 _firstPeriod,
uint256 _lockedValue,
uint16 _currentPeriod
)
internal
{
// Check that the old sub stake should be saved
bool oldCurrentCommittedPeriod = _info.currentCommittedPeriod != 0 &&
_info.currentCommittedPeriod < _currentPeriod;
bool oldnextCommittedPeriod = _info.nextCommittedPeriod != 0 &&
_info.nextCommittedPeriod < _currentPeriod;
bool crosscurrentCommittedPeriod = oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= _firstPeriod;
bool crossnextCommittedPeriod = oldnextCommittedPeriod && _info.nextCommittedPeriod >= _firstPeriod;
if (!crosscurrentCommittedPeriod && !crossnextCommittedPeriod) {
return;
}
// Try to find already existent proper old sub stake
uint16 previousPeriod = _currentPeriod - 1;
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
if (subStake.lastPeriod == previousPeriod &&
((crosscurrentCommittedPeriod ==
(oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= subStake.firstPeriod)) &&
(crossnextCommittedPeriod ==
(oldnextCommittedPeriod && _info.nextCommittedPeriod >= subStake.firstPeriod))))
{
subStake.lockedValue += uint128(_lockedValue);
return;
}
}
saveSubStake(_info, _firstPeriod, previousPeriod, 0, _lockedValue);
}
//-------------Additional getters for stakers info-------------
/**
* @notice Return the length of the array of stakers
*/
function getStakersLength() external view returns (uint256) {
return stakers.length;
}
/**
* @notice Return the length of the array of sub stakes
*/
function getSubStakesLength(address _staker) external view returns (uint256) {
return stakerInfo[_staker].subStakes.length;
}
/**
* @notice Return the information about sub stake
*/
function getSubStakeInfo(address _staker, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released (#1501)
// public view returns (SubStakeInfo)
// TODO "virtual" only for tests, probably will be removed after #1512
external view virtual returns (
uint16 firstPeriod,
uint16 lastPeriod,
uint16 unlockingDuration,
uint128 lockedValue
)
{
SubStakeInfo storage info = stakerInfo[_staker].subStakes[_index];
firstPeriod = info.firstPeriod;
lastPeriod = info.lastPeriod;
unlockingDuration = info.unlockingDuration;
lockedValue = info.lockedValue;
}
/**
* @notice Return the length of the array of past downtime
*/
function getPastDowntimeLength(address _staker) external view returns (uint256) {
return stakerInfo[_staker].pastDowntime.length;
}
/**
* @notice Return the information about past downtime
*/
function getPastDowntime(address _staker, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released (#1501)
// public view returns (Downtime)
external view returns (uint16 startPeriod, uint16 endPeriod)
{
Downtime storage downtime = stakerInfo[_staker].pastDowntime[_index];
startPeriod = downtime.startPeriod;
endPeriod = downtime.endPeriod;
}
//------------------ ERC900 connectors ----------------------
function totalStakedForAt(address _owner, uint256 _blockNumber) public view override returns (uint256){
return stakerInfo[_owner].history.getValueAt(_blockNumber);
}
function totalStakedAt(uint256 _blockNumber) public view override returns (uint256){
return balanceHistory.getValueAt(_blockNumber);
}
function supportsHistory() external pure override returns (bool){
return true;
}
//------------------------Upgradeable------------------------
/**
* @dev Get StakerInfo structure by delegatecall
*/
function delegateGetStakerInfo(address _target, bytes32 _staker)
internal returns (StakerInfo memory result)
{
bytes32 memoryAddress = delegateGetData(_target, this.stakerInfo.selector, 1, _staker, 0);
assembly {
result := memoryAddress
}
}
/**
* @dev Get SubStakeInfo structure by delegatecall
*/
function delegateGetSubStakeInfo(address _target, bytes32 _staker, uint256 _index)
internal returns (SubStakeInfo memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, this.getSubStakeInfo.selector, 2, _staker, bytes32(_index));
assembly {
result := memoryAddress
}
}
/**
* @dev Get Downtime structure by delegatecall
*/
function delegateGetPastDowntime(address _target, bytes32 _staker, uint256 _index)
internal returns (Downtime memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, this.getPastDowntime.selector, 2, _staker, bytes32(_index));
assembly {
result := memoryAddress
}
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
require(delegateGet(_testTarget, this.lockedPerPeriod.selector,
bytes32(bytes2(RESERVED_PERIOD))) == lockedPerPeriod(RESERVED_PERIOD));
require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(0))) ==
stakerFromWorker[address(0)]);
require(delegateGet(_testTarget, this.getStakersLength.selector) == stakers.length);
if (stakers.length == 0) {
return;
}
address stakerAddress = stakers[0];
require(address(uint160(delegateGet(_testTarget, this.stakers.selector, 0))) == stakerAddress);
StakerInfo storage info = stakerInfo[stakerAddress];
bytes32 staker = bytes32(uint256(stakerAddress));
StakerInfo memory infoToCheck = delegateGetStakerInfo(_testTarget, staker);
require(infoToCheck.value == info.value &&
infoToCheck.currentCommittedPeriod == info.currentCommittedPeriod &&
infoToCheck.nextCommittedPeriod == info.nextCommittedPeriod &&
infoToCheck.flags == info.flags &&
infoToCheck.lastCommittedPeriod == info.lastCommittedPeriod &&
infoToCheck.completedWork == info.completedWork &&
infoToCheck.worker == info.worker &&
infoToCheck.workerStartPeriod == info.workerStartPeriod);
require(delegateGet(_testTarget, this.getPastDowntimeLength.selector, staker) ==
info.pastDowntime.length);
for (uint256 i = 0; i < info.pastDowntime.length && i < MAX_CHECKED_VALUES; i++) {
Downtime storage downtime = info.pastDowntime[i];
Downtime memory downtimeToCheck = delegateGetPastDowntime(_testTarget, staker, i);
require(downtimeToCheck.startPeriod == downtime.startPeriod &&
downtimeToCheck.endPeriod == downtime.endPeriod);
}
require(delegateGet(_testTarget, this.getSubStakesLength.selector, staker) == info.subStakes.length);
for (uint256 i = 0; i < info.subStakes.length && i < MAX_CHECKED_VALUES; i++) {
SubStakeInfo storage subStakeInfo = info.subStakes[i];
SubStakeInfo memory subStakeInfoToCheck = delegateGetSubStakeInfo(_testTarget, staker, i);
require(subStakeInfoToCheck.firstPeriod == subStakeInfo.firstPeriod &&
subStakeInfoToCheck.lastPeriod == subStakeInfo.lastPeriod &&
subStakeInfoToCheck.unlockingDuration == subStakeInfo.unlockingDuration &&
subStakeInfoToCheck.lockedValue == subStakeInfo.lockedValue);
}
// it's not perfect because checks not only slot value but also decoding
// at least without additional functions
require(delegateGet(_testTarget, this.totalStakedForAt.selector, staker, bytes32(block.number)) ==
totalStakedForAt(stakerAddress, block.number));
require(delegateGet(_testTarget, this.totalStakedAt.selector, bytes32(block.number)) ==
totalStakedAt(block.number));
if (info.worker != address(0)) {
require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(uint256(info.worker)))) ==
stakerFromWorker[info.worker]);
}
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade`
function finishUpgrade(address _target) public override virtual {
super.finishUpgrade(_target);
// Create fake period
_lockedPerPeriod[RESERVED_PERIOD] = 111;
// Create fake worker
stakerFromWorker[address(0)] = address(this);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.7.0;
// Minimum interface to interact with Aragon's Aggregator
interface IERC900History {
function totalStakedForAt(address addr, uint256 blockNumber) external view returns (uint256);
function totalStakedAt(uint256 blockNumber) external view returns (uint256);
function supportsHistory() external pure returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./NuCypherToken.sol";
import "../zeppelin/math/Math.sol";
import "./proxy/Upgradeable.sol";
import "./lib/AdditionalMath.sol";
import "../zeppelin/token/ERC20/SafeERC20.sol";
/**
* @title Issuer
* @notice Contract for calculation of issued tokens
* @dev |v3.4.1|
*/
abstract contract Issuer is Upgradeable {
using SafeERC20 for NuCypherToken;
using AdditionalMath for uint32;
event Donated(address indexed sender, uint256 value);
/// Issuer is initialized with a reserved reward
event Initialized(uint256 reservedReward);
uint128 constant MAX_UINT128 = uint128(0) - 1;
NuCypherToken public immutable token;
uint128 public immutable totalSupply;
// d * k2
uint256 public immutable mintingCoefficient;
// k1
uint256 public immutable lockDurationCoefficient1;
// k2
uint256 public immutable lockDurationCoefficient2;
uint32 public immutable genesisSecondsPerPeriod;
uint32 public immutable secondsPerPeriod;
// kmax
uint16 public immutable maximumRewardedPeriods;
uint256 public immutable firstPhaseMaxIssuance;
uint256 public immutable firstPhaseTotalSupply;
/**
* Current supply is used in the minting formula and is stored to prevent different calculation
* for stakers which get reward in the same period. There are two values -
* supply for previous period (used in formula) and supply for current period which accumulates value
* before end of period.
*/
uint128 public previousPeriodSupply;
uint128 public currentPeriodSupply;
uint16 public currentMintingPeriod;
/**
* @notice Constructor sets address of token contract and coefficients for minting
* @dev Minting formula for one sub-stake in one period for the first phase
firstPhaseMaxIssuance * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2
* @dev Minting formula for one sub-stake in one period for the second phase
(totalSupply - currentSupply) / d * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2
if allLockedPeriods > maximumRewardedPeriods then allLockedPeriods = maximumRewardedPeriods
* @param _token Token contract
* @param _genesisHoursPerPeriod Size of period in hours at genesis
* @param _hoursPerPeriod Size of period in hours
* @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays,
* only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2.
* See Equation 10 in Staking Protocol & Economics paper
* @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent
* to which a stake's lock duration affects the subsidy it receives. Affects stakers differently.
* Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent
* to which a stake's lock duration affects the subsidy it receives. Affects stakers differently.
* Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier)
* where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration
* no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _firstPhaseTotalSupply Total supply for the first phase
* @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1.
* See Equation 7 in Staking Protocol & Economics paper.
*/
constructor(
NuCypherToken _token,
uint32 _genesisHoursPerPeriod,
uint32 _hoursPerPeriod,
uint256 _issuanceDecayCoefficient,
uint256 _lockDurationCoefficient1,
uint256 _lockDurationCoefficient2,
uint16 _maximumRewardedPeriods,
uint256 _firstPhaseTotalSupply,
uint256 _firstPhaseMaxIssuance
) {
uint256 localTotalSupply = _token.totalSupply();
require(localTotalSupply > 0 &&
_issuanceDecayCoefficient != 0 &&
_hoursPerPeriod != 0 &&
_genesisHoursPerPeriod != 0 &&
_genesisHoursPerPeriod <= _hoursPerPeriod &&
_lockDurationCoefficient1 != 0 &&
_lockDurationCoefficient2 != 0 &&
_maximumRewardedPeriods != 0);
require(localTotalSupply <= uint256(MAX_UINT128), "Token contract has supply more than supported");
uint256 maxLockDurationCoefficient = _maximumRewardedPeriods + _lockDurationCoefficient1;
uint256 localMintingCoefficient = _issuanceDecayCoefficient * _lockDurationCoefficient2;
require(maxLockDurationCoefficient > _maximumRewardedPeriods &&
localMintingCoefficient / _issuanceDecayCoefficient == _lockDurationCoefficient2 &&
// worst case for `totalLockedValue * d * k2`, when totalLockedValue == totalSupply
localTotalSupply * localMintingCoefficient / localTotalSupply == localMintingCoefficient &&
// worst case for `(totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax))`,
// when currentSupply == 0, lockedValue == totalSupply
localTotalSupply * localTotalSupply * maxLockDurationCoefficient / localTotalSupply / localTotalSupply ==
maxLockDurationCoefficient,
"Specified parameters cause overflow");
require(maxLockDurationCoefficient <= _lockDurationCoefficient2,
"Resulting locking duration coefficient must be less than 1");
require(_firstPhaseTotalSupply <= localTotalSupply, "Too many tokens for the first phase");
require(_firstPhaseMaxIssuance <= _firstPhaseTotalSupply, "Reward for the first phase is too high");
token = _token;
secondsPerPeriod = _hoursPerPeriod.mul32(1 hours);
genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours);
lockDurationCoefficient1 = _lockDurationCoefficient1;
lockDurationCoefficient2 = _lockDurationCoefficient2;
maximumRewardedPeriods = _maximumRewardedPeriods;
firstPhaseTotalSupply = _firstPhaseTotalSupply;
firstPhaseMaxIssuance = _firstPhaseMaxIssuance;
totalSupply = uint128(localTotalSupply);
mintingCoefficient = localMintingCoefficient;
}
/**
* @dev Checks contract initialization
*/
modifier isInitialized()
{
require(currentMintingPeriod != 0);
_;
}
/**
* @return Number of current period
*/
function getCurrentPeriod() public view returns (uint16) {
return uint16(block.timestamp / secondsPerPeriod);
}
/**
* @return Recalculate period value using new basis
*/
function recalculatePeriod(uint16 _period) internal view returns (uint16) {
return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod);
}
/**
* @notice Initialize reserved tokens for reward
*/
function initialize(uint256 _reservedReward, address _sourceOfFunds) external onlyOwner {
require(currentMintingPeriod == 0);
// Reserved reward must be sufficient for at least one period of the first phase
require(firstPhaseMaxIssuance <= _reservedReward);
currentMintingPeriod = getCurrentPeriod();
currentPeriodSupply = totalSupply - uint128(_reservedReward);
previousPeriodSupply = currentPeriodSupply;
token.safeTransferFrom(_sourceOfFunds, address(this), _reservedReward);
emit Initialized(_reservedReward);
}
/**
* @notice Function to mint tokens for one period.
* @param _currentPeriod Current period number.
* @param _lockedValue The amount of tokens that were locked by user in specified period.
* @param _totalLockedValue The amount of tokens that were locked by all users in specified period.
* @param _allLockedPeriods The max amount of periods during which tokens will be locked after specified period.
* @return amount Amount of minted tokens.
*/
function mint(
uint16 _currentPeriod,
uint256 _lockedValue,
uint256 _totalLockedValue,
uint16 _allLockedPeriods
)
internal returns (uint256 amount)
{
if (currentPeriodSupply == totalSupply) {
return 0;
}
if (_currentPeriod > currentMintingPeriod) {
previousPeriodSupply = currentPeriodSupply;
currentMintingPeriod = _currentPeriod;
}
uint256 currentReward;
uint256 coefficient;
// first phase
// firstPhaseMaxIssuance * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * k2)
if (previousPeriodSupply + firstPhaseMaxIssuance <= firstPhaseTotalSupply) {
currentReward = firstPhaseMaxIssuance;
coefficient = lockDurationCoefficient2;
// second phase
// (totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * d * k2)
} else {
currentReward = totalSupply - previousPeriodSupply;
coefficient = mintingCoefficient;
}
uint256 allLockedPeriods =
AdditionalMath.min16(_allLockedPeriods, maximumRewardedPeriods) + lockDurationCoefficient1;
amount = (uint256(currentReward) * _lockedValue * allLockedPeriods) /
(_totalLockedValue * coefficient);
// rounding the last reward
uint256 maxReward = getReservedReward();
if (amount == 0) {
amount = 1;
} else if (amount > maxReward) {
amount = maxReward;
}
currentPeriodSupply += uint128(amount);
}
/**
* @notice Return tokens for future minting
* @param _amount Amount of tokens
*/
function unMint(uint256 _amount) internal {
previousPeriodSupply -= uint128(_amount);
currentPeriodSupply -= uint128(_amount);
}
/**
* @notice Donate sender's tokens. Amount of tokens will be returned for future minting
* @param _value Amount to donate
*/
function donate(uint256 _value) external isInitialized {
token.safeTransferFrom(msg.sender, address(this), _value);
unMint(_value);
emit Donated(msg.sender, _value);
}
/**
* @notice Returns the number of tokens that can be minted
*/
function getReservedReward() public view returns (uint256) {
return totalSupply - currentPeriodSupply;
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
require(uint16(delegateGet(_testTarget, this.currentMintingPeriod.selector)) == currentMintingPeriod);
require(uint128(delegateGet(_testTarget, this.previousPeriodSupply.selector)) == previousPeriodSupply);
require(uint128(delegateGet(_testTarget, this.currentPeriodSupply.selector)) == currentPeriodSupply);
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade`
function finishUpgrade(address _target) public override virtual {
super.finishUpgrade(_target);
// recalculate currentMintingPeriod if needed
if (currentMintingPeriod > getCurrentPeriod()) {
currentMintingPeriod = recalculatePeriod(currentMintingPeriod);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../zeppelin/token/ERC20/ERC20.sol";
import "../zeppelin/token/ERC20/ERC20Detailed.sol";
/**
* @title NuCypherToken
* @notice ERC20 token
* @dev Optional approveAndCall() functionality to notify a contract if an approve() has occurred.
*/
contract NuCypherToken is ERC20, ERC20Detailed('NuCypher', 'NU', 18) {
/**
* @notice Set amount of tokens
* @param _totalSupplyOfTokens Total number of tokens
*/
constructor (uint256 _totalSupplyOfTokens) {
_mint(msg.sender, _totalSupplyOfTokens);
}
/**
* @notice Approves and then calls the receiving contract
*
* @dev call the receiveApproval function on the contract you want to be notified.
* receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
*/
function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData)
external returns (bool success)
{
approve(_spender, _value);
TokenRecipient(_spender).receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
/**
* @dev Interface to use the receiveApproval method
*/
interface TokenRecipient {
/**
* @notice Receives a notification of approval of the transfer
* @param _from Sender of approval
* @param _value The amount of tokens to be spent
* @param _tokenContract Address of the token contract
* @param _extraData Extra data
*/
function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes calldata _extraData) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view override 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 override 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 override returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public override 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);
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public override returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
abstract contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
/**
* @notice Base contract for upgradeable contract
* @dev Inherited contract should implement verifyState(address) method by checking storage variables
* (see verifyState(address) in Dispatcher). Also contract should implement finishUpgrade(address)
* if it is using constructor parameters by coping this parameters to the dispatcher storage
*/
abstract contract Upgradeable is Ownable {
event StateVerified(address indexed testTarget, address sender);
event UpgradeFinished(address indexed target, address sender);
/**
* @dev Contracts at the target must reserve the same location in storage for this address as in Dispatcher
* Stored data actually lives in the Dispatcher
* However the storage layout is specified here in the implementing contracts
*/
address public target;
/**
* @dev Previous contract address (if available). Used for rollback
*/
address public previousTarget;
/**
* @dev Upgrade status. Explicit `uint8` type is used instead of `bool` to save gas by excluding 0 value
*/
uint8 public isUpgrade;
/**
* @dev Guarantees that next slot will be separated from the previous
*/
uint256 stubSlot;
/**
* @dev Constants for `isUpgrade` field
*/
uint8 constant UPGRADE_FALSE = 1;
uint8 constant UPGRADE_TRUE = 2;
/**
* @dev Checks that function executed while upgrading
* Recommended to add to `verifyState` and `finishUpgrade` methods
*/
modifier onlyWhileUpgrading()
{
require(isUpgrade == UPGRADE_TRUE);
_;
}
/**
* @dev Method for verifying storage state.
* Should check that new target contract returns right storage value
*/
function verifyState(address _testTarget) public virtual onlyWhileUpgrading {
emit StateVerified(_testTarget, msg.sender);
}
/**
* @dev Copy values from the new target to the current storage
* @param _target New target contract address
*/
function finishUpgrade(address _target) public virtual onlyWhileUpgrading {
emit UpgradeFinished(_target, msg.sender);
}
/**
* @dev Base method to get data
* @param _target Target to call
* @param _selector Method selector
* @param _numberOfArguments Number of used arguments
* @param _argument1 First method argument
* @param _argument2 Second method argument
* @return memoryAddress Address in memory where the data is located
*/
function delegateGetData(
address _target,
bytes4 _selector,
uint8 _numberOfArguments,
bytes32 _argument1,
bytes32 _argument2
)
internal returns (bytes32 memoryAddress)
{
assembly {
memoryAddress := mload(0x40)
mstore(memoryAddress, _selector)
if gt(_numberOfArguments, 0) {
mstore(add(memoryAddress, 0x04), _argument1)
}
if gt(_numberOfArguments, 1) {
mstore(add(memoryAddress, 0x24), _argument2)
}
switch delegatecall(gas(), _target, memoryAddress, add(0x04, mul(0x20, _numberOfArguments)), 0, 0)
case 0 {
revert(memoryAddress, 0)
}
default {
returndatacopy(memoryAddress, 0x0, returndatasize())
}
}
}
/**
* @dev Call "getter" without parameters.
* Result should not exceed 32 bytes
*/
function delegateGet(address _target, bytes4 _selector)
internal returns (uint256 result)
{
bytes32 memoryAddress = delegateGetData(_target, _selector, 0, 0, 0);
assembly {
result := mload(memoryAddress)
}
}
/**
* @dev Call "getter" with one parameter.
* Result should not exceed 32 bytes
*/
function delegateGet(address _target, bytes4 _selector, bytes32 _argument)
internal returns (uint256 result)
{
bytes32 memoryAddress = delegateGetData(_target, _selector, 1, _argument, 0);
assembly {
result := mload(memoryAddress)
}
}
/**
* @dev Call "getter" with two parameters.
* Result should not exceed 32 bytes
*/
function delegateGet(
address _target,
bytes4 _selector,
bytes32 _argument1,
bytes32 _argument2
)
internal returns (uint256 result)
{
bytes32 memoryAddress = delegateGetData(_target, _selector, 2, _argument1, _argument2);
assembly {
result := mload(memoryAddress)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
abstract 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 () {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public virtual 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;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/math/SafeMath.sol";
/**
* @notice Additional math operations
*/
library AdditionalMath {
using SafeMath for uint256;
function max16(uint16 a, uint16 b) internal pure returns (uint16) {
return a >= b ? a : b;
}
function min16(uint16 a, uint16 b) internal pure returns (uint16) {
return a < b ? a : b;
}
/**
* @notice Division and ceil
*/
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
return (a.add(b) - 1) / b;
}
/**
* @dev Adds signed value to unsigned value, throws on overflow.
*/
function addSigned(uint256 a, int256 b) internal pure returns (uint256) {
if (b >= 0) {
return a.add(uint256(b));
} else {
return a.sub(uint256(-b));
}
}
/**
* @dev Subtracts signed value from unsigned value, throws on overflow.
*/
function subSigned(uint256 a, int256 b) internal pure returns (uint256) {
if (b >= 0) {
return a.sub(uint256(b));
} else {
return a.add(uint256(-b));
}
}
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul32(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint32 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add16(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub16(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds signed value to unsigned value, throws on overflow.
*/
function addSigned16(uint16 a, int16 b) internal pure returns (uint16) {
if (b >= 0) {
return add16(a, uint16(b));
} else {
return sub16(a, uint16(-b));
}
}
/**
* @dev Subtracts signed value from unsigned value, throws on overflow.
*/
function subSigned16(uint16 a, int16 b) internal pure returns (uint16) {
if (b >= 0) {
return sub16(a, uint16(b));
} else {
return add16(a, uint16(-b));
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* 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;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(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'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @dev Taken from https://github.com/ethereum/solidity-examples/blob/master/src/bits/Bits.sol
*/
library Bits {
uint256 internal constant ONE = uint256(1);
/**
* @notice Sets the bit at the given 'index' in 'self' to:
* '1' - if the bit is '0'
* '0' - if the bit is '1'
* @return The modified value
*/
function toggleBit(uint256 self, uint8 index) internal pure returns (uint256) {
return self ^ ONE << index;
}
/**
* @notice Get the value of the bit at the given 'index' in 'self'.
*/
function bit(uint256 self, uint8 index) internal pure returns (uint8) {
return uint8(self >> index & 1);
}
/**
* @notice Check if the bit at the given 'index' in 'self' is set.
* @return 'true' - if the value of the bit is '1',
* 'false' - if the value of the bit is '0'
*/
function bitSet(uint256 self, uint8 index) internal pure returns (bool) {
return self >> index & 1 == 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @title Snapshot
* @notice Manages snapshots of size 128 bits (32 bits for timestamp, 96 bits for value)
* 96 bits is enough for storing NU token values, and 32 bits should be OK for block numbers
* @dev Since each storage slot can hold two snapshots, new slots are allocated every other TX. Thus, gas cost of adding snapshots is 51400 and 36400 gas, alternately.
* Based on Aragon's Checkpointing (https://https://github.com/aragonone/voting-connectors/blob/master/shared/contract-utils/contracts/Checkpointing.sol)
* On average, adding snapshots spends ~6500 less gas than the 256-bit checkpoints of Aragon's Checkpointing
*/
library Snapshot {
function encodeSnapshot(uint32 _time, uint96 _value) internal pure returns(uint128) {
return uint128(uint256(_time) << 96 | uint256(_value));
}
function decodeSnapshot(uint128 _snapshot) internal pure returns(uint32 time, uint96 value){
time = uint32(bytes4(bytes16(_snapshot)));
value = uint96(_snapshot);
}
function addSnapshot(uint128[] storage _self, uint256 _value) internal {
addSnapshot(_self, block.number, _value);
}
function addSnapshot(uint128[] storage _self, uint256 _time, uint256 _value) internal {
uint256 length = _self.length;
if (length != 0) {
(uint32 currentTime, ) = decodeSnapshot(_self[length - 1]);
if (uint32(_time) == currentTime) {
_self[length - 1] = encodeSnapshot(uint32(_time), uint96(_value));
return;
} else if (uint32(_time) < currentTime){
revert();
}
}
_self.push(encodeSnapshot(uint32(_time), uint96(_value)));
}
function lastSnapshot(uint128[] storage _self) internal view returns (uint32, uint96) {
uint256 length = _self.length;
if (length > 0) {
return decodeSnapshot(_self[length - 1]);
}
return (0, 0);
}
function lastValue(uint128[] storage _self) internal view returns (uint96) {
(, uint96 value) = lastSnapshot(_self);
return value;
}
function getValueAt(uint128[] storage _self, uint256 _time256) internal view returns (uint96) {
uint32 _time = uint32(_time256);
uint256 length = _self.length;
// Short circuit if there's no checkpoints yet
// Note that this also lets us avoid using SafeMath later on, as we've established that
// there must be at least one checkpoint
if (length == 0) {
return 0;
}
// Check last checkpoint
uint256 lastIndex = length - 1;
(uint32 snapshotTime, uint96 snapshotValue) = decodeSnapshot(_self[length - 1]);
if (_time >= snapshotTime) {
return snapshotValue;
}
// Check first checkpoint (if not already checked with the above check on last)
(snapshotTime, snapshotValue) = decodeSnapshot(_self[0]);
if (length == 1 || _time < snapshotTime) {
return 0;
}
// Do binary search
// As we've already checked both ends, we don't need to check the last checkpoint again
uint256 low = 0;
uint256 high = lastIndex - 1;
uint32 midTime;
uint96 midValue;
while (high > low) {
uint256 mid = (high + low + 1) / 2; // average, ceil round
(midTime, midValue) = decodeSnapshot(_self[mid]);
if (_time > midTime) {
low = mid;
} else if (_time < midTime) {
// Note that we don't need SafeMath here because mid must always be greater than 0
// from the while condition
high = mid - 1;
} else {
// _time == midTime
return midValue;
}
}
(, snapshotValue) = decodeSnapshot(_self[low]);
return snapshotValue;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.7.0;
interface IForwarder {
function isForwarder() external pure returns (bool);
function canForward(address sender, bytes calldata evmCallScript) external view returns (bool);
function forward(bytes calldata evmCallScript) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.7.0;
interface TokenManager {
function mint(address _receiver, uint256 _amount) external;
function issue(uint256 _amount) external;
function assign(address _receiver, uint256 _amount) external;
function burn(address _holder, uint256 _amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.7.0;
import "./IForwarder.sol";
// Interface for Voting contract, as found in https://github.com/aragon/aragon-apps/blob/master/apps/voting/contracts/Voting.sol
interface Voting is IForwarder{
enum VoterState { Absent, Yea, Nay }
// Public getters
function token() external returns (address);
function supportRequiredPct() external returns (uint64);
function minAcceptQuorumPct() external returns (uint64);
function voteTime() external returns (uint64);
function votesLength() external returns (uint256);
// Setters
function changeSupportRequiredPct(uint64 _supportRequiredPct) external;
function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external;
// Creating new votes
function newVote(bytes calldata _executionScript, string memory _metadata) external returns (uint256 voteId);
function newVote(bytes calldata _executionScript, string memory _metadata, bool _castVote, bool _executesIfDecided)
external returns (uint256 voteId);
// Voting
function canVote(uint256 _voteId, address _voter) external view returns (bool);
function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external;
// Executing a passed vote
function canExecute(uint256 _voteId) external view returns (bool);
function executeVote(uint256 _voteId) external;
// Additional info
function getVote(uint256 _voteId) external view
returns (
bool open,
bool executed,
uint64 startDate,
uint64 snapshotBlock,
uint64 supportRequired,
uint64 minAcceptQuorum,
uint256 yea,
uint256 nay,
uint256 votingPower,
bytes memory script
);
function getVoterState(uint256 _voteId, address _voter) external view returns (VoterState);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../zeppelin/math/SafeMath.sol";
/**
* @notice Multi-signature contract with off-chain signing
*/
contract MultiSig {
using SafeMath for uint256;
event Executed(address indexed sender, uint256 indexed nonce, address indexed destination, uint256 value);
event OwnerAdded(address indexed owner);
event OwnerRemoved(address indexed owner);
event RequirementChanged(uint16 required);
uint256 constant public MAX_OWNER_COUNT = 50;
uint256 public nonce;
uint8 public required;
mapping (address => bool) public isOwner;
address[] public owners;
/**
* @notice Only this contract can call method
*/
modifier onlyThisContract() {
require(msg.sender == address(this));
_;
}
receive() external payable {}
/**
* @param _required Number of required signings
* @param _owners List of initial owners.
*/
constructor (uint8 _required, address[] memory _owners) {
require(_owners.length <= MAX_OWNER_COUNT &&
_required <= _owners.length &&
_required > 0);
for (uint256 i = 0; i < _owners.length; i++) {
address owner = _owners[i];
require(!isOwner[owner] && owner != address(0));
isOwner[owner] = true;
}
owners = _owners;
required = _required;
}
/**
* @notice Get unsigned hash for transaction parameters
* @dev Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191
* @param _sender Trustee who will execute the transaction
* @param _destination Destination address
* @param _value Amount of ETH to transfer
* @param _data Call data
* @param _nonce Nonce
*/
function getUnsignedTransactionHash(
address _sender,
address _destination,
uint256 _value,
bytes memory _data,
uint256 _nonce
)
public view returns (bytes32)
{
return keccak256(
abi.encodePacked(byte(0x19), byte(0), address(this), _sender, _destination, _value, _data, _nonce));
}
/**
* @dev Note that address recovered from signatures must be strictly increasing
* @param _sigV Array of signatures values V
* @param _sigR Array of signatures values R
* @param _sigS Array of signatures values S
* @param _destination Destination address
* @param _value Amount of ETH to transfer
* @param _data Call data
*/
function execute(
uint8[] calldata _sigV,
bytes32[] calldata _sigR,
bytes32[] calldata _sigS,
address _destination,
uint256 _value,
bytes calldata _data
)
external
{
require(_sigR.length >= required &&
_sigR.length == _sigS.length &&
_sigR.length == _sigV.length);
bytes32 txHash = getUnsignedTransactionHash(msg.sender, _destination, _value, _data, nonce);
address lastAdd = address(0);
for (uint256 i = 0; i < _sigR.length; i++) {
address recovered = ecrecover(txHash, _sigV[i], _sigR[i], _sigS[i]);
require(recovered > lastAdd && isOwner[recovered]);
lastAdd = recovered;
}
emit Executed(msg.sender, nonce, _destination, _value);
nonce = nonce.add(1);
(bool callSuccess,) = _destination.call{value: _value}(_data);
require(callSuccess);
}
/**
* @notice Allows to add a new owner
* @dev Transaction has to be sent by `execute` method.
* @param _owner Address of new owner
*/
function addOwner(address _owner)
external
onlyThisContract
{
require(owners.length < MAX_OWNER_COUNT &&
_owner != address(0) &&
!isOwner[_owner]);
isOwner[_owner] = true;
owners.push(_owner);
emit OwnerAdded(_owner);
}
/**
* @notice Allows to remove an owner
* @dev Transaction has to be sent by `execute` method.
* @param _owner Address of owner
*/
function removeOwner(address _owner)
external
onlyThisContract
{
require(owners.length > required && isOwner[_owner]);
isOwner[_owner] = false;
for (uint256 i = 0; i < owners.length - 1; i++) {
if (owners[i] == _owner) {
owners[i] = owners[owners.length - 1];
break;
}
}
owners.pop();
emit OwnerRemoved(_owner);
}
/**
* @notice Returns the number of owners of this MultiSig
*/
function getNumberOfOwners() external view returns (uint256) {
return owners.length;
}
/**
* @notice Allows to change the number of required signatures
* @dev Transaction has to be sent by `execute` method
* @param _required Number of required signatures
*/
function changeRequirement(uint8 _required)
external
onlyThisContract
{
require(_required <= owners.length && _required > 0);
required = _required;
emit RequirementChanged(_required);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../zeppelin/token/ERC20/SafeERC20.sol";
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/math/Math.sol";
import "../zeppelin/utils/Address.sol";
import "./lib/AdditionalMath.sol";
import "./lib/SignatureVerifier.sol";
import "./StakingEscrow.sol";
import "./NuCypherToken.sol";
import "./proxy/Upgradeable.sol";
/**
* @title PolicyManager
* @notice Contract holds policy data and locks accrued policy fees
* @dev |v6.3.1|
*/
contract PolicyManager is Upgradeable {
using SafeERC20 for NuCypherToken;
using SafeMath for uint256;
using AdditionalMath for uint256;
using AdditionalMath for int256;
using AdditionalMath for uint16;
using Address for address payable;
event PolicyCreated(
bytes16 indexed policyId,
address indexed sponsor,
address indexed owner,
uint256 feeRate,
uint64 startTimestamp,
uint64 endTimestamp,
uint256 numberOfNodes
);
event ArrangementRevoked(
bytes16 indexed policyId,
address indexed sender,
address indexed node,
uint256 value
);
event RefundForArrangement(
bytes16 indexed policyId,
address indexed sender,
address indexed node,
uint256 value
);
event PolicyRevoked(bytes16 indexed policyId, address indexed sender, uint256 value);
event RefundForPolicy(bytes16 indexed policyId, address indexed sender, uint256 value);
event MinFeeRateSet(address indexed node, uint256 value);
// TODO #1501
// Range range
event FeeRateRangeSet(address indexed sender, uint256 min, uint256 defaultValue, uint256 max);
event Withdrawn(address indexed node, address indexed recipient, uint256 value);
struct ArrangementInfo {
address node;
uint256 indexOfDowntimePeriods;
uint16 lastRefundedPeriod;
}
struct Policy {
bool disabled;
address payable sponsor;
address owner;
uint128 feeRate;
uint64 startTimestamp;
uint64 endTimestamp;
uint256 reservedSlot1;
uint256 reservedSlot2;
uint256 reservedSlot3;
uint256 reservedSlot4;
uint256 reservedSlot5;
ArrangementInfo[] arrangements;
}
struct NodeInfo {
uint128 fee;
uint16 previousFeePeriod;
uint256 feeRate;
uint256 minFeeRate;
mapping (uint16 => int256) stub; // former slot for feeDelta
mapping (uint16 => int256) feeDelta;
}
// TODO used only for `delegateGetNodeInfo`, probably will be removed after #1512
struct MemoryNodeInfo {
uint128 fee;
uint16 previousFeePeriod;
uint256 feeRate;
uint256 minFeeRate;
}
struct Range {
uint128 min;
uint128 defaultValue;
uint128 max;
}
bytes16 internal constant RESERVED_POLICY_ID = bytes16(0);
address internal constant RESERVED_NODE = address(0);
uint256 internal constant MAX_BALANCE = uint256(uint128(0) - 1);
// controlled overflow to get max int256
int256 public constant DEFAULT_FEE_DELTA = int256((uint256(0) - 1) >> 1);
StakingEscrow public immutable escrow;
uint32 public immutable genesisSecondsPerPeriod;
uint32 public immutable secondsPerPeriod;
mapping (bytes16 => Policy) public policies;
mapping (address => NodeInfo) public nodes;
Range public feeRateRange;
uint64 public resetTimestamp;
/**
* @notice Constructor sets address of the escrow contract
* @dev Put same address in both inputs variables except when migration is happening
* @param _escrowDispatcher Address of escrow dispatcher
* @param _escrowImplementation Address of escrow implementation
*/
constructor(StakingEscrow _escrowDispatcher, StakingEscrow _escrowImplementation) {
escrow = _escrowDispatcher;
// if the input address is not the StakingEscrow then calling `secondsPerPeriod` will throw error
uint32 localSecondsPerPeriod = _escrowImplementation.secondsPerPeriod();
require(localSecondsPerPeriod > 0);
secondsPerPeriod = localSecondsPerPeriod;
uint32 localgenesisSecondsPerPeriod = _escrowImplementation.genesisSecondsPerPeriod();
require(localgenesisSecondsPerPeriod > 0);
genesisSecondsPerPeriod = localgenesisSecondsPerPeriod;
// handle case when we deployed new StakingEscrow but not yet upgraded
if (_escrowDispatcher != _escrowImplementation) {
require(_escrowDispatcher.secondsPerPeriod() == localSecondsPerPeriod ||
_escrowDispatcher.secondsPerPeriod() == localgenesisSecondsPerPeriod);
}
}
/**
* @dev Checks that sender is the StakingEscrow contract
*/
modifier onlyEscrowContract()
{
require(msg.sender == address(escrow));
_;
}
/**
* @return Number of current period
*/
function getCurrentPeriod() public view returns (uint16) {
return uint16(block.timestamp / secondsPerPeriod);
}
/**
* @return Recalculate period value using new basis
*/
function recalculatePeriod(uint16 _period) internal view returns (uint16) {
return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod);
}
/**
* @notice Register a node
* @param _node Node address
* @param _period Initial period
*/
function register(address _node, uint16 _period) external onlyEscrowContract {
NodeInfo storage nodeInfo = nodes[_node];
require(nodeInfo.previousFeePeriod == 0 && _period < getCurrentPeriod());
nodeInfo.previousFeePeriod = _period;
}
/**
* @notice Migrate from the old period length to the new one
* @param _node Node address
*/
function migrate(address _node) external onlyEscrowContract {
NodeInfo storage nodeInfo = nodes[_node];
// with previous period length any previousFeePeriod will be greater than current period
// this is a sign of not migrated node
require(nodeInfo.previousFeePeriod >= getCurrentPeriod());
nodeInfo.previousFeePeriod = recalculatePeriod(nodeInfo.previousFeePeriod);
nodeInfo.feeRate = 0;
}
/**
* @notice Set minimum, default & maximum fee rate for all stakers and all policies ('global fee range')
*/
// TODO # 1501
// function setFeeRateRange(Range calldata _range) external onlyOwner {
function setFeeRateRange(uint128 _min, uint128 _default, uint128 _max) external onlyOwner {
require(_min <= _default && _default <= _max);
feeRateRange = Range(_min, _default, _max);
emit FeeRateRangeSet(msg.sender, _min, _default, _max);
}
/**
* @notice Set the minimum acceptable fee rate (set by staker for their associated worker)
* @dev Input value must fall within `feeRateRange` (global fee range)
*/
function setMinFeeRate(uint256 _minFeeRate) external {
require(_minFeeRate >= feeRateRange.min &&
_minFeeRate <= feeRateRange.max,
"The staker's min fee rate must fall within the global fee range");
NodeInfo storage nodeInfo = nodes[msg.sender];
if (nodeInfo.minFeeRate == _minFeeRate) {
return;
}
nodeInfo.minFeeRate = _minFeeRate;
emit MinFeeRateSet(msg.sender, _minFeeRate);
}
/**
* @notice Get the minimum acceptable fee rate (set by staker for their associated worker)
*/
function getMinFeeRate(NodeInfo storage _nodeInfo) internal view returns (uint256) {
// if minFeeRate has not been set or chosen value falls outside the global fee range
// a default value is returned instead
if (_nodeInfo.minFeeRate == 0 ||
_nodeInfo.minFeeRate < feeRateRange.min ||
_nodeInfo.minFeeRate > feeRateRange.max) {
return feeRateRange.defaultValue;
} else {
return _nodeInfo.minFeeRate;
}
}
/**
* @notice Get the minimum acceptable fee rate (set by staker for their associated worker)
*/
function getMinFeeRate(address _node) public view returns (uint256) {
NodeInfo storage nodeInfo = nodes[_node];
return getMinFeeRate(nodeInfo);
}
/**
* @notice Create policy
* @dev Generate policy id before creation
* @param _policyId Policy id
* @param _policyOwner Policy owner. Zero address means sender is owner
* @param _endTimestamp End timestamp of the policy in seconds
* @param _nodes Nodes that will handle policy
*/
function createPolicy(
bytes16 _policyId,
address _policyOwner,
uint64 _endTimestamp,
address[] calldata _nodes
)
external payable
{
require(
_endTimestamp > block.timestamp &&
msg.value > 0
);
require(address(this).balance <= MAX_BALANCE);
uint16 currentPeriod = getCurrentPeriod();
uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1;
uint256 numberOfPeriods = endPeriod - currentPeriod;
uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods);
require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length == msg.value);
Policy storage policy = createPolicy(_policyId, _policyOwner, _endTimestamp, feeRate, _nodes.length);
for (uint256 i = 0; i < _nodes.length; i++) {
address node = _nodes[i];
addFeeToNode(currentPeriod, endPeriod, node, feeRate, int256(feeRate));
policy.arrangements.push(ArrangementInfo(node, 0, 0));
}
}
/**
* @notice Create multiple policies with the same owner, nodes and length
* @dev Generate policy ids before creation
* @param _policyIds Policy ids
* @param _policyOwner Policy owner. Zero address means sender is owner
* @param _endTimestamp End timestamp of all policies in seconds
* @param _nodes Nodes that will handle all policies
*/
function createPolicies(
bytes16[] calldata _policyIds,
address _policyOwner,
uint64 _endTimestamp,
address[] calldata _nodes
)
external payable
{
require(
_endTimestamp > block.timestamp &&
msg.value > 0 &&
_policyIds.length > 1
);
require(address(this).balance <= MAX_BALANCE);
uint16 currentPeriod = getCurrentPeriod();
uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1;
uint256 numberOfPeriods = endPeriod - currentPeriod;
uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods / _policyIds.length);
require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length * _policyIds.length == msg.value);
for (uint256 i = 0; i < _policyIds.length; i++) {
Policy storage policy = createPolicy(_policyIds[i], _policyOwner, _endTimestamp, feeRate, _nodes.length);
for (uint256 j = 0; j < _nodes.length; j++) {
policy.arrangements.push(ArrangementInfo(_nodes[j], 0, 0));
}
}
int256 fee = int256(_policyIds.length * feeRate);
for (uint256 i = 0; i < _nodes.length; i++) {
address node = _nodes[i];
addFeeToNode(currentPeriod, endPeriod, node, feeRate, fee);
}
}
/**
* @notice Create policy
* @param _policyId Policy id
* @param _policyOwner Policy owner. Zero address means sender is owner
* @param _endTimestamp End timestamp of the policy in seconds
* @param _feeRate Fee rate for policy
* @param _nodesLength Number of nodes that will handle policy
*/
function createPolicy(
bytes16 _policyId,
address _policyOwner,
uint64 _endTimestamp,
uint128 _feeRate,
uint256 _nodesLength
)
internal returns (Policy storage policy)
{
policy = policies[_policyId];
require(
_policyId != RESERVED_POLICY_ID &&
policy.feeRate == 0 &&
!policy.disabled
);
policy.sponsor = msg.sender;
policy.startTimestamp = uint64(block.timestamp);
policy.endTimestamp = _endTimestamp;
policy.feeRate = _feeRate;
if (_policyOwner != msg.sender && _policyOwner != address(0)) {
policy.owner = _policyOwner;
}
emit PolicyCreated(
_policyId,
msg.sender,
_policyOwner == address(0) ? msg.sender : _policyOwner,
_feeRate,
policy.startTimestamp,
policy.endTimestamp,
_nodesLength
);
}
/**
* @notice Increase fee rate for specified node
* @param _currentPeriod Current period
* @param _endPeriod End period of policy
* @param _node Node that will handle policy
* @param _feeRate Fee rate for one policy
* @param _overallFeeRate Fee rate for all policies
*/
function addFeeToNode(
uint16 _currentPeriod,
uint16 _endPeriod,
address _node,
uint128 _feeRate,
int256 _overallFeeRate
)
internal
{
require(_node != RESERVED_NODE);
NodeInfo storage nodeInfo = nodes[_node];
require(nodeInfo.previousFeePeriod != 0 &&
nodeInfo.previousFeePeriod < _currentPeriod &&
_feeRate >= getMinFeeRate(nodeInfo));
// Check default value for feeDelta
if (nodeInfo.feeDelta[_currentPeriod] == DEFAULT_FEE_DELTA) {
nodeInfo.feeDelta[_currentPeriod] = _overallFeeRate;
} else {
// Overflow protection removed, because ETH total supply less than uint255/int256
nodeInfo.feeDelta[_currentPeriod] += _overallFeeRate;
}
if (nodeInfo.feeDelta[_endPeriod] == DEFAULT_FEE_DELTA) {
nodeInfo.feeDelta[_endPeriod] = -_overallFeeRate;
} else {
nodeInfo.feeDelta[_endPeriod] -= _overallFeeRate;
}
// Reset to default value if needed
if (nodeInfo.feeDelta[_currentPeriod] == 0) {
nodeInfo.feeDelta[_currentPeriod] = DEFAULT_FEE_DELTA;
}
if (nodeInfo.feeDelta[_endPeriod] == 0) {
nodeInfo.feeDelta[_endPeriod] = DEFAULT_FEE_DELTA;
}
}
/**
* @notice Get policy owner
*/
function getPolicyOwner(bytes16 _policyId) public view returns (address) {
Policy storage policy = policies[_policyId];
return policy.owner == address(0) ? policy.sponsor : policy.owner;
}
/**
* @notice Call from StakingEscrow to update node info once per period.
* Set default `feeDelta` value for specified period and update node fee
* @param _node Node address
* @param _processedPeriod1 Processed period
* @param _processedPeriod2 Processed period
* @param _periodToSetDefault Period to set
*/
function ping(
address _node,
uint16 _processedPeriod1,
uint16 _processedPeriod2,
uint16 _periodToSetDefault
)
external onlyEscrowContract
{
NodeInfo storage node = nodes[_node];
// protection from calling not migrated node, see migrate()
require(node.previousFeePeriod <= getCurrentPeriod());
if (_processedPeriod1 != 0) {
updateFee(node, _processedPeriod1);
}
if (_processedPeriod2 != 0) {
updateFee(node, _processedPeriod2);
}
// This code increases gas cost for node in trade of decreasing cost for policy sponsor
if (_periodToSetDefault != 0 && node.feeDelta[_periodToSetDefault] == 0) {
node.feeDelta[_periodToSetDefault] = DEFAULT_FEE_DELTA;
}
}
/**
* @notice Update node fee
* @param _info Node info structure
* @param _period Processed period
*/
function updateFee(NodeInfo storage _info, uint16 _period) internal {
if (_info.previousFeePeriod == 0 || _period <= _info.previousFeePeriod) {
return;
}
for (uint16 i = _info.previousFeePeriod + 1; i <= _period; i++) {
int256 delta = _info.feeDelta[i];
if (delta == DEFAULT_FEE_DELTA) {
// gas refund
_info.feeDelta[i] = 0;
continue;
}
_info.feeRate = _info.feeRate.addSigned(delta);
// gas refund
_info.feeDelta[i] = 0;
}
_info.previousFeePeriod = _period;
_info.fee += uint128(_info.feeRate);
}
/**
* @notice Withdraw fee by node
*/
function withdraw() external returns (uint256) {
return withdraw(msg.sender);
}
/**
* @notice Withdraw fee by node
* @param _recipient Recipient of the fee
*/
function withdraw(address payable _recipient) public returns (uint256) {
NodeInfo storage node = nodes[msg.sender];
uint256 fee = node.fee;
require(fee != 0);
node.fee = 0;
_recipient.sendValue(fee);
emit Withdrawn(msg.sender, _recipient, fee);
return fee;
}
/**
* @notice Calculate amount of refund
* @param _policy Policy
* @param _arrangement Arrangement
*/
function calculateRefundValue(Policy storage _policy, ArrangementInfo storage _arrangement)
internal view returns (uint256 refundValue, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod)
{
uint16 policyStartPeriod = uint16(_policy.startTimestamp / secondsPerPeriod);
uint16 maxPeriod = AdditionalMath.min16(getCurrentPeriod(), uint16(_policy.endTimestamp / secondsPerPeriod));
uint16 minPeriod = AdditionalMath.max16(policyStartPeriod, _arrangement.lastRefundedPeriod);
uint16 downtimePeriods = 0;
uint256 length = escrow.getPastDowntimeLength(_arrangement.node);
uint256 initialIndexOfDowntimePeriods;
if (_arrangement.lastRefundedPeriod == 0) {
initialIndexOfDowntimePeriods = escrow.findIndexOfPastDowntime(_arrangement.node, policyStartPeriod);
} else {
initialIndexOfDowntimePeriods = _arrangement.indexOfDowntimePeriods;
}
for (indexOfDowntimePeriods = initialIndexOfDowntimePeriods;
indexOfDowntimePeriods < length;
indexOfDowntimePeriods++)
{
(uint16 startPeriod, uint16 endPeriod) =
escrow.getPastDowntime(_arrangement.node, indexOfDowntimePeriods);
if (startPeriod > maxPeriod) {
break;
} else if (endPeriod < minPeriod) {
continue;
}
downtimePeriods += AdditionalMath.min16(maxPeriod, endPeriod)
.sub16(AdditionalMath.max16(minPeriod, startPeriod)) + 1;
if (maxPeriod <= endPeriod) {
break;
}
}
uint16 lastCommittedPeriod = escrow.getLastCommittedPeriod(_arrangement.node);
if (indexOfDowntimePeriods == length && lastCommittedPeriod < maxPeriod) {
// Overflow protection removed:
// lastCommittedPeriod < maxPeriod and minPeriod <= maxPeriod + 1
downtimePeriods += maxPeriod - AdditionalMath.max16(minPeriod - 1, lastCommittedPeriod);
}
refundValue = _policy.feeRate * downtimePeriods;
lastRefundedPeriod = maxPeriod + 1;
}
/**
* @notice Revoke/refund arrangement/policy by the sponsor
* @param _policyId Policy id
* @param _node Node that will be excluded or RESERVED_NODE if full policy should be used
( @param _forceRevoke Force revoke arrangement/policy
*/
function refundInternal(bytes16 _policyId, address _node, bool _forceRevoke)
internal returns (uint256 refundValue)
{
refundValue = 0;
Policy storage policy = policies[_policyId];
require(!policy.disabled && policy.startTimestamp >= resetTimestamp);
uint16 endPeriod = uint16(policy.endTimestamp / secondsPerPeriod) + 1;
uint256 numberOfActive = policy.arrangements.length;
uint256 i = 0;
for (; i < policy.arrangements.length; i++) {
ArrangementInfo storage arrangement = policy.arrangements[i];
address node = arrangement.node;
if (node == RESERVED_NODE || _node != RESERVED_NODE && _node != node) {
numberOfActive--;
continue;
}
uint256 nodeRefundValue;
(nodeRefundValue, arrangement.indexOfDowntimePeriods, arrangement.lastRefundedPeriod) =
calculateRefundValue(policy, arrangement);
if (_forceRevoke) {
NodeInfo storage nodeInfo = nodes[node];
// Check default value for feeDelta
uint16 lastRefundedPeriod = arrangement.lastRefundedPeriod;
if (nodeInfo.feeDelta[lastRefundedPeriod] == DEFAULT_FEE_DELTA) {
nodeInfo.feeDelta[lastRefundedPeriod] = -int256(policy.feeRate);
} else {
nodeInfo.feeDelta[lastRefundedPeriod] -= int256(policy.feeRate);
}
if (nodeInfo.feeDelta[endPeriod] == DEFAULT_FEE_DELTA) {
nodeInfo.feeDelta[endPeriod] = int256(policy.feeRate);
} else {
nodeInfo.feeDelta[endPeriod] += int256(policy.feeRate);
}
// Reset to default value if needed
if (nodeInfo.feeDelta[lastRefundedPeriod] == 0) {
nodeInfo.feeDelta[lastRefundedPeriod] = DEFAULT_FEE_DELTA;
}
if (nodeInfo.feeDelta[endPeriod] == 0) {
nodeInfo.feeDelta[endPeriod] = DEFAULT_FEE_DELTA;
}
nodeRefundValue += uint256(endPeriod - lastRefundedPeriod) * policy.feeRate;
}
if (_forceRevoke || arrangement.lastRefundedPeriod >= endPeriod) {
arrangement.node = RESERVED_NODE;
arrangement.indexOfDowntimePeriods = 0;
arrangement.lastRefundedPeriod = 0;
numberOfActive--;
emit ArrangementRevoked(_policyId, msg.sender, node, nodeRefundValue);
} else {
emit RefundForArrangement(_policyId, msg.sender, node, nodeRefundValue);
}
refundValue += nodeRefundValue;
if (_node != RESERVED_NODE) {
break;
}
}
address payable policySponsor = policy.sponsor;
if (_node == RESERVED_NODE) {
if (numberOfActive == 0) {
policy.disabled = true;
// gas refund
policy.sponsor = address(0);
policy.owner = address(0);
policy.feeRate = 0;
policy.startTimestamp = 0;
policy.endTimestamp = 0;
emit PolicyRevoked(_policyId, msg.sender, refundValue);
} else {
emit RefundForPolicy(_policyId, msg.sender, refundValue);
}
} else {
// arrangement not found
require(i < policy.arrangements.length);
}
if (refundValue > 0) {
policySponsor.sendValue(refundValue);
}
}
/**
* @notice Calculate amount of refund
* @param _policyId Policy id
* @param _node Node or RESERVED_NODE if all nodes should be used
*/
function calculateRefundValueInternal(bytes16 _policyId, address _node)
internal view returns (uint256 refundValue)
{
refundValue = 0;
Policy storage policy = policies[_policyId];
require((policy.owner == msg.sender || policy.sponsor == msg.sender) && !policy.disabled);
uint256 i = 0;
for (; i < policy.arrangements.length; i++) {
ArrangementInfo storage arrangement = policy.arrangements[i];
if (arrangement.node == RESERVED_NODE || _node != RESERVED_NODE && _node != arrangement.node) {
continue;
}
(uint256 nodeRefundValue,,) = calculateRefundValue(policy, arrangement);
refundValue += nodeRefundValue;
if (_node != RESERVED_NODE) {
break;
}
}
if (_node != RESERVED_NODE) {
// arrangement not found
require(i < policy.arrangements.length);
}
}
/**
* @notice Revoke policy by the sponsor
* @param _policyId Policy id
*/
function revokePolicy(bytes16 _policyId) external returns (uint256 refundValue) {
require(getPolicyOwner(_policyId) == msg.sender);
return refundInternal(_policyId, RESERVED_NODE, true);
}
/**
* @notice Revoke arrangement by the sponsor
* @param _policyId Policy id
* @param _node Node that will be excluded
*/
function revokeArrangement(bytes16 _policyId, address _node)
external returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
require(getPolicyOwner(_policyId) == msg.sender);
return refundInternal(_policyId, _node, true);
}
/**
* @notice Get unsigned hash for revocation
* @param _policyId Policy id
* @param _node Node that will be excluded
* @return Revocation hash, EIP191 version 0x45 ('E')
*/
function getRevocationHash(bytes16 _policyId, address _node) public view returns (bytes32) {
return SignatureVerifier.hashEIP191(abi.encodePacked(_policyId, _node), byte(0x45));
}
/**
* @notice Check correctness of signature
* @param _policyId Policy id
* @param _node Node that will be excluded, zero address if whole policy will be revoked
* @param _signature Signature of owner
*/
function checkOwnerSignature(bytes16 _policyId, address _node, bytes memory _signature) internal view {
bytes32 hash = getRevocationHash(_policyId, _node);
address recovered = SignatureVerifier.recover(hash, _signature);
require(getPolicyOwner(_policyId) == recovered);
}
/**
* @notice Revoke policy or arrangement using owner's signature
* @param _policyId Policy id
* @param _node Node that will be excluded, zero address if whole policy will be revoked
* @param _signature Signature of owner, EIP191 version 0x45 ('E')
*/
function revoke(bytes16 _policyId, address _node, bytes calldata _signature)
external returns (uint256 refundValue)
{
checkOwnerSignature(_policyId, _node, _signature);
return refundInternal(_policyId, _node, true);
}
/**
* @notice Refund part of fee by the sponsor
* @param _policyId Policy id
*/
function refund(bytes16 _policyId) external {
Policy storage policy = policies[_policyId];
require(policy.owner == msg.sender || policy.sponsor == msg.sender);
refundInternal(_policyId, RESERVED_NODE, false);
}
/**
* @notice Refund part of one node's fee by the sponsor
* @param _policyId Policy id
* @param _node Node address
*/
function refund(bytes16 _policyId, address _node)
external returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
Policy storage policy = policies[_policyId];
require(policy.owner == msg.sender || policy.sponsor == msg.sender);
return refundInternal(_policyId, _node, false);
}
/**
* @notice Calculate amount of refund
* @param _policyId Policy id
*/
function calculateRefundValue(bytes16 _policyId)
external view returns (uint256 refundValue)
{
return calculateRefundValueInternal(_policyId, RESERVED_NODE);
}
/**
* @notice Calculate amount of refund
* @param _policyId Policy id
* @param _node Node
*/
function calculateRefundValue(bytes16 _policyId, address _node)
external view returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
return calculateRefundValueInternal(_policyId, _node);
}
/**
* @notice Get number of arrangements in the policy
* @param _policyId Policy id
*/
function getArrangementsLength(bytes16 _policyId) external view returns (uint256) {
return policies[_policyId].arrangements.length;
}
/**
* @notice Get information about staker's fee rate
* @param _node Address of staker
* @param _period Period to get fee delta
*/
function getNodeFeeDelta(address _node, uint16 _period)
// TODO "virtual" only for tests, probably will be removed after #1512
public view virtual returns (int256)
{
// TODO remove after upgrade #2579
if (_node == RESERVED_NODE && _period == 11) {
return 55;
}
return nodes[_node].feeDelta[_period];
}
/**
* @notice Return the information about arrangement
*/
function getArrangementInfo(bytes16 _policyId, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released (#1501)
// public view returns (ArrangementInfo)
external view returns (address node, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod)
{
ArrangementInfo storage info = policies[_policyId].arrangements[_index];
node = info.node;
indexOfDowntimePeriods = info.indexOfDowntimePeriods;
lastRefundedPeriod = info.lastRefundedPeriod;
}
/**
* @dev Get Policy structure by delegatecall
*/
function delegateGetPolicy(address _target, bytes16 _policyId)
internal returns (Policy memory result)
{
bytes32 memoryAddress = delegateGetData(_target, this.policies.selector, 1, bytes32(_policyId), 0);
assembly {
result := memoryAddress
}
}
/**
* @dev Get ArrangementInfo structure by delegatecall
*/
function delegateGetArrangementInfo(address _target, bytes16 _policyId, uint256 _index)
internal returns (ArrangementInfo memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, this.getArrangementInfo.selector, 2, bytes32(_policyId), bytes32(_index));
assembly {
result := memoryAddress
}
}
/**
* @dev Get NodeInfo structure by delegatecall
*/
function delegateGetNodeInfo(address _target, address _node)
internal returns (MemoryNodeInfo memory result)
{
bytes32 memoryAddress = delegateGetData(_target, this.nodes.selector, 1, bytes32(uint256(_node)), 0);
assembly {
result := memoryAddress
}
}
/**
* @dev Get feeRateRange structure by delegatecall
*/
function delegateGetFeeRateRange(address _target) internal returns (Range memory result) {
bytes32 memoryAddress = delegateGetData(_target, this.feeRateRange.selector, 0, 0, 0);
assembly {
result := memoryAddress
}
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
require(uint64(delegateGet(_testTarget, this.resetTimestamp.selector)) == resetTimestamp);
Range memory rangeToCheck = delegateGetFeeRateRange(_testTarget);
require(feeRateRange.min == rangeToCheck.min &&
feeRateRange.defaultValue == rangeToCheck.defaultValue &&
feeRateRange.max == rangeToCheck.max);
Policy storage policy = policies[RESERVED_POLICY_ID];
Policy memory policyToCheck = delegateGetPolicy(_testTarget, RESERVED_POLICY_ID);
require(policyToCheck.sponsor == policy.sponsor &&
policyToCheck.owner == policy.owner &&
policyToCheck.feeRate == policy.feeRate &&
policyToCheck.startTimestamp == policy.startTimestamp &&
policyToCheck.endTimestamp == policy.endTimestamp &&
policyToCheck.disabled == policy.disabled);
require(delegateGet(_testTarget, this.getArrangementsLength.selector, RESERVED_POLICY_ID) ==
policy.arrangements.length);
if (policy.arrangements.length > 0) {
ArrangementInfo storage arrangement = policy.arrangements[0];
ArrangementInfo memory arrangementToCheck = delegateGetArrangementInfo(
_testTarget, RESERVED_POLICY_ID, 0);
require(arrangementToCheck.node == arrangement.node &&
arrangementToCheck.indexOfDowntimePeriods == arrangement.indexOfDowntimePeriods &&
arrangementToCheck.lastRefundedPeriod == arrangement.lastRefundedPeriod);
}
NodeInfo storage nodeInfo = nodes[RESERVED_NODE];
MemoryNodeInfo memory nodeInfoToCheck = delegateGetNodeInfo(_testTarget, RESERVED_NODE);
require(nodeInfoToCheck.fee == nodeInfo.fee &&
nodeInfoToCheck.feeRate == nodeInfo.feeRate &&
nodeInfoToCheck.previousFeePeriod == nodeInfo.previousFeePeriod &&
nodeInfoToCheck.minFeeRate == nodeInfo.minFeeRate);
require(int256(delegateGet(_testTarget, this.getNodeFeeDelta.selector,
bytes32(bytes20(RESERVED_NODE)), bytes32(uint256(11)))) == getNodeFeeDelta(RESERVED_NODE, 11));
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade`
function finishUpgrade(address _target) public override virtual {
super.finishUpgrade(_target);
if (resetTimestamp == 0) {
resetTimestamp = uint64(block.timestamp);
}
// Create fake Policy and NodeInfo to use them in verifyState(address)
Policy storage policy = policies[RESERVED_POLICY_ID];
policy.sponsor = msg.sender;
policy.owner = address(this);
policy.startTimestamp = 1;
policy.endTimestamp = 2;
policy.feeRate = 3;
policy.disabled = true;
policy.arrangements.push(ArrangementInfo(RESERVED_NODE, 11, 22));
NodeInfo storage nodeInfo = nodes[RESERVED_NODE];
nodeInfo.fee = 100;
nodeInfo.feeRate = 33;
nodeInfo.previousFeePeriod = 44;
nodeInfo.feeDelta[11] = 55;
nodeInfo.minFeeRate = 777;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _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");
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./Upgradeable.sol";
import "../../zeppelin/utils/Address.sol";
/**
* @notice ERC897 - ERC DelegateProxy
*/
interface ERCProxy {
function proxyType() external pure returns (uint256);
function implementation() external view returns (address);
}
/**
* @notice Proxying requests to other contracts.
* Client should use ABI of real contract and address of this contract
*/
contract Dispatcher is Upgradeable, ERCProxy {
using Address for address;
event Upgraded(address indexed from, address indexed to, address owner);
event RolledBack(address indexed from, address indexed to, address owner);
/**
* @dev Set upgrading status before and after operations
*/
modifier upgrading()
{
isUpgrade = UPGRADE_TRUE;
_;
isUpgrade = UPGRADE_FALSE;
}
/**
* @param _target Target contract address
*/
constructor(address _target) upgrading {
require(_target.isContract());
// Checks that target contract inherits Dispatcher state
verifyState(_target);
// `verifyState` must work with its contract
verifyUpgradeableState(_target, _target);
target = _target;
finishUpgrade();
emit Upgraded(address(0), _target, msg.sender);
}
//------------------------ERC897------------------------
/**
* @notice ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() external pure override returns (uint256) {
return 2;
}
/**
* @notice ERC897, gets the address of the implementation where every call will be delegated
*/
function implementation() external view override returns (address) {
return target;
}
//------------------------------------------------------------
/**
* @notice Verify new contract storage and upgrade target
* @param _target New target contract address
*/
function upgrade(address _target) public onlyOwner upgrading {
require(_target.isContract());
// Checks that target contract has "correct" (as much as possible) state layout
verifyState(_target);
//`verifyState` must work with its contract
verifyUpgradeableState(_target, _target);
if (target.isContract()) {
verifyUpgradeableState(target, _target);
}
previousTarget = target;
target = _target;
finishUpgrade();
emit Upgraded(previousTarget, _target, msg.sender);
}
/**
* @notice Rollback to previous target
* @dev Test storage carefully before upgrade again after rollback
*/
function rollback() public onlyOwner upgrading {
require(previousTarget.isContract());
emit RolledBack(target, previousTarget, msg.sender);
// should be always true because layout previousTarget -> target was already checked
// but `verifyState` is not 100% accurate so check again
verifyState(previousTarget);
if (target.isContract()) {
verifyUpgradeableState(previousTarget, target);
}
target = previousTarget;
previousTarget = address(0);
finishUpgrade();
}
/**
* @dev Call verifyState method for Upgradeable contract
*/
function verifyUpgradeableState(address _from, address _to) private {
(bool callSuccess,) = _from.delegatecall(abi.encodeWithSelector(this.verifyState.selector, _to));
require(callSuccess);
}
/**
* @dev Call finishUpgrade method from the Upgradeable contract
*/
function finishUpgrade() private {
(bool callSuccess,) = target.delegatecall(abi.encodeWithSelector(this.finishUpgrade.selector, target));
require(callSuccess);
}
function verifyState(address _testTarget) public override onlyWhileUpgrading {
//checks equivalence accessing state through new contract and current storage
require(address(uint160(delegateGet(_testTarget, this.owner.selector))) == owner());
require(address(uint160(delegateGet(_testTarget, this.target.selector))) == target);
require(address(uint160(delegateGet(_testTarget, this.previousTarget.selector))) == previousTarget);
require(uint8(delegateGet(_testTarget, this.isUpgrade.selector)) == isUpgrade);
}
/**
* @dev Override function using empty code because no reason to call this function in Dispatcher
*/
function finishUpgrade(address) public override {}
/**
* @dev Receive function sends empty request to the target contract
*/
receive() external payable {
assert(target.isContract());
// execute receive function from target contract using storage of the dispatcher
(bool callSuccess,) = target.delegatecall("");
if (!callSuccess) {
revert();
}
}
/**
* @dev Fallback function sends all requests to the target contract
*/
fallback() external payable {
assert(target.isContract());
// execute requested function from target contract using storage of the dispatcher
(bool callSuccess,) = target.delegatecall(msg.data);
if (callSuccess) {
// copy result of the request to the return data
// we can use the second return value from `delegatecall` (bytes memory)
// but it will consume a little more gas
assembly {
returndatacopy(0x0, 0x0, returndatasize())
return(0x0, returndatasize())
}
} else {
revert();
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/utils/Address.sol";
import "../../zeppelin/token/ERC20/SafeERC20.sol";
import "./StakingInterface.sol";
import "../../zeppelin/proxy/Initializable.sol";
/**
* @notice Router for accessing interface contract
*/
contract StakingInterfaceRouter is Ownable {
BaseStakingInterface public target;
/**
* @param _target Address of the interface contract
*/
constructor(BaseStakingInterface _target) {
require(address(_target.token()) != address(0));
target = _target;
}
/**
* @notice Upgrade interface
* @param _target New contract address
*/
function upgrade(BaseStakingInterface _target) external onlyOwner {
require(address(_target.token()) != address(0));
target = _target;
}
}
/**
* @notice Internal base class for AbstractStakingContract and InitializableStakingContract
*/
abstract contract RawStakingContract {
using Address for address;
/**
* @dev Returns address of StakingInterfaceRouter
*/
function router() public view virtual returns (StakingInterfaceRouter);
/**
* @dev Checks permission for calling fallback function
*/
function isFallbackAllowed() public virtual returns (bool);
/**
* @dev Withdraw tokens from staking contract
*/
function withdrawTokens(uint256 _value) public virtual;
/**
* @dev Withdraw ETH from staking contract
*/
function withdrawETH() public virtual;
receive() external payable {}
/**
* @dev Function sends all requests to the target contract
*/
fallback() external payable {
require(isFallbackAllowed());
address target = address(router().target());
require(target.isContract());
// execute requested function from target contract
(bool callSuccess, ) = target.delegatecall(msg.data);
if (callSuccess) {
// copy result of the request to the return data
// we can use the second return value from `delegatecall` (bytes memory)
// but it will consume a little more gas
assembly {
returndatacopy(0x0, 0x0, returndatasize())
return(0x0, returndatasize())
}
} else {
revert();
}
}
}
/**
* @notice Base class for any staking contract (not usable with openzeppelin proxy)
* @dev Implement `isFallbackAllowed()` or override fallback function
* Implement `withdrawTokens(uint256)` and `withdrawETH()` functions
*/
abstract contract AbstractStakingContract is RawStakingContract {
StakingInterfaceRouter immutable router_;
NuCypherToken public immutable token;
/**
* @param _router Interface router contract address
*/
constructor(StakingInterfaceRouter _router) {
router_ = _router;
NuCypherToken localToken = _router.target().token();
require(address(localToken) != address(0));
token = localToken;
}
/**
* @dev Returns address of StakingInterfaceRouter
*/
function router() public view override returns (StakingInterfaceRouter) {
return router_;
}
}
/**
* @notice Base class for any staking contract usable with openzeppelin proxy
* @dev Implement `isFallbackAllowed()` or override fallback function
* Implement `withdrawTokens(uint256)` and `withdrawETH()` functions
*/
abstract contract InitializableStakingContract is Initializable, RawStakingContract {
StakingInterfaceRouter router_;
NuCypherToken public token;
/**
* @param _router Interface router contract address
*/
function initialize(StakingInterfaceRouter _router) public initializer {
router_ = _router;
NuCypherToken localToken = _router.target().token();
require(address(localToken) != address(0));
token = localToken;
}
/**
* @dev Returns address of StakingInterfaceRouter
*/
function router() public view override returns (StakingInterfaceRouter) {
return router_;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./AbstractStakingContract.sol";
import "../NuCypherToken.sol";
import "../StakingEscrow.sol";
import "../PolicyManager.sol";
import "../WorkLock.sol";
/**
* @notice Base StakingInterface
*/
contract BaseStakingInterface {
address public immutable stakingInterfaceAddress;
NuCypherToken public immutable token;
StakingEscrow public immutable escrow;
PolicyManager public immutable policyManager;
WorkLock public immutable workLock;
/**
* @notice Constructor sets addresses of the contracts
* @param _token Token contract
* @param _escrow Escrow contract
* @param _policyManager PolicyManager contract
* @param _workLock WorkLock contract
*/
constructor(
NuCypherToken _token,
StakingEscrow _escrow,
PolicyManager _policyManager,
WorkLock _workLock
) {
require(_token.totalSupply() > 0 &&
_escrow.secondsPerPeriod() > 0 &&
_policyManager.secondsPerPeriod() > 0 &&
// in case there is no worklock contract
(address(_workLock) == address(0) || _workLock.boostingRefund() > 0));
token = _token;
escrow = _escrow;
policyManager = _policyManager;
workLock = _workLock;
stakingInterfaceAddress = address(this);
}
/**
* @dev Checks executing through delegate call
*/
modifier onlyDelegateCall()
{
require(stakingInterfaceAddress != address(this));
_;
}
/**
* @dev Checks the existence of the worklock contract
*/
modifier workLockSet()
{
require(address(workLock) != address(0));
_;
}
}
/**
* @notice Interface for accessing main contracts from a staking contract
* @dev All methods must be stateless because this code will be executed by delegatecall call, use immutable fields.
* @dev |v1.7.1|
*/
contract StakingInterface is BaseStakingInterface {
event DepositedAsStaker(address indexed sender, uint256 value, uint16 periods);
event WithdrawnAsStaker(address indexed sender, uint256 value);
event DepositedAndIncreased(address indexed sender, uint256 index, uint256 value);
event LockedAndCreated(address indexed sender, uint256 value, uint16 periods);
event LockedAndIncreased(address indexed sender, uint256 index, uint256 value);
event Divided(address indexed sender, uint256 index, uint256 newValue, uint16 periods);
event Merged(address indexed sender, uint256 index1, uint256 index2);
event Minted(address indexed sender);
event PolicyFeeWithdrawn(address indexed sender, uint256 value);
event MinFeeRateSet(address indexed sender, uint256 value);
event ReStakeSet(address indexed sender, bool reStake);
event WorkerBonded(address indexed sender, address worker);
event Prolonged(address indexed sender, uint256 index, uint16 periods);
event WindDownSet(address indexed sender, bool windDown);
event SnapshotSet(address indexed sender, bool snapshotsEnabled);
event Bid(address indexed sender, uint256 depositedETH);
event Claimed(address indexed sender, uint256 claimedTokens);
event Refund(address indexed sender, uint256 refundETH);
event BidCanceled(address indexed sender);
event CompensationWithdrawn(address indexed sender);
/**
* @notice Constructor sets addresses of the contracts
* @param _token Token contract
* @param _escrow Escrow contract
* @param _policyManager PolicyManager contract
* @param _workLock WorkLock contract
*/
constructor(
NuCypherToken _token,
StakingEscrow _escrow,
PolicyManager _policyManager,
WorkLock _workLock
)
BaseStakingInterface(_token, _escrow, _policyManager, _workLock)
{
}
/**
* @notice Bond worker in the staking escrow
* @param _worker Worker address
*/
function bondWorker(address _worker) public onlyDelegateCall {
escrow.bondWorker(_worker);
emit WorkerBonded(msg.sender, _worker);
}
/**
* @notice Set `reStake` parameter in the staking escrow
* @param _reStake Value for parameter
*/
function setReStake(bool _reStake) public onlyDelegateCall {
escrow.setReStake(_reStake);
emit ReStakeSet(msg.sender, _reStake);
}
/**
* @notice Deposit tokens to the staking escrow
* @param _value Amount of token to deposit
* @param _periods Amount of periods during which tokens will be locked
*/
function depositAsStaker(uint256 _value, uint16 _periods) public onlyDelegateCall {
require(token.balanceOf(address(this)) >= _value);
token.approve(address(escrow), _value);
escrow.deposit(address(this), _value, _periods);
emit DepositedAsStaker(msg.sender, _value, _periods);
}
/**
* @notice Deposit tokens to the staking escrow
* @param _index Index of the sub-stake
* @param _value Amount of tokens which will be locked
*/
function depositAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall {
require(token.balanceOf(address(this)) >= _value);
token.approve(address(escrow), _value);
escrow.depositAndIncrease(_index, _value);
emit DepositedAndIncreased(msg.sender, _index, _value);
}
/**
* @notice Withdraw available amount of tokens from the staking escrow to the staking contract
* @param _value Amount of token to withdraw
*/
function withdrawAsStaker(uint256 _value) public onlyDelegateCall {
escrow.withdraw(_value);
emit WithdrawnAsStaker(msg.sender, _value);
}
/**
* @notice Lock some tokens in the staking escrow
* @param _value Amount of tokens which should lock
* @param _periods Amount of periods during which tokens will be locked
*/
function lockAndCreate(uint256 _value, uint16 _periods) public onlyDelegateCall {
escrow.lockAndCreate(_value, _periods);
emit LockedAndCreated(msg.sender, _value, _periods);
}
/**
* @notice Lock some tokens in the staking escrow
* @param _index Index of the sub-stake
* @param _value Amount of tokens which will be locked
*/
function lockAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall {
escrow.lockAndIncrease(_index, _value);
emit LockedAndIncreased(msg.sender, _index, _value);
}
/**
* @notice Divide stake into two parts
* @param _index Index of stake
* @param _newValue New stake value
* @param _periods Amount of periods for extending stake
*/
function divideStake(uint256 _index, uint256 _newValue, uint16 _periods) public onlyDelegateCall {
escrow.divideStake(_index, _newValue, _periods);
emit Divided(msg.sender, _index, _newValue, _periods);
}
/**
* @notice Merge two sub-stakes into one
* @param _index1 Index of the first sub-stake
* @param _index2 Index of the second sub-stake
*/
function mergeStake(uint256 _index1, uint256 _index2) public onlyDelegateCall {
escrow.mergeStake(_index1, _index2);
emit Merged(msg.sender, _index1, _index2);
}
/**
* @notice Mint tokens in the staking escrow
*/
function mint() public onlyDelegateCall {
escrow.mint();
emit Minted(msg.sender);
}
/**
* @notice Withdraw available policy fees from the policy manager to the staking contract
*/
function withdrawPolicyFee() public onlyDelegateCall {
uint256 value = policyManager.withdraw();
emit PolicyFeeWithdrawn(msg.sender, value);
}
/**
* @notice Set the minimum fee that the staker will accept in the policy manager contract
*/
function setMinFeeRate(uint256 _minFeeRate) public onlyDelegateCall {
policyManager.setMinFeeRate(_minFeeRate);
emit MinFeeRateSet(msg.sender, _minFeeRate);
}
/**
* @notice Prolong active sub stake
* @param _index Index of the sub stake
* @param _periods Amount of periods for extending sub stake
*/
function prolongStake(uint256 _index, uint16 _periods) public onlyDelegateCall {
escrow.prolongStake(_index, _periods);
emit Prolonged(msg.sender, _index, _periods);
}
/**
* @notice Set `windDown` parameter in the staking escrow
* @param _windDown Value for parameter
*/
function setWindDown(bool _windDown) public onlyDelegateCall {
escrow.setWindDown(_windDown);
emit WindDownSet(msg.sender, _windDown);
}
/**
* @notice Set `snapshots` parameter in the staking escrow
* @param _enableSnapshots Value for parameter
*/
function setSnapshots(bool _enableSnapshots) public onlyDelegateCall {
escrow.setSnapshots(_enableSnapshots);
emit SnapshotSet(msg.sender, _enableSnapshots);
}
/**
* @notice Bid for tokens by transferring ETH
*/
function bid(uint256 _value) public payable onlyDelegateCall workLockSet {
workLock.bid{value: _value}();
emit Bid(msg.sender, _value);
}
/**
* @notice Cancel bid and refund deposited ETH
*/
function cancelBid() public onlyDelegateCall workLockSet {
workLock.cancelBid();
emit BidCanceled(msg.sender);
}
/**
* @notice Withdraw compensation after force refund
*/
function withdrawCompensation() public onlyDelegateCall workLockSet {
workLock.withdrawCompensation();
emit CompensationWithdrawn(msg.sender);
}
/**
* @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract
*/
function claim() public onlyDelegateCall workLockSet {
uint256 claimedTokens = workLock.claim();
emit Claimed(msg.sender, claimedTokens);
}
/**
* @notice Refund ETH for the completed work
*/
function refund() public onlyDelegateCall workLockSet {
uint256 refundETH = workLock.refund();
emit Refund(msg.sender, refundETH);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/token/ERC20/SafeERC20.sol";
import "../zeppelin/utils/Address.sol";
import "../zeppelin/ownership/Ownable.sol";
import "./NuCypherToken.sol";
import "./StakingEscrow.sol";
import "./lib/AdditionalMath.sol";
/**
* @notice The WorkLock distribution contract
*/
contract WorkLock is Ownable {
using SafeERC20 for NuCypherToken;
using SafeMath for uint256;
using AdditionalMath for uint256;
using Address for address payable;
using Address for address;
event Deposited(address indexed sender, uint256 value);
event Bid(address indexed sender, uint256 depositedETH);
event Claimed(address indexed sender, uint256 claimedTokens);
event Refund(address indexed sender, uint256 refundETH, uint256 completedWork);
event Canceled(address indexed sender, uint256 value);
event BiddersChecked(address indexed sender, uint256 startIndex, uint256 endIndex);
event ForceRefund(address indexed sender, address indexed bidder, uint256 refundETH);
event CompensationWithdrawn(address indexed sender, uint256 value);
event Shutdown(address indexed sender);
struct WorkInfo {
uint256 depositedETH;
uint256 completedWork;
bool claimed;
uint128 index;
}
uint16 public constant SLOWING_REFUND = 100;
uint256 private constant MAX_ETH_SUPPLY = 2e10 ether;
NuCypherToken public immutable token;
StakingEscrow public immutable escrow;
/*
* @dev WorkLock calculations:
* bid = minBid + bonusETHPart
* bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens
* bonusDepositRate = bonusTokenSupply / bonusETHSupply
* claimedTokens = minAllowableLockedTokens + bonusETHPart * bonusDepositRate
* bonusRefundRate = bonusDepositRate * SLOWING_REFUND / boostingRefund
* refundETH = completedWork / refundRate
*/
uint256 public immutable boostingRefund;
uint256 public immutable minAllowedBid;
uint16 public immutable stakingPeriods;
// copy from the escrow contract
uint256 public immutable maxAllowableLockedTokens;
uint256 public immutable minAllowableLockedTokens;
uint256 public tokenSupply;
uint256 public startBidDate;
uint256 public endBidDate;
uint256 public endCancellationDate;
uint256 public bonusETHSupply;
mapping(address => WorkInfo) public workInfo;
mapping(address => uint256) public compensation;
address[] public bidders;
// if value == bidders.length then WorkLock is fully checked
uint256 public nextBidderToCheck;
/**
* @dev Checks timestamp regarding cancellation window
*/
modifier afterCancellationWindow()
{
require(block.timestamp >= endCancellationDate,
"Operation is allowed when cancellation phase is over");
_;
}
/**
* @param _token Token contract
* @param _escrow Escrow contract
* @param _startBidDate Timestamp when bidding starts
* @param _endBidDate Timestamp when bidding will end
* @param _endCancellationDate Timestamp when cancellation will ends
* @param _boostingRefund Coefficient to boost refund ETH
* @param _stakingPeriods Amount of periods during which tokens will be locked after claiming
* @param _minAllowedBid Minimum allowed ETH amount for bidding
*/
constructor(
NuCypherToken _token,
StakingEscrow _escrow,
uint256 _startBidDate,
uint256 _endBidDate,
uint256 _endCancellationDate,
uint256 _boostingRefund,
uint16 _stakingPeriods,
uint256 _minAllowedBid
) {
uint256 totalSupply = _token.totalSupply();
require(totalSupply > 0 && // token contract is deployed and accessible
_escrow.secondsPerPeriod() > 0 && // escrow contract is deployed and accessible
_escrow.token() == _token && // same token address for worklock and escrow
_endBidDate > _startBidDate && // bidding period lasts some time
_endBidDate > block.timestamp && // there is time to make a bid
_endCancellationDate >= _endBidDate && // cancellation window includes bidding
_minAllowedBid > 0 && // min allowed bid was set
_boostingRefund > 0 && // boosting coefficient was set
_stakingPeriods >= _escrow.minLockedPeriods()); // staking duration is consistent with escrow contract
// worst case for `ethToWork()` and `workToETH()`,
// when ethSupply == MAX_ETH_SUPPLY and tokenSupply == totalSupply
require(MAX_ETH_SUPPLY * totalSupply * SLOWING_REFUND / MAX_ETH_SUPPLY / totalSupply == SLOWING_REFUND &&
MAX_ETH_SUPPLY * totalSupply * _boostingRefund / MAX_ETH_SUPPLY / totalSupply == _boostingRefund);
token = _token;
escrow = _escrow;
startBidDate = _startBidDate;
endBidDate = _endBidDate;
endCancellationDate = _endCancellationDate;
boostingRefund = _boostingRefund;
stakingPeriods = _stakingPeriods;
minAllowedBid = _minAllowedBid;
maxAllowableLockedTokens = _escrow.maxAllowableLockedTokens();
minAllowableLockedTokens = _escrow.minAllowableLockedTokens();
}
/**
* @notice Deposit tokens to contract
* @param _value Amount of tokens to transfer
*/
function tokenDeposit(uint256 _value) external {
require(block.timestamp < endBidDate, "Can't deposit more tokens after end of bidding");
token.safeTransferFrom(msg.sender, address(this), _value);
tokenSupply += _value;
emit Deposited(msg.sender, _value);
}
/**
* @notice Calculate amount of tokens that will be get for specified amount of ETH
* @dev This value will be fixed only after end of bidding
*/
function ethToTokens(uint256 _ethAmount) public view returns (uint256) {
if (_ethAmount < minAllowedBid) {
return 0;
}
// when all participants bid with the same minimum amount of eth
if (bonusETHSupply == 0) {
return tokenSupply / bidders.length;
}
uint256 bonusETH = _ethAmount - minAllowedBid;
uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens;
return minAllowableLockedTokens + bonusETH.mul(bonusTokenSupply).div(bonusETHSupply);
}
/**
* @notice Calculate amount of work that need to be done to refund specified amount of ETH
*/
function ethToWork(uint256 _ethAmount, uint256 _tokenSupply, uint256 _ethSupply)
internal view returns (uint256)
{
return _ethAmount.mul(_tokenSupply).mul(SLOWING_REFUND).divCeil(_ethSupply.mul(boostingRefund));
}
/**
* @notice Calculate amount of work that need to be done to refund specified amount of ETH
* @dev This value will be fixed only after end of bidding
* @param _ethToReclaim Specified sum of ETH staker wishes to reclaim following completion of work
* @param _restOfDepositedETH Remaining ETH in staker's deposit once ethToReclaim sum has been subtracted
* @dev _ethToReclaim + _restOfDepositedETH = depositedETH
*/
function ethToWork(uint256 _ethToReclaim, uint256 _restOfDepositedETH) internal view returns (uint256) {
uint256 baseETHSupply = bidders.length * minAllowedBid;
// when all participants bid with the same minimum amount of eth
if (bonusETHSupply == 0) {
return ethToWork(_ethToReclaim, tokenSupply, baseETHSupply);
}
uint256 baseETH = 0;
uint256 bonusETH = 0;
// If the staker's total remaining deposit (including the specified sum of ETH to reclaim)
// is lower than the minimum bid size,
// then only the base part is used to calculate the work required to reclaim ETH
if (_ethToReclaim + _restOfDepositedETH <= minAllowedBid) {
baseETH = _ethToReclaim;
// If the staker's remaining deposit (not including the specified sum of ETH to reclaim)
// is still greater than the minimum bid size,
// then only the bonus part is used to calculate the work required to reclaim ETH
} else if (_restOfDepositedETH >= minAllowedBid) {
bonusETH = _ethToReclaim;
// If the staker's remaining deposit (not including the specified sum of ETH to reclaim)
// is lower than the minimum bid size,
// then both the base and bonus parts must be used to calculate the work required to reclaim ETH
} else {
bonusETH = _ethToReclaim + _restOfDepositedETH - minAllowedBid;
baseETH = _ethToReclaim - bonusETH;
}
uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens;
uint256 work = 0;
if (baseETH > 0) {
work = ethToWork(baseETH, baseTokenSupply, baseETHSupply);
}
if (bonusETH > 0) {
uint256 bonusTokenSupply = tokenSupply - baseTokenSupply;
work += ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply);
}
return work;
}
/**
* @notice Calculate amount of work that need to be done to refund specified amount of ETH
* @dev This value will be fixed only after end of bidding
*/
function ethToWork(uint256 _ethAmount) public view returns (uint256) {
return ethToWork(_ethAmount, 0);
}
/**
* @notice Calculate amount of ETH that will be refund for completing specified amount of work
*/
function workToETH(uint256 _completedWork, uint256 _ethSupply, uint256 _tokenSupply)
internal view returns (uint256)
{
return _completedWork.mul(_ethSupply).mul(boostingRefund).div(_tokenSupply.mul(SLOWING_REFUND));
}
/**
* @notice Calculate amount of ETH that will be refund for completing specified amount of work
* @dev This value will be fixed only after end of bidding
*/
function workToETH(uint256 _completedWork, uint256 _depositedETH) public view returns (uint256) {
uint256 baseETHSupply = bidders.length * minAllowedBid;
// when all participants bid with the same minimum amount of eth
if (bonusETHSupply == 0) {
return workToETH(_completedWork, baseETHSupply, tokenSupply);
}
uint256 bonusWork = 0;
uint256 bonusETH = 0;
uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens;
if (_depositedETH > minAllowedBid) {
bonusETH = _depositedETH - minAllowedBid;
uint256 bonusTokenSupply = tokenSupply - baseTokenSupply;
bonusWork = ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply);
if (_completedWork <= bonusWork) {
return workToETH(_completedWork, bonusETHSupply, bonusTokenSupply);
}
}
_completedWork -= bonusWork;
return bonusETH + workToETH(_completedWork, baseETHSupply, baseTokenSupply);
}
/**
* @notice Get remaining work to full refund
*/
function getRemainingWork(address _bidder) external view returns (uint256) {
WorkInfo storage info = workInfo[_bidder];
uint256 completedWork = escrow.getCompletedWork(_bidder).sub(info.completedWork);
uint256 remainingWork = ethToWork(info.depositedETH);
if (remainingWork <= completedWork) {
return 0;
}
return remainingWork - completedWork;
}
/**
* @notice Get length of bidders array
*/
function getBiddersLength() external view returns (uint256) {
return bidders.length;
}
/**
* @notice Bid for tokens by transferring ETH
*/
function bid() external payable {
require(block.timestamp >= startBidDate, "Bidding is not open yet");
require(block.timestamp < endBidDate, "Bidding is already finished");
WorkInfo storage info = workInfo[msg.sender];
// first bid
if (info.depositedETH == 0) {
require(msg.value >= minAllowedBid, "Bid must be at least minimum");
require(bidders.length < tokenSupply / minAllowableLockedTokens, "Not enough tokens for more bidders");
info.index = uint128(bidders.length);
bidders.push(msg.sender);
bonusETHSupply = bonusETHSupply.add(msg.value - minAllowedBid);
} else {
bonusETHSupply = bonusETHSupply.add(msg.value);
}
info.depositedETH = info.depositedETH.add(msg.value);
emit Bid(msg.sender, msg.value);
}
/**
* @notice Cancel bid and refund deposited ETH
*/
function cancelBid() external {
require(block.timestamp < endCancellationDate,
"Cancellation allowed only during cancellation window");
WorkInfo storage info = workInfo[msg.sender];
require(info.depositedETH > 0, "No bid to cancel");
require(!info.claimed, "Tokens are already claimed");
uint256 refundETH = info.depositedETH;
info.depositedETH = 0;
// remove from bidders array, move last bidder to the empty place
uint256 lastIndex = bidders.length - 1;
if (info.index != lastIndex) {
address lastBidder = bidders[lastIndex];
bidders[info.index] = lastBidder;
workInfo[lastBidder].index = info.index;
}
bidders.pop();
if (refundETH > minAllowedBid) {
bonusETHSupply = bonusETHSupply.sub(refundETH - minAllowedBid);
}
msg.sender.sendValue(refundETH);
emit Canceled(msg.sender, refundETH);
}
/**
* @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens
*/
function shutdown() external onlyOwner {
require(!isClaimingAvailable(), "Claiming has already been enabled");
internalShutdown();
}
/**
* @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens
*/
function internalShutdown() internal {
startBidDate = 0;
endBidDate = 0;
endCancellationDate = uint256(0) - 1; // "infinite" cancellation window
token.safeTransfer(owner(), tokenSupply);
emit Shutdown(msg.sender);
}
/**
* @notice Make force refund to bidders who can get tokens more than maximum allowed
* @param _biddersForRefund Sorted list of unique bidders. Only bidders who must receive a refund
*/
function forceRefund(address payable[] calldata _biddersForRefund) external afterCancellationWindow {
require(nextBidderToCheck != bidders.length, "Bidders have already been checked");
uint256 length = _biddersForRefund.length;
require(length > 0, "Must be at least one bidder for a refund");
uint256 minNumberOfBidders = tokenSupply.divCeil(maxAllowableLockedTokens);
if (bidders.length < minNumberOfBidders) {
internalShutdown();
return;
}
address previousBidder = _biddersForRefund[0];
uint256 minBid = workInfo[previousBidder].depositedETH;
uint256 maxBid = minBid;
// get minimum and maximum bids
for (uint256 i = 1; i < length; i++) {
address bidder = _biddersForRefund[i];
uint256 depositedETH = workInfo[bidder].depositedETH;
require(bidder > previousBidder && depositedETH > 0, "Addresses must be an array of unique bidders");
if (minBid > depositedETH) {
minBid = depositedETH;
} else if (maxBid < depositedETH) {
maxBid = depositedETH;
}
previousBidder = bidder;
}
uint256[] memory refunds = new uint256[](length);
// first step - align at a minimum bid
if (minBid != maxBid) {
for (uint256 i = 0; i < length; i++) {
address bidder = _biddersForRefund[i];
WorkInfo storage info = workInfo[bidder];
if (info.depositedETH > minBid) {
refunds[i] = info.depositedETH - minBid;
info.depositedETH = minBid;
bonusETHSupply -= refunds[i];
}
}
}
require(ethToTokens(minBid) > maxAllowableLockedTokens,
"At least one of bidders has allowable bid");
// final bids adjustment (only for bonus part)
// (min_whale_bid * token_supply - max_stake * eth_supply) / (token_supply - max_stake * n_whales)
uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens;
uint256 minBonusETH = minBid - minAllowedBid;
uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens;
uint256 refundETH = minBonusETH.mul(bonusTokenSupply)
.sub(maxBonusTokens.mul(bonusETHSupply))
.divCeil(bonusTokenSupply - maxBonusTokens.mul(length));
uint256 resultBid = minBid.sub(refundETH);
bonusETHSupply -= length * refundETH;
for (uint256 i = 0; i < length; i++) {
address bidder = _biddersForRefund[i];
WorkInfo storage info = workInfo[bidder];
refunds[i] += refundETH;
info.depositedETH = resultBid;
}
// reset verification
nextBidderToCheck = 0;
// save a refund
for (uint256 i = 0; i < length; i++) {
address bidder = _biddersForRefund[i];
compensation[bidder] += refunds[i];
emit ForceRefund(msg.sender, bidder, refunds[i]);
}
}
/**
* @notice Withdraw compensation after force refund
*/
function withdrawCompensation() external {
uint256 refund = compensation[msg.sender];
require(refund > 0, "There is no compensation");
compensation[msg.sender] = 0;
msg.sender.sendValue(refund);
emit CompensationWithdrawn(msg.sender, refund);
}
/**
* @notice Check that the claimed tokens are within `maxAllowableLockedTokens` for all participants,
* starting from the last point `nextBidderToCheck`
* @dev Method stops working when the remaining gas is less than `_gasToSaveState`
* and saves the state in `nextBidderToCheck`.
* If all bidders have been checked then `nextBidderToCheck` will be equal to the length of the bidders array
*/
function verifyBiddingCorrectness(uint256 _gasToSaveState) external afterCancellationWindow returns (uint256) {
require(nextBidderToCheck != bidders.length, "Bidders have already been checked");
// all participants bid with the same minimum amount of eth
uint256 index = nextBidderToCheck;
if (bonusETHSupply == 0) {
require(tokenSupply / bidders.length <= maxAllowableLockedTokens, "Not enough bidders");
index = bidders.length;
}
uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens;
uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens;
uint256 maxBidFromMaxStake = minAllowedBid + maxBonusTokens.mul(bonusETHSupply).div(bonusTokenSupply);
while (index < bidders.length && gasleft() > _gasToSaveState) {
address bidder = bidders[index];
require(workInfo[bidder].depositedETH <= maxBidFromMaxStake, "Bid is greater than max allowable bid");
index++;
}
if (index != nextBidderToCheck) {
emit BiddersChecked(msg.sender, nextBidderToCheck, index);
nextBidderToCheck = index;
}
return nextBidderToCheck;
}
/**
* @notice Checks if claiming available
*/
function isClaimingAvailable() public view returns (bool) {
return block.timestamp >= endCancellationDate &&
nextBidderToCheck == bidders.length;
}
/**
* @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract.
*/
function claim() external returns (uint256 claimedTokens) {
require(isClaimingAvailable(), "Claiming has not been enabled yet");
WorkInfo storage info = workInfo[msg.sender];
require(!info.claimed, "Tokens are already claimed");
claimedTokens = ethToTokens(info.depositedETH);
require(claimedTokens > 0, "Nothing to claim");
info.claimed = true;
token.approve(address(escrow), claimedTokens);
escrow.depositFromWorkLock(msg.sender, claimedTokens, stakingPeriods);
info.completedWork = escrow.setWorkMeasurement(msg.sender, true);
emit Claimed(msg.sender, claimedTokens);
}
/**
* @notice Get available refund for bidder
*/
function getAvailableRefund(address _bidder) public view returns (uint256) {
WorkInfo storage info = workInfo[_bidder];
// nothing to refund
if (info.depositedETH == 0) {
return 0;
}
uint256 currentWork = escrow.getCompletedWork(_bidder);
uint256 completedWork = currentWork.sub(info.completedWork);
// no work that has been completed since last refund
if (completedWork == 0) {
return 0;
}
uint256 refundETH = workToETH(completedWork, info.depositedETH);
if (refundETH > info.depositedETH) {
refundETH = info.depositedETH;
}
return refundETH;
}
/**
* @notice Refund ETH for the completed work
*/
function refund() external returns (uint256 refundETH) {
WorkInfo storage info = workInfo[msg.sender];
require(info.claimed, "Tokens must be claimed before refund");
refundETH = getAvailableRefund(msg.sender);
require(refundETH > 0, "Nothing to refund: there is no ETH to refund or no completed work");
if (refundETH == info.depositedETH) {
escrow.setWorkMeasurement(msg.sender, false);
}
info.depositedETH = info.depositedETH.sub(refundETH);
// convert refund back to work to eliminate potential rounding errors
uint256 completedWork = ethToWork(refundETH, info.depositedETH);
info.completedWork = info.completedWork.add(completedWork);
emit Refund(msg.sender, refundETH, completedWork);
msg.sender.sendValue(refundETH);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^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;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/math/SafeMath.sol";
import "./AbstractStakingContract.sol";
/**
* @notice Contract acts as delegate for sub-stakers and owner
**/
contract PoolingStakingContract is AbstractStakingContract, Ownable {
using SafeMath for uint256;
using Address for address payable;
using SafeERC20 for NuCypherToken;
event TokensDeposited(address indexed sender, uint256 value, uint256 depositedTokens);
event TokensWithdrawn(address indexed sender, uint256 value, uint256 depositedTokens);
event ETHWithdrawn(address indexed sender, uint256 value);
event DepositSet(address indexed sender, bool value);
struct Delegator {
uint256 depositedTokens;
uint256 withdrawnReward;
uint256 withdrawnETH;
}
StakingEscrow public immutable escrow;
uint256 public totalDepositedTokens;
uint256 public totalWithdrawnReward;
uint256 public totalWithdrawnETH;
uint256 public ownerFraction;
uint256 public ownerWithdrawnReward;
uint256 public ownerWithdrawnETH;
mapping (address => Delegator) public delegators;
bool depositIsEnabled = true;
/**
* @param _router Address of the StakingInterfaceRouter contract
* @param _ownerFraction Base owner's portion of reward
*/
constructor(
StakingInterfaceRouter _router,
uint256 _ownerFraction
)
AbstractStakingContract(_router)
{
escrow = _router.target().escrow();
ownerFraction = _ownerFraction;
}
/**
* @notice Enabled deposit
*/
function enableDeposit() external onlyOwner {
depositIsEnabled = true;
emit DepositSet(msg.sender, depositIsEnabled);
}
/**
* @notice Disable deposit
*/
function disableDeposit() external onlyOwner {
depositIsEnabled = false;
emit DepositSet(msg.sender, depositIsEnabled);
}
/**
* @notice Transfer tokens as delegator
* @param _value Amount of tokens to transfer
*/
function depositTokens(uint256 _value) external {
require(depositIsEnabled, "Deposit must be enabled");
require(_value > 0, "Value must be not empty");
totalDepositedTokens = totalDepositedTokens.add(_value);
Delegator storage delegator = delegators[msg.sender];
delegator.depositedTokens += _value;
token.safeTransferFrom(msg.sender, address(this), _value);
emit TokensDeposited(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Get available reward for all delegators and owner
*/
function getAvailableReward() public view returns (uint256) {
uint256 stakedTokens = escrow.getAllTokens(address(this));
uint256 freeTokens = token.balanceOf(address(this));
uint256 reward = stakedTokens + freeTokens - totalDepositedTokens;
if (reward > freeTokens) {
return freeTokens;
}
return reward;
}
/**
* @notice Get cumulative reward
*/
function getCumulativeReward() public view returns (uint256) {
return getAvailableReward().add(totalWithdrawnReward);
}
/**
* @notice Get available reward in tokens for pool owner
*/
function getAvailableOwnerReward() public view returns (uint256) {
uint256 reward = getCumulativeReward();
uint256 maxAllowableReward;
if (totalDepositedTokens != 0) {
maxAllowableReward = reward.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction));
} else {
maxAllowableReward = reward;
}
return maxAllowableReward.sub(ownerWithdrawnReward);
}
/**
* @notice Get available reward in tokens for delegator
*/
function getAvailableReward(address _delegator) public view returns (uint256) {
if (totalDepositedTokens == 0) {
return 0;
}
uint256 reward = getCumulativeReward();
Delegator storage delegator = delegators[_delegator];
uint256 maxAllowableReward = reward.mul(delegator.depositedTokens)
.div(totalDepositedTokens.add(ownerFraction));
return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0;
}
/**
* @notice Withdraw reward in tokens to owner
*/
function withdrawOwnerReward() public onlyOwner {
uint256 balance = token.balanceOf(address(this));
uint256 availableReward = getAvailableOwnerReward();
if (availableReward > balance) {
availableReward = balance;
}
require(availableReward > 0, "There is no available reward to withdraw");
ownerWithdrawnReward = ownerWithdrawnReward.add(availableReward);
totalWithdrawnReward = totalWithdrawnReward.add(availableReward);
token.safeTransfer(msg.sender, availableReward);
emit TokensWithdrawn(msg.sender, availableReward, 0);
}
/**
* @notice Withdraw amount of tokens to delegator
* @param _value Amount of tokens to withdraw
*/
function withdrawTokens(uint256 _value) public override {
uint256 balance = token.balanceOf(address(this));
require(_value <= balance, "Not enough tokens in the contract");
uint256 availableReward = getAvailableReward(msg.sender);
Delegator storage delegator = delegators[msg.sender];
require(_value <= availableReward + delegator.depositedTokens,
"Requested amount of tokens exceeded allowed portion");
if (_value <= availableReward) {
delegator.withdrawnReward += _value;
totalWithdrawnReward += _value;
} else {
delegator.withdrawnReward = delegator.withdrawnReward.add(availableReward);
totalWithdrawnReward = totalWithdrawnReward.add(availableReward);
uint256 depositToWithdraw = _value - availableReward;
uint256 newDepositedTokens = delegator.depositedTokens - depositToWithdraw;
uint256 newWithdrawnReward = delegator.withdrawnReward.mul(newDepositedTokens).div(delegator.depositedTokens);
uint256 newWithdrawnETH = delegator.withdrawnETH.mul(newDepositedTokens).div(delegator.depositedTokens);
totalDepositedTokens -= depositToWithdraw;
totalWithdrawnReward -= (delegator.withdrawnReward - newWithdrawnReward);
totalWithdrawnETH -= (delegator.withdrawnETH - newWithdrawnETH);
delegator.depositedTokens = newDepositedTokens;
delegator.withdrawnReward = newWithdrawnReward;
delegator.withdrawnETH = newWithdrawnETH;
}
token.safeTransfer(msg.sender, _value);
emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Get available ether for owner
*/
function getAvailableOwnerETH() public view returns (uint256) {
// TODO boilerplate code
uint256 balance = address(this).balance;
balance = balance.add(totalWithdrawnETH);
uint256 maxAllowableETH = balance.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction));
uint256 availableETH = maxAllowableETH.sub(ownerWithdrawnETH);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/**
* @notice Get available ether for delegator
*/
function getAvailableETH(address _delegator) public view returns (uint256) {
Delegator storage delegator = delegators[_delegator];
// TODO boilerplate code
uint256 balance = address(this).balance;
balance = balance.add(totalWithdrawnETH);
uint256 maxAllowableETH = balance.mul(delegator.depositedTokens)
.div(totalDepositedTokens.add(ownerFraction));
uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/**
* @notice Withdraw available amount of ETH to pool owner
*/
function withdrawOwnerETH() public onlyOwner {
uint256 availableETH = getAvailableOwnerETH();
require(availableETH > 0, "There is no available ETH to withdraw");
ownerWithdrawnETH = ownerWithdrawnETH.add(availableETH);
totalWithdrawnETH = totalWithdrawnETH.add(availableETH);
msg.sender.sendValue(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
}
/**
* @notice Withdraw available amount of ETH to delegator
*/
function withdrawETH() public override {
uint256 availableETH = getAvailableETH(msg.sender);
require(availableETH > 0, "There is no available ETH to withdraw");
Delegator storage delegator = delegators[msg.sender];
delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH);
totalWithdrawnETH = totalWithdrawnETH.add(availableETH);
msg.sender.sendValue(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
}
/**
* @notice Calling fallback function is allowed only for the owner
**/
function isFallbackAllowed() public view override returns (bool) {
return msg.sender == owner();
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/math/SafeMath.sol";
import "./AbstractStakingContract.sol";
/**
* @notice Contract acts as delegate for sub-stakers
**/
contract PoolingStakingContractV2 is InitializableStakingContract, Ownable {
using SafeMath for uint256;
using Address for address payable;
using SafeERC20 for NuCypherToken;
event TokensDeposited(
address indexed sender,
uint256 value,
uint256 depositedTokens
);
event TokensWithdrawn(
address indexed sender,
uint256 value,
uint256 depositedTokens
);
event ETHWithdrawn(address indexed sender, uint256 value);
event WorkerOwnerSet(address indexed sender, address indexed workerOwner);
struct Delegator {
uint256 depositedTokens;
uint256 withdrawnReward;
uint256 withdrawnETH;
}
/**
* Defines base fraction and precision of worker fraction.
* E.g., for a value of 10000, a worker fraction of 100 represents 1% of reward (100/10000)
*/
uint256 public constant BASIS_FRACTION = 10000;
StakingEscrow public escrow;
address public workerOwner;
uint256 public totalDepositedTokens;
uint256 public totalWithdrawnReward;
uint256 public totalWithdrawnETH;
uint256 workerFraction;
uint256 public workerWithdrawnReward;
mapping(address => Delegator) public delegators;
/**
* @notice Initialize function for using with OpenZeppelin proxy
* @param _workerFraction Share of token reward that worker node owner will get.
* Use value up to BASIS_FRACTION (10000), if _workerFraction = BASIS_FRACTION -> means 100% reward as commission.
* For example, 100 worker fraction is 1% of reward
* @param _router StakingInterfaceRouter address
* @param _workerOwner Owner of worker node, only this address can withdraw worker commission
*/
function initialize(
uint256 _workerFraction,
StakingInterfaceRouter _router,
address _workerOwner
) external initializer {
require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION);
InitializableStakingContract.initialize(_router);
_transferOwnership(msg.sender);
escrow = _router.target().escrow();
workerFraction = _workerFraction;
workerOwner = _workerOwner;
emit WorkerOwnerSet(msg.sender, _workerOwner);
}
/**
* @notice withdrawAll() is allowed
*/
function isWithdrawAllAllowed() public view returns (bool) {
// no tokens in StakingEscrow contract which belong to pool
return escrow.getAllTokens(address(this)) == 0;
}
/**
* @notice deposit() is allowed
*/
function isDepositAllowed() public view returns (bool) {
// tokens which directly belong to pool
uint256 freeTokens = token.balanceOf(address(this));
// no sub-stakes and no earned reward
return isWithdrawAllAllowed() && freeTokens == totalDepositedTokens;
}
/**
* @notice Set worker owner address
*/
function setWorkerOwner(address _workerOwner) external onlyOwner {
workerOwner = _workerOwner;
emit WorkerOwnerSet(msg.sender, _workerOwner);
}
/**
* @notice Calculate worker's fraction depending on deposited tokens
* Override to implement dynamic worker fraction.
*/
function getWorkerFraction() public view virtual returns (uint256) {
return workerFraction;
}
/**
* @notice Transfer tokens as delegator
* @param _value Amount of tokens to transfer
*/
function depositTokens(uint256 _value) external {
require(isDepositAllowed(), "Deposit must be enabled");
require(_value > 0, "Value must be not empty");
totalDepositedTokens = totalDepositedTokens.add(_value);
Delegator storage delegator = delegators[msg.sender];
delegator.depositedTokens = delegator.depositedTokens.add(_value);
token.safeTransferFrom(msg.sender, address(this), _value);
emit TokensDeposited(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Get available reward for all delegators and owner
*/
function getAvailableReward() public view returns (uint256) {
// locked + unlocked tokens in StakingEscrow contract which belong to pool
uint256 stakedTokens = escrow.getAllTokens(address(this));
// tokens which directly belong to pool
uint256 freeTokens = token.balanceOf(address(this));
// tokens in excess of the initially deposited
uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens);
// check how many of reward tokens belong directly to pool
if (reward > freeTokens) {
return freeTokens;
}
return reward;
}
/**
* @notice Get cumulative reward.
* Available and withdrawn reward together to use in delegator/owner reward calculations
*/
function getCumulativeReward() public view returns (uint256) {
return getAvailableReward().add(totalWithdrawnReward);
}
/**
* @notice Get available reward in tokens for worker node owner
*/
function getAvailableWorkerReward() public view returns (uint256) {
// total current and historical reward
uint256 reward = getCumulativeReward();
// calculate total reward for worker including historical reward
uint256 maxAllowableReward;
// usual case
if (totalDepositedTokens != 0) {
uint256 fraction = getWorkerFraction();
maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION);
// special case when there are no delegators
} else {
maxAllowableReward = reward;
}
// check that worker has any new reward
if (maxAllowableReward > workerWithdrawnReward) {
return maxAllowableReward - workerWithdrawnReward;
}
return 0;
}
/**
* @notice Get available reward in tokens for delegator
*/
function getAvailableDelegatorReward(address _delegator) public view returns (uint256) {
// special case when there are no delegators
if (totalDepositedTokens == 0) {
return 0;
}
// total current and historical reward
uint256 reward = getCumulativeReward();
Delegator storage delegator = delegators[_delegator];
uint256 fraction = getWorkerFraction();
// calculate total reward for delegator including historical reward
// excluding worker share
uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div(
totalDepositedTokens.mul(BASIS_FRACTION)
);
// check that worker has any new reward
if (maxAllowableReward > delegator.withdrawnReward) {
return maxAllowableReward - delegator.withdrawnReward;
}
return 0;
}
/**
* @notice Withdraw reward in tokens to worker node owner
*/
function withdrawWorkerReward() external {
require(msg.sender == workerOwner);
uint256 balance = token.balanceOf(address(this));
uint256 availableReward = getAvailableWorkerReward();
if (availableReward > balance) {
availableReward = balance;
}
require(
availableReward > 0,
"There is no available reward to withdraw"
);
workerWithdrawnReward = workerWithdrawnReward.add(availableReward);
totalWithdrawnReward = totalWithdrawnReward.add(availableReward);
token.safeTransfer(msg.sender, availableReward);
emit TokensWithdrawn(msg.sender, availableReward, 0);
}
/**
* @notice Withdraw reward to delegator
* @param _value Amount of tokens to withdraw
*/
function withdrawTokens(uint256 _value) public override {
uint256 balance = token.balanceOf(address(this));
require(_value <= balance, "Not enough tokens in the contract");
Delegator storage delegator = delegators[msg.sender];
uint256 availableReward = getAvailableDelegatorReward(msg.sender);
require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion");
delegator.withdrawnReward = delegator.withdrawnReward.add(_value);
totalWithdrawnReward = totalWithdrawnReward.add(_value);
token.safeTransfer(msg.sender, _value);
emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Withdraw reward, deposit and fee to delegator
*/
function withdrawAll() public {
require(isWithdrawAllAllowed(), "Withdraw deposit and reward must be enabled");
uint256 balance = token.balanceOf(address(this));
Delegator storage delegator = delegators[msg.sender];
uint256 availableReward = getAvailableDelegatorReward(msg.sender);
uint256 value = availableReward.add(delegator.depositedTokens);
require(value <= balance, "Not enough tokens in the contract");
// TODO remove double reading: availableReward and availableWorkerReward use same calls to external contracts
uint256 availableWorkerReward = getAvailableWorkerReward();
// potentially could be less then due reward
uint256 availableETH = getAvailableDelegatorETH(msg.sender);
// prevent losing reward for worker after calculations
uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens);
if (workerReward > 0) {
require(value.add(workerReward) <= balance, "Not enough tokens in the contract");
token.safeTransfer(workerOwner, workerReward);
emit TokensWithdrawn(workerOwner, workerReward, 0);
}
uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens);
workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease);
totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward);
totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens);
delegator.withdrawnReward = 0;
delegator.depositedTokens = 0;
token.safeTransfer(msg.sender, value);
emit TokensWithdrawn(msg.sender, value, 0);
totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH);
delegator.withdrawnETH = 0;
if (availableETH > 0) {
emit ETHWithdrawn(msg.sender, availableETH);
msg.sender.sendValue(availableETH);
}
}
/**
* @notice Get available ether for delegator
*/
function getAvailableDelegatorETH(address _delegator) public view returns (uint256) {
Delegator storage delegator = delegators[_delegator];
uint256 balance = address(this).balance;
// ETH balance + already withdrawn
balance = balance.add(totalWithdrawnETH);
uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens);
uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/**
* @notice Withdraw available amount of ETH to delegator
*/
function withdrawETH() public override {
Delegator storage delegator = delegators[msg.sender];
uint256 availableETH = getAvailableDelegatorETH(msg.sender);
require(availableETH > 0, "There is no available ETH to withdraw");
delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH);
totalWithdrawnETH = totalWithdrawnETH.add(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
msg.sender.sendValue(availableETH);
}
/**
* @notice Calling fallback function is allowed only for the owner
*/
function isFallbackAllowed() public override view returns (bool) {
return msg.sender == owner();
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/math/SafeMath.sol";
import "./AbstractStakingContract.sol";
/**
* @notice Contract holds tokens for vesting.
* Also tokens can be used as a stake in the staking escrow contract
*/
contract PreallocationEscrow is AbstractStakingContract, Ownable {
using SafeMath for uint256;
using SafeERC20 for NuCypherToken;
using Address for address payable;
event TokensDeposited(address indexed sender, uint256 value, uint256 duration);
event TokensWithdrawn(address indexed owner, uint256 value);
event ETHWithdrawn(address indexed owner, uint256 value);
StakingEscrow public immutable stakingEscrow;
uint256 public lockedValue;
uint256 public endLockTimestamp;
/**
* @param _router Address of the StakingInterfaceRouter contract
*/
constructor(StakingInterfaceRouter _router) AbstractStakingContract(_router) {
stakingEscrow = _router.target().escrow();
}
/**
* @notice Initial tokens deposit
* @param _sender Token sender
* @param _value Amount of token to deposit
* @param _duration Duration of tokens locking
*/
function initialDeposit(address _sender, uint256 _value, uint256 _duration) internal {
require(lockedValue == 0 && _value > 0);
endLockTimestamp = block.timestamp.add(_duration);
lockedValue = _value;
token.safeTransferFrom(_sender, address(this), _value);
emit TokensDeposited(_sender, _value, _duration);
}
/**
* @notice Initial tokens deposit
* @param _value Amount of token to deposit
* @param _duration Duration of tokens locking
*/
function initialDeposit(uint256 _value, uint256 _duration) external {
initialDeposit(msg.sender, _value, _duration);
}
/**
* @notice Implementation of the receiveApproval(address,uint256,address,bytes) method
* (see NuCypherToken contract). Initial tokens deposit
* @param _from Sender
* @param _value Amount of tokens to deposit
* @param _tokenContract Token contract address
* @notice (param _extraData) Amount of seconds during which tokens will be locked
*/
function receiveApproval(
address _from,
uint256 _value,
address _tokenContract,
bytes calldata /* _extraData */
)
external
{
require(_tokenContract == address(token) && msg.sender == address(token));
// Copy first 32 bytes from _extraData, according to calldata memory layout:
//
// 0x00: method signature 4 bytes
// 0x04: _from 32 bytes after encoding
// 0x24: _value 32 bytes after encoding
// 0x44: _tokenContract 32 bytes after encoding
// 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter)
// 0x84: _extraData length 32 bytes
// 0xA4: _extraData data Length determined by previous variable
//
// See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples
uint256 payloadSize;
uint256 payload;
assembly {
payloadSize := calldataload(0x84)
payload := calldataload(0xA4)
}
payload = payload >> 8*(32 - payloadSize);
initialDeposit(_from, _value, payload);
}
/**
* @notice Get locked tokens value
*/
function getLockedTokens() public view returns (uint256) {
if (endLockTimestamp <= block.timestamp) {
return 0;
}
return lockedValue;
}
/**
* @notice Withdraw available amount of tokens to owner
* @param _value Amount of token to withdraw
*/
function withdrawTokens(uint256 _value) public override onlyOwner {
uint256 balance = token.balanceOf(address(this));
require(balance >= _value);
// Withdrawal invariant for PreallocationEscrow:
// After withdrawing, the sum of all escrowed tokens (either here or in StakingEscrow) must exceed the locked amount
require(balance - _value + stakingEscrow.getAllTokens(address(this)) >= getLockedTokens());
token.safeTransfer(msg.sender, _value);
emit TokensWithdrawn(msg.sender, _value);
}
/**
* @notice Withdraw available ETH to the owner
*/
function withdrawETH() public override onlyOwner {
uint256 balance = address(this).balance;
require(balance != 0);
msg.sender.sendValue(balance);
emit ETHWithdrawn(msg.sender, balance);
}
/**
* @notice Calling fallback function is allowed only for the owner
*/
function isFallbackAllowed() public view override returns (bool) {
return msg.sender == owner();
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/math/SafeMath.sol";
import "./AbstractStakingContract.sol";
/**
* @notice Contract acts as delegate for sub-stakers and owner
* @author @vzotova and @roma_k
**/
contract WorkLockPoolingContract is InitializableStakingContract, Ownable {
using SafeMath for uint256;
using Address for address payable;
using SafeERC20 for NuCypherToken;
event TokensDeposited(
address indexed sender,
uint256 value,
uint256 depositedTokens
);
event TokensWithdrawn(
address indexed sender,
uint256 value,
uint256 depositedTokens
);
event ETHWithdrawn(address indexed sender, uint256 value);
event DepositSet(address indexed sender, bool value);
event Bid(address indexed sender, uint256 depositedETH);
event Claimed(address indexed sender, uint256 claimedTokens);
event Refund(address indexed sender, uint256 refundETH);
struct Delegator {
uint256 depositedTokens;
uint256 withdrawnReward;
uint256 withdrawnETH;
uint256 depositedETHWorkLock;
uint256 refundedETHWorkLock;
bool claimedWorkLockTokens;
}
uint256 public constant BASIS_FRACTION = 100;
StakingEscrow public escrow;
WorkLock public workLock;
address public workerOwner;
uint256 public totalDepositedTokens;
uint256 public workLockClaimedTokens;
uint256 public totalWithdrawnReward;
uint256 public totalWithdrawnETH;
uint256 public totalWorkLockETHReceived;
uint256 public totalWorkLockETHRefunded;
uint256 public totalWorkLockETHWithdrawn;
uint256 workerFraction;
uint256 public workerWithdrawnReward;
mapping(address => Delegator) public delegators;
bool depositIsEnabled = true;
/**
* @notice Initialize function for using with OpenZeppelin proxy
* @param _workerFraction Share of token reward that worker node owner will get.
* Use value up to BASIS_FRACTION, if _workerFraction = BASIS_FRACTION -> means 100% reward as commission
* @param _router StakingInterfaceRouter address
* @param _workerOwner Owner of worker node, only this address can withdraw worker commission
*/
function initialize(
uint256 _workerFraction,
StakingInterfaceRouter _router,
address _workerOwner
) public initializer {
require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION);
InitializableStakingContract.initialize(_router);
_transferOwnership(msg.sender);
escrow = _router.target().escrow();
workLock = _router.target().workLock();
workerFraction = _workerFraction;
workerOwner = _workerOwner;
}
/**
* @notice Enabled deposit
*/
function enableDeposit() external onlyOwner {
depositIsEnabled = true;
emit DepositSet(msg.sender, depositIsEnabled);
}
/**
* @notice Disable deposit
*/
function disableDeposit() external onlyOwner {
depositIsEnabled = false;
emit DepositSet(msg.sender, depositIsEnabled);
}
/**
* @notice Calculate worker's fraction depending on deposited tokens
*/
function getWorkerFraction() public view returns (uint256) {
return workerFraction;
}
/**
* @notice Transfer tokens as delegator
* @param _value Amount of tokens to transfer
*/
function depositTokens(uint256 _value) external {
require(depositIsEnabled, "Deposit must be enabled");
require(_value > 0, "Value must be not empty");
totalDepositedTokens = totalDepositedTokens.add(_value);
Delegator storage delegator = delegators[msg.sender];
delegator.depositedTokens = delegator.depositedTokens.add(_value);
token.safeTransferFrom(msg.sender, address(this), _value);
emit TokensDeposited(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Delegator can transfer ETH directly to workLock
*/
function escrowETH() external payable {
Delegator storage delegator = delegators[msg.sender];
delegator.depositedETHWorkLock = delegator.depositedETHWorkLock.add(msg.value);
totalWorkLockETHReceived = totalWorkLockETHReceived.add(msg.value);
workLock.bid{value: msg.value}();
emit Bid(msg.sender, msg.value);
}
/**
* @dev Hide method from StakingInterface
*/
function bid(uint256) public payable {
revert();
}
/**
* @dev Hide method from StakingInterface
*/
function withdrawCompensation() public pure {
revert();
}
/**
* @dev Hide method from StakingInterface
*/
function cancelBid() public pure {
revert();
}
/**
* @dev Hide method from StakingInterface
*/
function claim() public pure {
revert();
}
/**
* @notice Claim tokens in WorkLock and save number of claimed tokens
*/
function claimTokensFromWorkLock() public {
workLockClaimedTokens = workLock.claim();
totalDepositedTokens = totalDepositedTokens.add(workLockClaimedTokens);
emit Claimed(address(this), workLockClaimedTokens);
}
/**
* @notice Calculate and save number of claimed tokens for specified delegator
*/
function calculateAndSaveTokensAmount() external {
Delegator storage delegator = delegators[msg.sender];
calculateAndSaveTokensAmount(delegator);
}
/**
* @notice Calculate and save number of claimed tokens for specified delegator
*/
function calculateAndSaveTokensAmount(Delegator storage _delegator) internal {
if (workLockClaimedTokens == 0 ||
_delegator.depositedETHWorkLock == 0 ||
_delegator.claimedWorkLockTokens)
{
return;
}
uint256 delegatorTokensShare = _delegator.depositedETHWorkLock.mul(workLockClaimedTokens)
.div(totalWorkLockETHReceived);
_delegator.depositedTokens = _delegator.depositedTokens.add(delegatorTokensShare);
_delegator.claimedWorkLockTokens = true;
emit Claimed(msg.sender, delegatorTokensShare);
}
/**
* @notice Get available reward for all delegators and owner
*/
function getAvailableReward() public view returns (uint256) {
uint256 stakedTokens = escrow.getAllTokens(address(this));
uint256 freeTokens = token.balanceOf(address(this));
uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens);
if (reward > freeTokens) {
return freeTokens;
}
return reward;
}
/**
* @notice Get cumulative reward
*/
function getCumulativeReward() public view returns (uint256) {
return getAvailableReward().add(totalWithdrawnReward);
}
/**
* @notice Get available reward in tokens for worker node owner
*/
function getAvailableWorkerReward() public view returns (uint256) {
uint256 reward = getCumulativeReward();
uint256 maxAllowableReward;
if (totalDepositedTokens != 0) {
uint256 fraction = getWorkerFraction();
maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION);
} else {
maxAllowableReward = reward;
}
if (maxAllowableReward > workerWithdrawnReward) {
return maxAllowableReward - workerWithdrawnReward;
}
return 0;
}
/**
* @notice Get available reward in tokens for delegator
*/
function getAvailableReward(address _delegator)
public
view
returns (uint256)
{
if (totalDepositedTokens == 0) {
return 0;
}
uint256 reward = getCumulativeReward();
Delegator storage delegator = delegators[_delegator];
uint256 fraction = getWorkerFraction();
uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div(
totalDepositedTokens.mul(BASIS_FRACTION)
);
return
maxAllowableReward > delegator.withdrawnReward
? maxAllowableReward - delegator.withdrawnReward
: 0;
}
/**
* @notice Withdraw reward in tokens to worker node owner
*/
function withdrawWorkerReward() external {
require(msg.sender == workerOwner);
uint256 balance = token.balanceOf(address(this));
uint256 availableReward = getAvailableWorkerReward();
if (availableReward > balance) {
availableReward = balance;
}
require(
availableReward > 0,
"There is no available reward to withdraw"
);
workerWithdrawnReward = workerWithdrawnReward.add(availableReward);
totalWithdrawnReward = totalWithdrawnReward.add(availableReward);
token.safeTransfer(msg.sender, availableReward);
emit TokensWithdrawn(msg.sender, availableReward, 0);
}
/**
* @notice Withdraw reward to delegator
* @param _value Amount of tokens to withdraw
*/
function withdrawTokens(uint256 _value) public override {
uint256 balance = token.balanceOf(address(this));
require(_value <= balance, "Not enough tokens in the contract");
Delegator storage delegator = delegators[msg.sender];
calculateAndSaveTokensAmount(delegator);
uint256 availableReward = getAvailableReward(msg.sender);
require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion");
delegator.withdrawnReward = delegator.withdrawnReward.add(_value);
totalWithdrawnReward = totalWithdrawnReward.add(_value);
token.safeTransfer(msg.sender, _value);
emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Withdraw reward, deposit and fee to delegator
*/
function withdrawAll() public {
uint256 balance = token.balanceOf(address(this));
Delegator storage delegator = delegators[msg.sender];
calculateAndSaveTokensAmount(delegator);
uint256 availableReward = getAvailableReward(msg.sender);
uint256 value = availableReward.add(delegator.depositedTokens);
require(value <= balance, "Not enough tokens in the contract");
// TODO remove double reading
uint256 availableWorkerReward = getAvailableWorkerReward();
// potentially could be less then due reward
uint256 availableETH = getAvailableETH(msg.sender);
// prevent losing reward for worker after calculations
uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens);
if (workerReward > 0) {
require(value.add(workerReward) <= balance, "Not enough tokens in the contract");
token.safeTransfer(workerOwner, workerReward);
emit TokensWithdrawn(workerOwner, workerReward, 0);
}
uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens);
workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease);
totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward);
totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens);
delegator.withdrawnReward = 0;
delegator.depositedTokens = 0;
token.safeTransfer(msg.sender, value);
emit TokensWithdrawn(msg.sender, value, 0);
totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH);
delegator.withdrawnETH = 0;
if (availableETH > 0) {
msg.sender.sendValue(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
}
}
/**
* @notice Get available ether for delegator
*/
function getAvailableETH(address _delegator) public view returns (uint256) {
Delegator storage delegator = delegators[_delegator];
uint256 balance = address(this).balance;
// ETH balance + already withdrawn - (refunded - refundWithdrawn)
balance = balance.add(totalWithdrawnETH).add(totalWorkLockETHWithdrawn).sub(totalWorkLockETHRefunded);
uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens);
uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/**
* @notice Withdraw available amount of ETH to delegator
*/
function withdrawETH() public override {
Delegator storage delegator = delegators[msg.sender];
calculateAndSaveTokensAmount(delegator);
uint256 availableETH = getAvailableETH(msg.sender);
require(availableETH > 0, "There is no available ETH to withdraw");
delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH);
totalWithdrawnETH = totalWithdrawnETH.add(availableETH);
msg.sender.sendValue(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
}
/**
* @notice Withdraw compensation and refund from WorkLock and save these numbers
*/
function refund() public {
uint256 balance = address(this).balance;
if (workLock.compensation(address(this)) > 0) {
workLock.withdrawCompensation();
}
workLock.refund();
uint256 refundETH = address(this).balance - balance;
totalWorkLockETHRefunded = totalWorkLockETHRefunded.add(refundETH);
emit Refund(address(this), refundETH);
}
/**
* @notice Get available refund for delegator
*/
function getAvailableRefund(address _delegator) public view returns (uint256) {
Delegator storage delegator = delegators[_delegator];
uint256 maxAllowableETH = totalWorkLockETHRefunded.mul(delegator.depositedETHWorkLock)
.div(totalWorkLockETHReceived);
uint256 availableETH = maxAllowableETH.sub(delegator.refundedETHWorkLock);
uint256 balance = totalWorkLockETHRefunded.sub(totalWorkLockETHWithdrawn);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/*
* @notice Withdraw available amount of ETH to delegator
*/
function withdrawRefund() external {
uint256 availableETH = getAvailableRefund(msg.sender);
require(availableETH > 0, "There is no available ETH to withdraw");
Delegator storage delegator = delegators[msg.sender];
delegator.refundedETHWorkLock = delegator.refundedETHWorkLock.add(availableETH);
totalWorkLockETHWithdrawn = totalWorkLockETHWithdrawn.add(availableETH);
msg.sender.sendValue(availableETH);
emit Refund(msg.sender, availableETH);
}
/**
* @notice Calling fallback function is allowed only for the owner
*/
function isFallbackAllowed() public override view returns (bool) {
return msg.sender == owner();
}
}
| * @notice Get available reward in tokens for delegator/ | function getAvailableReward(address _delegator) public view returns (uint256) {
if (totalDepositedTokens == 0) {
return 0;
}
uint256 reward = getCumulativeReward();
Delegator storage delegator = delegators[_delegator];
uint256 maxAllowableReward = reward.mul(delegator.depositedTokens)
.div(totalDepositedTokens.add(ownerFraction));
return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0;
}
| 1,393,576 | [
1,
967,
2319,
19890,
316,
2430,
364,
11158,
639,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
15796,
17631,
1060,
12,
2867,
389,
3771,
1332,
639,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
4963,
758,
1724,
329,
5157,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
19890,
273,
1927,
11276,
17631,
1060,
5621,
203,
3639,
24117,
639,
2502,
11158,
639,
273,
11158,
3062,
63,
67,
3771,
1332,
639,
15533,
203,
3639,
2254,
5034,
943,
31508,
17631,
1060,
273,
19890,
18,
16411,
12,
3771,
1332,
639,
18,
323,
1724,
329,
5157,
13,
203,
5411,
263,
2892,
12,
4963,
758,
1724,
329,
5157,
18,
1289,
12,
8443,
13724,
10019,
203,
203,
3639,
327,
943,
31508,
17631,
1060,
405,
11158,
639,
18,
1918,
9446,
82,
17631,
1060,
692,
943,
31508,
17631,
1060,
300,
11158,
639,
18,
1918,
9446,
82,
17631,
1060,
294,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xc528dCf51c9DD63B49DebBC8FE524C600CEad3D2/sources/MusicRoomDAO.sol | * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). If there are multiple variables, please pack them into a uint64./ | function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
| 3,934,942 | [
1,
2785,
326,
9397,
737,
814,
501,
364,
1375,
8443,
8338,
261,
73,
18,
75,
18,
1300,
434,
10734,
312,
474,
12169,
1399,
2934,
971,
1915,
854,
3229,
3152,
16,
9582,
2298,
2182,
1368,
279,
2254,
1105,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
389,
542,
21981,
12,
2867,
3410,
16,
2254,
1105,
9397,
13,
2713,
288,
203,
3639,
309,
261,
8443,
422,
1758,
12,
20,
3719,
15226,
432,
2616,
1138,
1290,
7170,
1887,
5621,
203,
3639,
389,
2867,
751,
63,
8443,
8009,
18196,
273,
9397,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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/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 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract FuDaoVerseDAN is ERC721, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
using ECDSA for bytes32;
//NFT params
string public baseURI;
bool public revealed;
string public notRevealedUri;
IERC721 public OG;
//sale stages:
//stage 0: init(no minting)
//stage 1: free-mint
//stage 2: pre-sale, OGs are included in here
//stage 2.5: whitelisted can mint an extra 2, increase presaleMintMax to 4
//stage 3: public sale
Counters.Counter public tokenSupply;
uint8 public stage = 0;
mapping(uint256 => bool) public isOGMinted;
mapping(uint256 => uint8) public OGWhitelistMintCount;
uint256 public VIP_PASSES = 888;
uint256 public presaleSalePrice = 0.077 ether;
uint256 public presaleSupply = 6666;
uint256 public presaleMintMax = 2;
mapping(address => uint8) public presaleMintCount;
mapping(address => uint8) public vipMintCount; // For Whitelist Sale
mapping(address => uint256) public publicMintCount;
//public sale (stage=3)
uint256 public publicSalePrice = 0.088 ether;
uint256 public publicMintMax = 2;
uint256 public totalSaleSupply = 8888;
//others
bool public paused = false;
//sale holders
address[2] public fundRecipients = [
0xaDDfdc72494E29A131B1d4d6668184840f1Fc30C,
0xcD7BCAc7Ee5c18d8cC1374B62F09cf67e6432a08
];
uint256[] public receivePercentagePt = [7000]; //distribution in basis points
// Off-chain whitelist
address private signerAddress;
mapping(bytes => bool) private _nonceUsed;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
address _newOwner,
address _signerAddress,
address ogCollection
) ERC721(_name, _symbol) {
setNotRevealedURI(_initBaseURI);
signerAddress = _signerAddress;
transferOwnership(_newOwner);
OG = IERC721(ogCollection);
}
event VIPMint(address indexed to, uint256 tokenId);
event WhitelistMint(address indexed to, uint256 tokenId);
event PublicMint(address indexed to, uint256 mintAmount);
event DevMint(uint256 count);
event Airdrop(address indexed to, uint256 tokenId);
/**
* @notice Performs respective minting condition checks depending on stage of minting
* @param tokenIds tokenIds of VIP Pass
* @dev Stage 1: OG Mints, Free Claim for OG Pass Holders
* @dev Each Pass can only be used once to claim
* @dev Minter must be owner of OG pass to claim
*/
function vipMint(uint256[] memory tokenIds) public {
require(!paused, "FuDaoVerseDAN: Contract is paused");
require(stage > 0, "FuDaoVerseDAN: Minting has not started");
for (uint256 i; i < tokenIds.length; i++) {
require(
OG.ownerOf(tokenIds[i]) == msg.sender,
"FuDaoVerseDAN: Claimant is not the owner!"
);
require(
!isOGMinted[tokenIds[i]],
"FuDaoVerseDAN: OG Token has already been used!"
);
_vipMint(tokenIds[i]);
}
}
function _vipMint(uint256 tokenId) internal {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
isOGMinted[tokenId] = true;
VIP_PASSES--;
emit VIPMint(msg.sender, tokenSupply.current());
}
/**
* @notice VIP Whitelist Mint. VIPs are automatically whitelisted and can use their Mint pass to mint
* @param _mintAmount Amount minted for vipWhitelistMint
* @dev Stage 2: Presale Mints, VIP Automatically whitelisted
* @dev 2 VIP Whitelist Mints at stage 2, another 2 VIP Whitelist Mints at stage 2.5
* @dev Minter must hold an OG pass to VIP Whitelist Mint
*/
function vipWhitelistMint(uint8 _mintAmount) public payable {
require(!paused, "FuDaoVerseDAN: Contract is paused");
require(stage == 2, "FuDaoVerseDAN: Private Sale Closed!");
require(
msg.value == _mintAmount * presaleSalePrice,
"FuDaoVerseDAN: Insufficient ETH!"
);
require(
tokenSupply.current() + _mintAmount <= presaleSupply,
"FuDaoVerseDAN: Max Supply for Presale Mint Reached!"
);
require(
OG.balanceOf(msg.sender) > 0,
"FuDaoVerseDAN: Claimant does not own a mint pass"
);
require(
presaleMintCount[msg.sender] + _mintAmount <= presaleMintMax,
"FuDaoVerseDAN: Claimant has exceeded VIP Whitelist Mint Max!"
);
presaleMintCount[msg.sender] += _mintAmount;
for (uint8 i; i < _mintAmount; i++) {
_vipWhitelistMint();
}
}
function _vipWhitelistMint() internal {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
emit VIPMint(msg.sender, tokenSupply.current());
}
/**
* @notice Performs respective minting condition checks depending on stage of minting
* @param _mintAmount Amount that is minted
* @param nonce Random bytes32 nonce
* @param signature Signature generated off-chain
* @dev Stage 1: OG Mints, Free Claim for OG Pass Holders
* @dev Each Pass can only be used once to claim
*/
function whitelistMint(
uint8 _mintAmount,
bytes memory signature,
bytes memory nonce
) public payable {
require(!paused, "FuDaoVerseDAN: Contract is paused");
require(stage == 2, "FuDaoVerseDAN: Private Sale Closed!");
require(!_nonceUsed[nonce], "FuDaoVerseDAN: Nonce already used");
_nonceUsed[nonce] = true;
require(
whitelistSigned(msg.sender, nonce, signature),
"FuDaoVerseDAN: Invalid signature!"
);
require(
tokenSupply.current() + _mintAmount <= presaleSupply,
"FuDaoVerseDAN: Max Supply for Presale Mint Reached!"
);
require(
msg.value == _mintAmount * presaleSalePrice,
"FuDaoVerseDAN: Insufficient ETH!"
);
require(
presaleMintCount[msg.sender] + _mintAmount <= presaleMintMax,
"FuDaoVerseDAN: Wallet has already minted Max Amount for Presale!"
);
presaleMintCount[msg.sender] += _mintAmount;
for (uint256 i; i < _mintAmount; i++) {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
emit WhitelistMint(msg.sender, tokenSupply.current());
}
}
/**
* @notice Public Mint
* @param _mintAmount Amount that is minted
* @dev Stage 3: Public Mint
*/
function publicMint(uint8 _mintAmount) public payable {
require(!paused, "FuDaoVerseDAN: Contract is paused");
require(stage == 3, "FuDaoVerseDAN: Public Sale Closed!");
require(
msg.value == _mintAmount * publicSalePrice,
"FuDaoVerseDAN: Insufficient ETH!"
);
require(
tokenSupply.current() + _mintAmount <= totalSaleSupply - VIP_PASSES,
"FuDaoVerseDAN: Max Supply for Public Mint Reached!"
);
require(
publicMintCount[msg.sender] + _mintAmount <= publicMintMax,
"FuDaoVerseDAN: Wallet has already minted Max Amount for Public!"
);
publicMintCount[msg.sender] += _mintAmount; // FIX: Gas Optimization
for (uint256 i; i < _mintAmount; i++) {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
emit PublicMint(msg.sender, tokenSupply.current());
}
}
/**
* @dev Mints NFTS to the owner's wallet
* @param _mintAmount Amount to mint
*/
function devMint(uint8 _mintAmount) public onlyOwner {
require(
tokenSupply.current() + _mintAmount <= totalSaleSupply,
"FuDaoVerseDAN: Max Supply Reached!"
);
for (uint256 i; i < _mintAmount; i++) {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
}
emit DevMint(_mintAmount);
}
/**
* @dev Airdrops NFTs to the list of addresses provided
* @param addresses List of airdrop recepients
*/
function airdrop(address[] memory addresses) public onlyOwner {
require(
tokenSupply.current() + addresses.length <= totalSaleSupply,
"FuDaoVerseDAN: Max Supply Reached!"
);
for (uint256 i; i < addresses.length; i++) {
tokenSupply.increment();
_safeMint(addresses[i], tokenSupply.current());
emit Airdrop(addresses[i], tokenSupply.current());
}
}
/**
* @dev Checks if the the signature is signed by a valid signer for whitelists
* @param sender Address of minter
* @param nonce Random bytes32 nonce
* @param signature Signature generated off-chain
*/
function whitelistSigned(
address sender,
bytes memory nonce,
bytes memory signature
) private view returns (bool) {
bytes32 hash = keccak256(abi.encodePacked(sender, nonce));
return signerAddress == hash.recover(signature);
}
// ------------------------- VIEW FUNCTIONS -----------------------------
/**
* @notice Returns metadata URI for sepecified token id
* @param tokenId Token Id to retrieve metadata
* @return Metadata URI
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
".json"
)
)
: "";
}
/**
* @notice Total NFTs Minted
*/
function totalSupply() public view returns (uint256) {
return tokenSupply.current();
}
// ------------------------- ADMIN FUNCTIONS -----------------------------
/**
* @dev Set Mint Stage
*/
function setStage(uint8 _stage) public onlyOwner {
require(stage < 4, "FuDaoVerseDAN: Exceeded maximum number of stages");
stage = _stage;
}
/**
* @dev Set Revealed Metadata URI
*/
function setBaseURI(string memory _newBaseURI) public onlyOwner {
require(!revealed);
baseURI = _newBaseURI;
}
/**
* @dev Set Presale maximum amount of mints
*/
function setPresaleMintMax(uint256 amount) public onlyOwner {
presaleMintMax = amount;
}
/**
* @dev Set the unrevealed URI
* @param _notRevealedURI unrevealed URI for metadata
*/
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
/**
* @dev Set Revealed state of NFT metadata
*/
function reveal() public onlyOwner {
revealed = true;
}
/**
* @dev Switches pause state to `_state`
* @param _state Pause State
*/
function pause(bool _state) public onlyOwner {
paused = _state;
}
/**
* @dev Emergency Function to withdraw any ETH deposited to this contract
*/
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
/**
* @dev requires currentBalance of contract to have some amount
* @dev withdraws with the fixed define distribution
*/
function withdrawFund() public onlyOwner {
uint256 currentBal = address(this).balance;
require(currentBal > 0);
for (uint256 i = 0; i < fundRecipients.length - 1; i++) {
_withdraw(
fundRecipients[i],
(currentBal * receivePercentagePt[i]) / 10000
);
}
//final address receives remainder to prevent ether dust
_withdraw(
fundRecipients[fundRecipients.length - 1],
address(this).balance
);
}
/**
* @dev private function utilized by withdrawFund
* @param _addr Address of receiver
* @param _amt Amount to withdraw
*/
function _withdraw(address _addr, uint256 _amt) private {
(bool success, ) = _addr.call{value: _amt}("");
require(success, "Transfer failed");
}
/**
* @dev retrieve base URI internally
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
} | * @dev Set Revealed Metadata URI/ | function setBaseURI(string memory _newBaseURI) public onlyOwner {
require(!revealed);
baseURI = _newBaseURI;
}
| 13,708,003 | [
1,
694,
868,
537,
18931,
6912,
3699,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
26435,
3098,
12,
1080,
3778,
389,
2704,
2171,
3098,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
5,
266,
537,
18931,
1769,
203,
3639,
1026,
3098,
273,
389,
2704,
2171,
3098,
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
] |
pragma solidity ^0.4.24;
contract WeatherC2 {
address owner;
//uint constant price = 1 ether;
mapping (address => WeatherStation) private stations;
struct WeatherStation {
address stationAddress;
string name;
address[] accessList;
string temperature;
string humidity;
string picture;
string livestream;
uint price;
}
WeatherStation[] private addressList;
constructor() public {
owner = msg.sender;
}
//checks if the owner tries to execute the function
modifier onlyBy {
require(msg.sender == owner, "not owner");
_;
}
//If the delivered station address is on the accesslist the function will be executed
modifier onAccessList(address sAddress) {
bool x;
x = true;
for(uint i = 0; i < stations[sAddress].accessList.length; i++){
if (stations[sAddress].accessList[i] == msg.sender){
x = false;
_;
}
}
if (x){
revert("not on accesslist");
}
}
//If the delivered station address is NOT on the accesslist the function will be executed
modifier notOnAccessList(address sAddress) {
for(uint i = 0; i < stations[sAddress].accessList.length; i++){
if (stations[sAddress].accessList[i] == msg.sender){
revert("Already paid");
}
}
_;
}
//checks if mapping is already set
modifier addressNotZero() {
require(stations[msg.sender].stationAddress == address(0x0), "Mapping already set");
_;
}
//Creates a new Weather Station. Can only be executed once per Station
function createStation(string name) public addressNotZero {
WeatherStation memory ws;
ws.stationAddress = msg.sender;
ws.name = name;
addressList.push(ws);
stations[msg.sender] = ws;
}
//The Weather Station can only update references for itself (msg.sender)
function updateReference(string tem, string hum, string pic, string live) public {
stations[msg.sender].temperature = tem;
stations[msg.sender].humidity = hum;
stations[msg.sender].picture = pic;
stations[msg.sender].livestream = live;
}
function updatePrice(uint price) public {
stations[msg.sender].price = price * 1000000000000000000;
}
//function to pay for the data. Can be executed only once per account.
function pay(address sAddress) public notOnAccessList(sAddress) payable {
if (msg.value != stations[sAddress].price || msg.value == 0) {
revert("Not enough Ether");
}
stations[sAddress].accessList.push(msg.sender);
sAddress.transfer(stations[sAddress].price);
}
//Returns data references, checks if account already paid.
function getReference(address sAddress) public constant onAccessList(sAddress) returns(string, string, string, string) {
return(stations[sAddress].temperature, stations[sAddress].humidity, stations[sAddress].picture, stations[sAddress].livestream);
}
//Returns
function getStations(uint nr) public constant returns(address, string) {
return (addressList[nr].stationAddress, addressList[nr].name);
}
//returns station count
function getStationCount() public constant returns(uint) {
return (addressList.length);
}
//Destroys this smart contract, all funds of this smart contracts gets back to owner (should be nothing)
function destroyContract() public onlyBy {
selfdestruct(owner);
}
}
| returns station count | function getStationCount() public constant returns(uint) {
return (addressList.length);
}
| 5,375,408 | [
1,
6154,
13282,
1056,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
16672,
1380,
1435,
1071,
5381,
1135,
12,
11890,
13,
288,
203,
3639,
327,
261,
2867,
682,
18,
2469,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x5ddD9989284A9CAb04c2144C839d35aD5b53217C/sources/f0rG.sol | create uniswap pair | constructor() {
address _uniswapPair =
IUniswapV2Factory(UNISWAP_V2_ROUTER.factory()).createPair(address(this), UNISWAP_V2_ROUTER.WETH());
UNISWAP_V2_PAIR = _uniswapPair;
_setAutomatedMarketMakerPair(address(_uniswapPair), true);
_allowances[address(this)][address(UNISWAP_V2_ROUTER)] = type(uint256).max;
_allowances[address(this)][owner()] = type(uint256).max;
isLimitExempt[address(this)] = true;
isLimitExempt[DEAD] = true;
isLimitExempt[owner()] = true;
isLimitExempt[UNISWAP_V2_PAIR] = true;
isFeeExempt[address(this)] = true;
isFeeExempt[DEAD] = true;
isFeeExempt[owner()] = true;
marketingFeeReceiver = 0xEB3b5D6C8732eA15527CA271E3Ac70816aC2FFb3;
lpFeeReceiver = 0xEB3b5D6C8732eA15527CA271E3Ac70816aC2FFb3;
buybackFeeReceiver = 0xEB3b5D6C8732eA15527CA271E3Ac70816aC2FFb3;
_rOwned[tx.origin] = _totalSupply;
emit Transfer(address(0), tx.origin, _totalSupply);
}
| 16,038,785 | [
1,
2640,
640,
291,
91,
438,
3082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
1435,
288,
203,
3639,
1758,
389,
318,
291,
91,
438,
4154,
273,
203,
5411,
467,
984,
291,
91,
438,
58,
22,
1733,
12,
2124,
5127,
59,
2203,
67,
58,
22,
67,
1457,
1693,
654,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
5019,
5127,
59,
2203,
67,
58,
22,
67,
1457,
1693,
654,
18,
59,
1584,
44,
10663,
203,
3639,
5019,
5127,
59,
2203,
67,
58,
22,
67,
4066,
7937,
273,
389,
318,
291,
91,
438,
4154,
31,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
24899,
318,
291,
91,
438,
4154,
3631,
638,
1769,
203,
203,
3639,
389,
5965,
6872,
63,
2867,
12,
2211,
13,
6362,
2867,
12,
2124,
5127,
59,
2203,
67,
58,
22,
67,
1457,
1693,
654,
25887,
273,
618,
12,
11890,
5034,
2934,
1896,
31,
203,
3639,
389,
5965,
6872,
63,
2867,
12,
2211,
13,
6362,
8443,
1435,
65,
273,
618,
12,
11890,
5034,
2934,
1896,
31,
203,
203,
3639,
353,
3039,
424,
5744,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
3639,
353,
3039,
424,
5744,
63,
1639,
1880,
65,
273,
638,
31,
203,
3639,
353,
3039,
424,
5744,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
353,
3039,
424,
5744,
63,
2124,
5127,
59,
2203,
67,
58,
22,
67,
4066,
7937,
65,
273,
638,
31,
203,
540,
203,
3639,
353,
14667,
424,
5744,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
3639,
353,
14667,
424,
5744,
63,
1639,
1880,
65,
273,
638,
31,
203,
3639,
353,
2
] |
pragma solidity >=0.4.18;
import "../exchange/EnglishAuction.sol";
contract MintingAuctionUtility is EnglishAuction {
/*
@dev When a terraform auction is won, this can redeem it, sends Created Event
Sender must be approved
@param _tokenIds - tile tokens.
*/
function redeemTerraformAuction(
uint256[] _tokenIds
)
external
whenNotPaused
{
// will not complete if msg.sender did not win
landContract.mint(msg.sender, _tokenIds);
completeAuction(_tokenIds);
}
/*
@dev Creates and begins a new terraform auction (land is to be minted).
@param _tokenIds - tile tokens.
@param _startingPrice - Price of item (in wei) at beginning of auction.
@param _duration - Length of time to move between starting
@param _buyItNowPrice - Price user could buy it now at if set
*/
function createTerraformAuction(
uint256[] _tokenIds,
uint256 _startingPrice,
uint256 _duration,
uint256 _buyItNowPrice
)
limitBatchSize(_tokenIds)
external
onlyOwner
whenNotPaused
returns (uint)
{
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_duration == uint256(uint64(_duration)));
require(landContract.ownsTokens(0, _tokenIds));
// build token ids for parcels
return addAuction(this, _tokenIds, _startingPrice, _duration, _buyItNowPrice);
}
} | / will not complete if msg.sender did not win | {
landContract.mint(msg.sender, _tokenIds);
completeAuction(_tokenIds);
}
@param _tokenIds - tile tokens.
@param _startingPrice - Price of item (in wei) at beginning of auction.
@param _duration - Length of time to move between starting
@param _buyItNowPrice - Price user could buy it now at if set
| 12,665,263 | [
1,
19,
903,
486,
3912,
309,
1234,
18,
15330,
5061,
486,
5657,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
288,
203,
3639,
19193,
8924,
18,
81,
474,
12,
3576,
18,
15330,
16,
389,
2316,
2673,
1769,
203,
3639,
3912,
37,
4062,
24899,
2316,
2673,
1769,
203,
565,
289,
203,
203,
3639,
632,
891,
389,
2316,
2673,
300,
4769,
2430,
18,
203,
3639,
632,
891,
389,
18526,
5147,
300,
20137,
434,
761,
261,
267,
732,
77,
13,
622,
8435,
434,
279,
4062,
18,
203,
3639,
632,
891,
389,
8760,
300,
11311,
434,
813,
358,
3635,
3086,
5023,
203,
3639,
632,
891,
389,
70,
9835,
7193,
8674,
5147,
300,
20137,
729,
3377,
30143,
518,
2037,
622,
309,
444,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x6D0B05ef27C5D5A0783e86F6056B531616284D14/sources/contracts/RadbroWebringV2.sol | @notice Total number of radbros won as prizes for upgrading. | uint256 public mintedPrizeRadbros;
| 3,621,221 | [
1,
5269,
1300,
434,
767,
1966,
6973,
8462,
487,
846,
3128,
364,
731,
15210,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
312,
474,
329,
2050,
554,
6621,
4637,
87,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
import "@etherisc/gif-interface/contracts/0.7/Product.sol";
import "./IHelloWorldInsurance.sol";
import "./HelloWorldOracle.sol";
contract HelloWorldInsurance is IHelloWorldInsurance, Product {
bytes32 public constant VERSION = "0.0.1";
bytes32 public constant POLICY_FLOW = "PolicyFlowDefault";
uint256 public constant MIN_PREMIUM = 100 * 10**16;
uint256 public constant MAX_PREMIUM = 1500 * 10**16;
uint256 public constant PAYOUT_FACTOR_RUDE_RESPONSE = 3;
uint256 public constant PAYOUT_FACTOR_NO_RESPONSE = 1;
uint256 public constant PAYOUT_FACTOR_KIND_RESPONSE = 0;
uint16 public constant MAX_LENGTH_GREETING = 32;
string public constant CALLBACK_METHOD_NAME = "greetingCallback";
uint256 public uniqueIndex;
bytes32 public greetingsOracleType;
uint256 public greetingsOracleId;
mapping(bytes32 => address) public policyIdToAddress;
mapping(address => bytes32[]) public addressToPolicyIds;
constructor(
address gifProductService,
bytes32 productName,
bytes32 oracleType,
uint256 oracleId
)
Product(gifProductService, productName, POLICY_FLOW)
{
greetingsOracleType = oracleType;
greetingsOracleId = oracleId;
}
function applyForPolicy() external payable override returns (bytes32 policyId) {
address payable policyHolder = msg.sender;
uint256 premium = _getValue();
// Create new ID for this policy
policyId = _uniqueId(policyHolder);
// Validate input parameters
require(premium >= MIN_PREMIUM, "ERROR:HWI-001:INVALID_PREMIUM");
require(premium <= MAX_PREMIUM, "ERROR:HWI-002:INVALID_PREMIUM");
// Create and underwrite new application
_newApplication(policyId, abi.encode(premium, policyHolder));
_underwrite(policyId);
emit LogHelloWorldPolicyCreated(policyId);
// Book keeping to simplify lookup
policyIdToAddress[policyId] = policyHolder;
addressToPolicyIds[policyHolder].push(policyId);
}
function greet(bytes32 policyId, string calldata greeting) external override {
// Validate input parameters
require(policyIdToAddress[policyId] == msg.sender, "ERROR:HWI-003:INVALID_POLICY_OR_HOLDER");
require(bytes(greeting).length <= MAX_LENGTH_GREETING, "ERROR:HWI-004:GREETING_TOO_LONG");
emit LogHelloWorldGreetingReceived(policyId, greeting);
// request response to greeting via oracle call
uint256 requestId = _request(
policyId,
abi.encode(greeting),
CALLBACK_METHOD_NAME,
greetingsOracleType,
greetingsOracleId
);
emit LogHelloWorldGreetingCompleted(requestId, policyId, greeting);
}
function greetingCallback(uint256 requestId, bytes32 policyId, bytes calldata response)
external
onlyOracle
{
// get policy data for oracle response
(uint256 premium, address payable policyHolder) = abi.decode(
_getApplicationData(policyId), (uint256, address));
// get oracle response data
(HelloWorldOracle.AnswerType answer) = abi.decode(response, (HelloWorldOracle.AnswerType));
// claim handling based on reponse to greeting provided by oracle
_handleClaim(policyId, policyHolder, premium, answer);
// policy only covers a single greeting/response pair
// policy can therefore be expired
_expire(policyId);
emit LogHelloWorldCallbackCompleted(requestId, policyId, response);
}
function withdraw(uint256 amount) external override onlyOwner {
require(amount <= address(this).balance);
address payable receiver;
receiver = payable(owner());
receiver.transfer(amount);
}
function _getValue() internal returns(uint256 premium) { premium = msg.value; }
function _uniqueId(address senderAddress) internal returns (bytes32 uniqueId) {
uniqueIndex += 1;
return keccak256(abi.encode(senderAddress, productId, uniqueIndex));
}
function _handleClaim(
bytes32 policyId,
address payable policyHolder,
uint256 premium,
HelloWorldOracle.AnswerType answer
)
internal
{
uint256 payoutAmount = _calculatePayoutAmount(premium, answer);
// no claims handling for payouts == 0
if (payoutAmount > 0) {
uint256 claimId = _newClaim(policyId, abi.encode(payoutAmount));
uint256 payoutId = _confirmClaim(policyId, claimId, abi.encode(payoutAmount));
_payout(policyId, payoutId, true, abi.encode(payoutAmount));
// actual transfer of funds for payout of claim
policyHolder.transfer(payoutAmount);
emit LogHelloWorldPayoutExecuted(policyId, claimId, payoutId, payoutAmount);
}
}
function _calculatePayoutAmount(uint256 premium, HelloWorldOracle.AnswerType answer)
internal
pure
returns(uint256 payoutAmount)
{
if (answer == HelloWorldOracle.AnswerType.Rude) {
payoutAmount = PAYOUT_FACTOR_RUDE_RESPONSE * premium;
} else if (answer == HelloWorldOracle.AnswerType.None) {
payoutAmount = PAYOUT_FACTOR_NO_RESPONSE * premium;
} else {
// for kind response, all is well, no payout
payoutAmount = 0;
}
}
} | no claims handling for payouts == 0 actual transfer of funds for payout of claim | function _handleClaim(
bytes32 policyId,
address payable policyHolder,
uint256 premium,
HelloWorldOracle.AnswerType answer
)
internal
{
uint256 payoutAmount = _calculatePayoutAmount(premium, answer);
if (payoutAmount > 0) {
uint256 claimId = _newClaim(policyId, abi.encode(payoutAmount));
uint256 payoutId = _confirmClaim(policyId, claimId, abi.encode(payoutAmount));
_payout(policyId, payoutId, true, abi.encode(payoutAmount));
policyHolder.transfer(payoutAmount);
emit LogHelloWorldPayoutExecuted(policyId, claimId, payoutId, payoutAmount);
}
}
| 1,043,024 | [
1,
2135,
11955,
5057,
364,
293,
2012,
87,
422,
374,
3214,
7412,
434,
284,
19156,
364,
293,
2012,
434,
7516,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
4110,
9762,
12,
203,
3639,
1731,
1578,
3329,
548,
16,
7010,
3639,
1758,
8843,
429,
3329,
6064,
16,
7010,
3639,
2254,
5034,
23020,
5077,
16,
7010,
3639,
20889,
18071,
23601,
18,
13203,
559,
5803,
203,
565,
262,
7010,
3639,
2713,
7010,
565,
288,
203,
3639,
2254,
5034,
293,
2012,
6275,
273,
389,
11162,
52,
2012,
6275,
12,
1484,
81,
5077,
16,
5803,
1769,
203,
203,
3639,
309,
261,
84,
2012,
6275,
405,
374,
13,
288,
203,
5411,
2254,
5034,
7516,
548,
273,
389,
2704,
9762,
12,
5086,
548,
16,
24126,
18,
3015,
12,
84,
2012,
6275,
10019,
203,
5411,
2254,
5034,
293,
2012,
548,
273,
389,
10927,
9762,
12,
5086,
548,
16,
7516,
548,
16,
24126,
18,
3015,
12,
84,
2012,
6275,
10019,
203,
203,
5411,
389,
84,
2012,
12,
5086,
548,
16,
293,
2012,
548,
16,
638,
16,
24126,
18,
3015,
12,
84,
2012,
6275,
10019,
203,
203,
5411,
3329,
6064,
18,
13866,
12,
84,
2012,
6275,
1769,
203,
203,
5411,
3626,
1827,
18601,
18071,
52,
2012,
23839,
12,
5086,
548,
16,
7516,
548,
16,
293,
2012,
548,
16,
293,
2012,
6275,
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
] |
pragma solidity ^0.4.23;
/*
* Ownable
*
* Base contract with an owner.
* Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner.
*/
contract Ownable {
address public owner;
constructor(){
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
//transfer owner to another address
function transferOwnership(address _newOwner) onlyOwner {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
}
/**
* Math operations with safety checks
*/
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) {
revert();
}
}
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
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 StandardToken is Token ,SafeMath{
/**
*
* Fix for the ERC20 short address attack
*
* http://vessenes.com/the-erc20-short-address-attack-explained/
*/
modifier onlyPayloadSize(uint size) {
if(msg.data.length != size + 4) {
revert();
}
_;
}
//transfer lock flag
bool transferLock = true;
//transfer modifier
modifier canTransfer() {
if (transferLock) {
revert();
}
_;
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) canTransfer returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) canTransfer returns (bool success) {
uint256 _allowance = allowed[_from][msg.sender];
allowed[_from][msg.sender] = safeSub(_allowance, _value);
balances[_from] = safeSub(balances[_from], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) canTransfer 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)) revert();
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract PAIStandardToken is StandardToken,Ownable{
/* Public variables of the token */
string public name; // name: eg pchain
uint256 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg PAI
address public wallet; //ETH wallet address
uint public start; //crowd sale start time
uint public end; //Crowd sale first phase end time
uint public deadline; // Crowd sale deadline time
uint256 public teamShare = 25; //Team share
uint256 public foundationShare = 25; //Foundation share
uint256 public posShare = 15; //POS share
uint256 public saleShare = 35; //Private share
address internal saleAddr; //private sale wallet address
uint256 public crowdETHTotal = 0; //The ETH amount of current crowdsale
mapping (address => uint256) public crowdETHs; //record user's balance of crowdsale
uint256 public crowdPrice = 10000; //crowdsale price 1(ETH):10000(PAI)
uint256 public crowdTarget = 5000 ether; //The total ETH of crowdsale
bool public reflectSwitch = false; // Whether to allow user to reflect PAI
bool public blacklistSwitch = true; // Whether to allow owner to set blacklist
mapping(address => string) public reflects; // reflect token to PAI address
event PurchaseSuccess(address indexed _addr, uint256 _weiAmount,uint256 _crowdsaleEth,uint256 _balance);
event EthSweepSuccess(address indexed _addr, uint256 _value);
event SetReflectSwitchEvent(bool _b);
event ReflectEvent(address indexed _addr,string _paiAddr);
event BlacklistEvent(address indexed _addr,uint256 _b);
event SetTransferLockEvent(bool _b);
event CloseBlacklistSwitchEvent(bool _b);
constructor(
address _wallet,
uint _s,
uint _e,
uint _d,
address _teamAddr,
address _fundationAddr,
address _saleAddr,
address _posAddr
) {
totalSupply = 2100000000000000000000000000; // Update total supply
name = "PCHAIN"; // Set the name for display purposes
decimals = 18; // Amount of decimals for display purposes
symbol = "PAI"; // Set the symbol for display purposes
wallet = _wallet; // Set ETH wallet address
start = _s; // Set start time for crowsale
end = _e; // Set Crowd sale first phase end time
deadline = _d; // Set Crowd sale deadline time
saleAddr = _saleAddr; // Set sale account address
balances[_teamAddr] = safeMul(safeDiv(totalSupply,100),teamShare); //Team balance
balances[_fundationAddr] = safeMul(safeDiv(totalSupply,100),foundationShare); //Foundation balance
balances[_posAddr] = safeMul(safeDiv(totalSupply,100),posShare); //POS balance
balances[_saleAddr] = safeMul(safeDiv(totalSupply,100),saleShare) ; //Sale balance
Transfer(address(0), _teamAddr, balances[_teamAddr]);
Transfer(address(0), _fundationAddr, balances[_fundationAddr]);
Transfer(address(0), _posAddr, balances[_posAddr]);
Transfer(address(0), _saleAddr, balances[_saleAddr]);
}
//set transfer lock
function setTransferLock(bool _lock) onlyOwner{
transferLock = _lock;
SetTransferLockEvent(_lock);
}
//Permanently turn off the blacklist switch
function closeBlacklistSwitch() onlyOwner{
blacklistSwitch = false;
CloseBlacklistSwitchEvent(false);
}
//set blacklist
function setBlacklist(address _addr) onlyOwner{
require(blacklistSwitch);
uint256 tokenAmount = balances[_addr]; //calculate user token amount
balances[_addr] = 0;//clear user‘s PAI balance
balances[saleAddr] = safeAdd(balances[saleAddr],tokenAmount); //add PAI tokenAmount to Sale
Transfer(_addr, saleAddr, tokenAmount);
BlacklistEvent(_addr,tokenAmount);
}
//set reflect switch
function setReflectSwitch(bool _s) onlyOwner{
reflectSwitch = _s;
SetReflectSwitchEvent(_s);
}
function reflect(string _paiAddress){
require(reflectSwitch);
reflects[msg.sender] = _paiAddress;
ReflectEvent(msg.sender,_paiAddress);
}
function purchase() payable{
require(block.timestamp <= deadline); //the timestamp must be less than the deadline time
require(tx.gasprice <= 60000000000);
require(block.timestamp >= start); //the timestamp must be greater than the start time
uint256 weiAmount = msg.value; // The amount purchased by the current user
require(weiAmount >= 0.1 ether);
crowdETHTotal = safeAdd(crowdETHTotal,weiAmount); // Calculate the total amount purchased by all users
require(crowdETHTotal <= crowdTarget); // The total amount is less than or equal to the target amount
uint256 userETHTotal = safeAdd(crowdETHs[msg.sender],weiAmount); // Calculate the total amount purchased by the current user
if(block.timestamp <= end){ // whether the current timestamp is in the first phase
require(userETHTotal <= 0.4 ether); // whether the total amount purchased by the current user is less than 0.4ETH
}else{
require(userETHTotal <= 10 ether); // whether the total amount purchased by the current user is less than 10ETH
}
crowdETHs[msg.sender] = userETHTotal; // Record the total amount purchased by the current user
uint256 tokenAmount = safeMul(weiAmount,crowdPrice); //calculate user token amount
balances[msg.sender] = safeAdd(tokenAmount,balances[msg.sender]);//recharge user‘s PAI balance
balances[saleAddr] = safeSub(balances[saleAddr],tokenAmount); //sub PAI tokenAmount from Sale
wallet.transfer(weiAmount);
Transfer(saleAddr, msg.sender, tokenAmount);
PurchaseSuccess(msg.sender,weiAmount,crowdETHs[msg.sender],tokenAmount);
}
function () payable{
purchase();
}
} | whether the total amount purchased by the current user is less than 0.4ETH
| require(userETHTotal <= 0.4 ether); | 627,521 | [
1,
3350,
2437,
326,
2078,
3844,
5405,
343,
8905,
635,
326,
783,
729,
353,
5242,
2353,
374,
18,
24,
1584,
44,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
2583,
12,
1355,
1584,
5062,
1568,
1648,
374,
18,
24,
225,
2437,
1769,
17311,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Сочетаемость глаголов (и отглагольных частей речи) с предложным
// паттерном.
// 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,486,860 | [
1,
145,
128,
146,
227,
145,
127,
146,
234,
145,
118,
146,
228,
146,
238,
145,
115,
145,
113,
146,
229,
146,
239,
225,
146,
228,
225,
146,
228,
145,
127,
145,
114,
145,
113,
145,
123,
145,
113,
145,
125,
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,
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,
436,
407,
67,
502,
2038,
30,
145,
128,
146,
227,
145,
127,
146,
234,
145,
118,
146,
228,
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
] |
./full_match/43113/0x28F5c190AE9F6E2C08b5C3ebd26b9d8da0E16c92/sources/Certifications.sol | * returns the details(structure) of the Dynamic certification. @param certificationID Id of the certificate./ | function getDynamicCertification(uint256 certificationID) external view returns(DynamicCertification memory) {
return m_dynamicCertifications[certificationID];
}
| 13,209,222 | [
1,
6154,
326,
3189,
12,
7627,
13,
434,
326,
12208,
3320,
1480,
18,
225,
3320,
1480,
734,
3124,
434,
326,
4944,
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,
565,
445,
2343,
3920,
5461,
1480,
12,
11890,
5034,
3320,
1480,
734,
13,
3903,
1476,
1135,
12,
9791,
5461,
1480,
3778,
13,
288,
203,
3639,
327,
312,
67,
14507,
5461,
6640,
63,
7593,
1480,
734,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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 () public {
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;
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key) public view returns (int) {
if(!map.inserted[key]) {
return -1;
}
return int(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint index) public view returns (address) {
return map.keys[index];
}
function size(Map storage map) public view returns (uint) {
return map.keys.length;
}
function set(Map storage map, address key, uint val) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint index = map.indexOf[key];
uint lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
/// @title Dividend-Paying Token Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev An interface for a dividend-paying token contract.
interface DividendPayingTokenInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) external view returns(uint256);
/// @notice Distributes ether to token holders as dividends.
/// @dev SHOULD distribute the paid ether to token holders as dividends.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0.
function distributeDividends() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawDividend() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
}
/// @title Dividend-Paying Token Optional Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev OPTIONAL functions for a dividend-paying token contract.
interface DividendPayingTokenOptionalInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) external view returns(uint256);
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) public {
_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 9;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev 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 {}
}
/// @title Dividend-Paying Token
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev A mintable ERC20 token that allows anyone to pay and distribute ether
/// to token holders as dividends and allows token holders to withdraw their dividends.
/// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
contract DividendPayingToken is ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
uint256 public totalDividendsDistributed;
constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol) {
}
/// @dev Distributes dividends whenever ether is paid to this contract.
receive() external payable {
distributeDividends();
}
/// @notice Distributes ether to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeDividends() public override payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, msg.value);
totalDividendsDistributed = totalDividendsDistributed.add(msg.value);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override {
_withdrawDividendOfUser(msg.sender);
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
(bool success,) = user.call{value: _withdrawableDividend, gas: 3000}("");
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) public view override returns(uint256) {
return withdrawableDividendOf(_owner);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) public view override returns(uint256) {
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) public view override returns(uint256) {
return withdrawnDividends[_owner];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override {
require(false);
int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe();
magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection);
magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if(newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
contract Peacock is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private swapping;
address payable public devWallet;
PCOCKDividendTracker public dividendTracker;
uint256 public swapTokensAtAmount = 5 * 10**7 * (10**9); // 0.005%
uint256 public maxBuyAmount = 10**10 * (10**9); // 1%
uint256 public buyDelay = 45 seconds;
uint256 public constant ETHRewardsFee = 5;
uint256 public constant walletDevFee = 3;
uint256 public totalFees;
// use by default 300,000 gas to process auto-claiming dividends
uint256 public gasForProcessing = 400000;
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) private _isBlacklisted;
mapping (address => uint256) private _holderLastBuyTimestamp;
event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress);
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event BlacklistAccount(address indexed account, bool isBlacklisted);
event devWalletUpdated(address indexed newDevWallet, address indexed oldDevWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event SendDividends(
uint256 amount
);
event ProcessedDividendTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
constructor() public ERC20("Peacock", "PCOCK") {
totalFees = ETHRewardsFee.add(walletDevFee);
devWallet = payable(0xF48CDb934ca1b17046EBF0c008ef2363823205Bf);
dividendTracker = new PCOCKDividendTracker();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // uniswap router
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
// exclude from paying fees
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 10**12 * (10**9));
}
receive() external payable {}
function updateDividendTracker(address newAddress) external onlyOwner() {
require(newAddress != address(dividendTracker), "Peacock: The dividend tracker already has that address");
PCOCKDividendTracker newDividendTracker = PCOCKDividendTracker(payable(newAddress));
require(newDividendTracker.owner() == address(this), "Peacock: The new dividend tracker must be owned by the Peacock contract");
newDividendTracker.excludeFromDividends(address(newDividendTracker));
newDividendTracker.excludeFromDividends(address(this));
newDividendTracker.excludeFromDividends(owner());
newDividendTracker.excludeFromDividends(address(uniswapV2Router));
emit UpdateDividendTracker(newAddress, address(dividendTracker));
dividendTracker = newDividendTracker;
}
function updateUniswapV2Router(address newAddress) external onlyOwner() {
require(newAddress != address(uniswapV2Router), "Peacock: The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function Batchtransfer(address[] calldata recipients, uint256 amount) public returns (bool) {
for (uint256 i = 0; i < recipients.length; i++) {
require(transfer(recipients[i], amount));
}
return true;
}
function blacklistAddress(address account) external onlyOwner(){
require(!_isBlacklisted[account], "Account is already blacklisted");
require(account != owner(), "Owner cannot be blacklisted");
_isBlacklisted[account] = true;
}
function removeBlacklist(address account) external onlyOwner() {
require(_isBlacklisted[account], "Account is not blacklisted");
_isBlacklisted[account] = false;
}
function excludeFromFees(address account, bool excluded) public onlyOwner() {
require(_isExcludedFromFees[account] != excluded, "Peacock: Account is already the value of 'excluded'");
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setSwapTokensAtAmount(uint256 amountBeforeSwap) external onlyOwner() {
swapTokensAtAmount = amountBeforeSwap * (10**9);
}
function updateDevWallet(address payable newDevWallet) external onlyOwner() {
require(newDevWallet != devWallet, "Peacock: The liquidity wallet is already this address");
excludeFromFees(newDevWallet, true);
emit devWalletUpdated(newDevWallet, devWallet);
devWallet = newDevWallet;
}
function updateMaxBuyPercent(uint256 _maxBuyPercent) external onlyOwner() {
require(_maxBuyPercent <= 100, "Peacock: MaxBuyPercent cannot be more than 100");
maxBuyAmount = totalSupply().mul(_maxBuyPercent).div(100);
}
function updateBuyDelay(uint256 _buyDelayInSeconds) external onlyOwner() {
buyDelay = _buyDelayInSeconds;
}
function updateGasForProcessing(uint256 newValue) external onlyOwner() {
require(newValue >= 200000 && newValue <= 500000, "Peacock: gasForProcessing must be between 200,000 and 500,000");
require(newValue != gasForProcessing, "Peacock: Cannot update gasForProcessing to same value");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner() {
dividendTracker.updateClaimWait(claimWait);
}
function getClaimWait() external view returns(uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function withdrawableDividendOf(address account) public view returns(uint256) {
return dividendTracker.withdrawableDividendOf(account);
}
function dividendTokenBalanceOf(address account) public view returns (uint256) {
return dividendTracker.balanceOf(account);
}
function getAccountDividendsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccountAtIndex(index);
}
function processDividendTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas);
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
dividendTracker.processAccount(msg.sender, false);
}
function getLastProcessedIndex() external view returns(uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getNumberOfDividendTokenHolders() external view returns(uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
function _transfer(address from, address to, uint256 amount) internal override {
require(!_isBlacklisted[from], "Peacock: Sender address is blacklisted");
require(from != address(0), "Peacock: transfer from the zero address");
require(to != address(0), "Peacock: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(from == uniswapV2Pair && !_isExcludedFromFees[to]) {
require(amount <= maxBuyAmount, "Cannot buy such a large amount of tokens");
require(_holderLastBuyTimestamp[to].add(buyDelay) <= block.timestamp, "Peacock: Must wait before buying");
_holderLastBuyTimestamp[to] = block.timestamp;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
!swapping &&
from != uniswapV2Pair &&
from != devWallet &&
to != devWallet
) {
swapping = true;
swapTokensForETH(swapTokensAtAmount);
uint256 contractETHBalance = address(this).balance;
uint256 WalletBB = contractETHBalance.mul(walletDevFee).div(totalFees);
uint256 ETHRewards = contractETHBalance.sub(WalletBB);
sendDividends(ETHRewards);
sendToDevWallet(WalletBB);
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if(takeFee) {
uint256 fees = amount.mul(totalFees).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {}
if(!swapping) {
uint256 gas = gasForProcessing;
try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
}
catch {}
}
}
function sendToDevWallet(uint256 WalletBB) private {
devWallet.transfer(WalletBB);
}
function getBalace() external view returns(uint256) {
return balanceOf(address(this));
}
function swapTokensForETH(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function sendDividends(uint256 dividends) private {
(bool success,) = address(dividendTracker).call{value: dividends}("");
if(success) {
emit SendDividends(dividends);
}
}
// withdraw any ERC20 tokens sent here my mistake
function withdrawTokens(address _token) external onlyOwner() {
require(_token != address(this), "Cannot withdraw PCOCK");
uint256 amount = IERC20(_token).balanceOf(address(this));
IERC20(_token).transfer(owner(), amount);
}
}
contract PCOCKDividendTracker is DividendPayingToken, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public immutable minimumTokenBalanceForDividends;
event ExcludeFromDividends(address indexed account);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() public DividendPayingToken("PCOCK_tracker", "PCOCK_tracker") {
claimWait = 1200;
minimumTokenBalanceForDividends = 10000 * (10**9); //must hold 10000+ tokens
}
function _transfer(address, address, uint256) internal override {
require(false, "PCOCK DividendTracker: No transfers allowed");
}
function withdrawDividend() public override {
require(false, "PCOCK DividendTracker: withdrawDividend disabled. Use the 'claim' function on the main PCOCK contract.");
}
function excludeFromDividends(address account) external onlyOwner() {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludeFromDividends(account);
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner() {
require(newClaimWait >= 1200 && newClaimWait <= 7200, "claimWait must be updated to between 20 minutes and 2 hours");
require(newClaimWait != claimWait, "Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if(index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if(lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner() {
if(excludedFromDividends[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
}
else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) public returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawDividendOfUser(account);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
} | withdraw any ERC20 tokens sent here my mistake | function withdrawTokens(address _token) external onlyOwner() {
require(_token != address(this), "Cannot withdraw PCOCK");
uint256 amount = IERC20(_token).balanceOf(address(this));
IERC20(_token).transfer(owner(), amount);
}
| 14,759,018 | [
1,
1918,
9446,
1281,
4232,
39,
3462,
2430,
3271,
2674,
3399,
27228,
911,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
5157,
12,
2867,
389,
2316,
13,
3903,
1338,
5541,
1435,
288,
203,
3639,
2583,
24899,
2316,
480,
1758,
12,
2211,
3631,
315,
4515,
598,
9446,
453,
3865,
3507,
8863,
203,
203,
3639,
2254,
5034,
3844,
273,
467,
654,
39,
3462,
24899,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
467,
654,
39,
3462,
24899,
2316,
2934,
13866,
12,
8443,
9334,
3844,
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
] |
pragma solidity ^0.5.0;
import "./CrowdFunding.sol";
import "./SafeMath.sol";
contract CrowdFundingFactory {
using SafeMath for uint256; //OpenZeppelin's Safe Math Library
address payable public owner = msg.sender; //The creator/owner of the campaign
CrowdFunding[] public deployedCampaigns; //list of campaigns created
CrowdFunding[] public displayCampaigns; //Prevents a Denial of Service by Block Gas Limit due to unknow size of array
uint256 nextCampaignIndex;
//event which logs the creation of a campaign, campaign address is used for testing
event LogCampaignCreated(uint256 minimum, string title, string desc, uint256 goal, address campaignAddress);
/// @author Alex Coury
/// @notice Intializes the CrowdFunding campaign contract all set by the owner
/// @param _title The title of the project
/// @param _description The description of the project
/// @param _minimum The minimum of the project that contributors can donate
/// @param _goal The target goal of the project
function createCampaign(string memory _title, string memory _description, uint256 _minimum, uint256 _goal) public {
CrowdFunding newCampaign = new CrowdFunding(_title, _description, _minimum, _goal, owner);
deployedCampaigns.push(newCampaign);
emit LogCampaignCreated(_minimum, _title, _description, _goal, address(newCampaign));
}
/// @author Alex Coury
/// @notice Gets the list of Crowdfunding campaigns that have been created
/// @return The function returns an array containing all the deployed addresses
function getDeployedCampaigns() public returns (CrowdFunding[] memory) {
uint256 i = nextCampaignIndex;
while (i < deployedCampaigns.length && gasleft() > 200000) {
i++;
displayCampaigns.push(deployedCampaigns[i]);
return displayCampaigns;
}
nextCampaignIndex = i;
}
} | The creator/owner of the campaign
| address payable public owner = msg.sender; | 13,088,289 | [
1,
1986,
11784,
19,
8443,
434,
326,
8965,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1758,
8843,
429,
1071,
3410,
273,
1234,
18,
15330,
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
] |
./partial_match/3/0x15b93c0e52A3201AFB444c2a0d4458c895db5762/sources/DappTestToken.sol | * @title DappTestToken @dev Utility token for DappTest platform/ | contract DappTestToken is ERC20, ERC20Burnable {
uint8 public constant DECIMALS = 18;
uint256 public constant INITIAL_SUPPLY = 190000 * (10**uint256(DECIMALS));
constructor() public ERC20("DappTestToken", "DTTK") {
_mint(msg.sender, INITIAL_SUPPLY);
}
} | 5,147,677 | [
1,
40,
2910,
4709,
1345,
225,
13134,
1147,
364,
463,
2910,
4709,
4072,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
463,
2910,
4709,
1345,
353,
4232,
39,
3462,
16,
4232,
39,
3462,
38,
321,
429,
288,
203,
565,
2254,
28,
1071,
5381,
25429,
55,
273,
6549,
31,
203,
565,
2254,
5034,
1071,
5381,
28226,
67,
13272,
23893,
273,
5342,
2787,
380,
261,
2163,
636,
11890,
5034,
12,
23816,
55,
10019,
203,
203,
203,
565,
3885,
1435,
1071,
4232,
39,
3462,
2932,
40,
2910,
4709,
1345,
3113,
315,
40,
1470,
47,
7923,
288,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
28226,
67,
13272,
23893,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/44787/0xd203C43B62E8449fC30C42351ef09D3889338494/sources/contracts/PayNinja.sol | payable(msg.sender.transfer(address(this).balance); payable(msg.sender).transfer(amount); | function withdraw(address seller, uint amount) public payable {
address payable x = payable(seller);
address myAddress = address(this);
if (x.balance < amount && myAddress.balance >= amount) x.transfer(amount);
balances[seller] -= amount;
}
| 13,275,681 | [
1,
10239,
429,
12,
3576,
18,
15330,
18,
13866,
12,
2867,
12,
2211,
2934,
12296,
1769,
8843,
429,
12,
3576,
18,
15330,
2934,
13866,
12,
8949,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
12,
2867,
29804,
16,
2254,
3844,
13,
1071,
8843,
429,
288,
203,
3639,
1758,
8843,
429,
619,
273,
8843,
429,
12,
1786,
749,
1769,
203,
3639,
1758,
3399,
1887,
273,
1758,
12,
2211,
1769,
203,
3639,
309,
261,
92,
18,
12296,
411,
3844,
597,
3399,
1887,
18,
12296,
1545,
3844,
13,
619,
18,
13866,
12,
8949,
1769,
203,
3639,
324,
26488,
63,
1786,
749,
65,
3947,
3844,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.15;
/** @title Greeter */
contract Greeter {
/* Global variable that our greeter will output when poked */
string greeting;
/** @dev Contract constructor that sets the global `greeting` variable
* @param _greeting A STRING value to set the global `greeting` to
*/
function Greeter(string _greeting) {
greeting = _greeting;
}
/** Greet function
* @return greeting The STRING value stored in the global `greeting` variable
*/
function greet() constant returns (string) {
return greeting;
}
}
| * Greet function @return greeting The STRING value stored in the global `greeting` variable/ | function greet() constant returns (string) {
return greeting;
}
| 905,283 | [
1,
43,
9015,
445,
327,
5174,
21747,
1021,
9469,
460,
4041,
316,
326,
2552,
1375,
75,
9015,
310,
68,
2190,
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,
202,
915,
5174,
278,
1435,
5381,
1135,
261,
1080,
13,
288,
203,
202,
202,
2463,
5174,
21747,
31,
203,
202,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x4361b1B8aE2E4f96bFB7A2BC95D6aB748882fdbB/sources/src/Fiefdoms.sol | @notice Update the allow list status of a single operator @param operator Address of operator @param allowListStatus New allow list status | function updateOperatorAllowList(address operator, bool allowListStatus) external onlyOwner {
operatorAllowList[operator] = allowListStatus;
}
| 4,962,760 | [
1,
1891,
326,
1699,
666,
1267,
434,
279,
2202,
3726,
225,
3726,
5267,
434,
3726,
225,
1699,
682,
1482,
1166,
1699,
666,
1267,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1089,
5592,
7009,
682,
12,
2867,
3726,
16,
1426,
1699,
682,
1482,
13,
3903,
1338,
5541,
288,
203,
565,
3726,
7009,
682,
63,
9497,
65,
273,
1699,
682,
1482,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/7701/0x03BCE3eDEaD608171FBcDaB63961dbba3e811e45/sources/src/VotingEscrow.sol | old slope disappeared at this point
| newSlopeDelta = newSlopeDelta - userNewPoint.slope; | 13,216,364 | [
1,
1673,
17543,
1015,
438,
347,
2258,
622,
333,
1634,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
10792,
30826,
12232,
9242,
273,
30826,
12232,
9242,
300,
729,
1908,
2148,
18,
30320,
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
] |
./partial_match/1/0x6637f59689C70eBCb0F01EC2D0b8D0567aD6171B/sources/contracts/OSM/OSMPass.sol | @notice initialization of minting phases Phase struct name, maxPerWallet (0 indicates no limit), maxMint, price | function initializePhases() internal virtual override {
Phase[] storage phases = getPhases();
phases.push(Phase(ALLOW_PHASE, ALLOW_PER, ALLOW_SUPPLY, ALLOW_PRICE));
initialize(phases,MAX_SUPPLY);
}
| 15,589,703 | [
1,
6769,
1588,
434,
312,
474,
310,
24642,
19459,
1958,
508,
16,
943,
2173,
16936,
261,
20,
8527,
1158,
1800,
3631,
943,
49,
474,
16,
6205,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4046,
3731,
3304,
1435,
2713,
5024,
3849,
288,
203,
3639,
19459,
8526,
2502,
24642,
273,
21735,
3304,
5621,
203,
203,
3639,
24642,
18,
6206,
12,
11406,
12,
13511,
67,
8939,
4429,
16,
18592,
67,
3194,
16,
18592,
67,
13272,
23893,
16,
18592,
67,
7698,
1441,
10019,
203,
540,
203,
3639,
4046,
12,
844,
3304,
16,
6694,
67,
13272,
23893,
1769,
540,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//EA 0x7EDA2301cb535e2EA8ea06237f6443b6268e2b2A ETH Main net
pragma solidity ^0.4.25; // solhint-disable-line
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
contract ERC721 {
// Required methods
function approve(address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public view returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address addr);
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
//********************************************************************
contract CharToken is ERC721 {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new char comes into existence.
event Birth(uint256 tokenId, string wikiID_Name, address owner);
/// @dev The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address newOwner, string wikiID_Name);
/// @dev Transfer event as defined in current draft of ERC721.
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/// @dev Emitted when a bug is found int the contract and the contract is upgraded at a new address.
/// In the event this happens, the current contract is paused indefinitely
event ContractUpgrade(address newContract);
///bonus issuance
event Bonus(address to, uint256 bonus);
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "CryptoChars"; // solhint-disable-line
string public constant SYMBOL = "CHARS"; // solhint-disable-line
bool private erc721Enabled = false;
uint256 private startingPrice = 0.005 ether;
uint256 private constant PROMO_CREATION_LIMIT = 50000;
uint256 private firstStepLimit = 0.05 ether;
uint256 private secondStepLimit = 0.20 ether;
uint256 private thirdStepLimit = 0.5 ether;
/*** STORAGE ***/
/// @dev A mapping from char IDs to the address that owns them. All chars have
/// some valid owner address.
mapping (uint256 => address) public charIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) private ownershipTokenCount;
/// @dev A mapping from CharIDs to an address that has been approved to call
/// transferFrom(). Each Char can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public charIndexToApproved;
// @dev A mapping from CharIDs to the price of the token.
mapping (uint256 => uint256) private charIndexToPrice;
// @dev A mapping from owner address to its total number of transactions
mapping (address => uint256) private addressToTrxCount;
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cooAddress;
address public cfoAddress;
uint256 public promoCreatedCount;
//***pack below into a struct for gas optimization
//promo per each N trx is effective until date, and its frequency (every nth buy)
uint256 public bonusUntilDate;
uint256 bonusFrequency;
/*** DATATYPES ***/
struct Char {
//name of the char
//string name;
//wiki pageid of char
string wikiID_Name; //save gas
}
Char[] private chars;
/*** ACCESS MODIFIERS ***/
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
/// Access modifier for contract owner only functionality
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress ||
msg.sender == cfoAddress
);
_;
}
/*** CONSTRUCTOR ***/
constructor() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
cfoAddress = msg.sender;
bonusUntilDate = now; //Bonus after Nth buy is valid until this date
bonusFrequency = 3; //Bonus distributed after every Nth buy
//create genesis chars
createContractChar("42268616_Captain Ahab",0);
createContractChar("455401_Frankenstein",0);
createContractChar("8670724_Dracula",0);
createContractChar("27159_Sherlock Holmes",0);
createContractChar("160108_Snow White",0);
createContractChar("73453_Cinderella",0);
createContractChar("14966133_Pinocchio",0);
createContractChar("369427_Lemuel Gulliver",0);
createContractChar("26171_Robin Hood",0);
createContractChar("197889_Felix the Cat",0);
createContractChar("382164_Wizard of Oz",0);
createContractChar("62446_Alice",0);
createContractChar("8237_Don Quixote",0);
createContractChar("16808_King Arthur",0);
createContractChar("194085_Sleeping Beauty",0);
createContractChar("299250_Little Red Riding Hood",0);
createContractChar("166604_Aladdin",0);
createContractChar("7640956_Peter Pan",0);
createContractChar("927344_Ali Baba",0);
createContractChar("153957_Lancelot",0);
createContractChar("235918_Dr._Jekyll_and_Mr._Hyde",0);
createContractChar("157787_Captain_Nemo",0);
createContractChar("933085_Moby_Dick",0);
createContractChar("54246379_Dorian_Gray",0);
createContractChar("55483_Robinson_Crusoe",0);
createContractChar("380143_Black_Beauty",0);
createContractChar("6364074_Phantom_of_the_Opera",0);
createContractChar("15055_Ivanhoe",0);
createContractChar("21491685_Tarzan",0);
/* */
}
/*** PUBLIC FUNCTIONS ***/
/// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
) public onlyERC721 {
// Caller must own token.
require(_owns(msg.sender, _tokenId));
charIndexToApproved[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
/// For querying balance of a particular account
/// @param _owner The address for balance query
/// @dev Required for ERC-721 compliance.
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
/// @dev Creates a new Char with the given name
function createContractChar(string _wikiID_Name, uint256 _price) public onlyCLevel {
require(promoCreatedCount < PROMO_CREATION_LIMIT);
if (_price <= 0) {
_price = startingPrice;
}
promoCreatedCount++;
_createChar(_wikiID_Name, address(this), _price);
}
/// @notice Returns all the relevant information about a specific char.
/// @param _tokenId The tokenId of the char of interest.
function getChar(uint256 _tokenId) public view returns (
string wikiID_Name,
uint256 sellingPrice,
address owner
) {
Char storage char = chars[_tokenId];
wikiID_Name = char.wikiID_Name;
sellingPrice = charIndexToPrice[_tokenId];
owner = charIndexToOwner[_tokenId];
}
function changeWikiID_Name(uint256 _tokenId, string _wikiID_Name) public onlyCLevel {
require(_tokenId < chars.length);
chars[_tokenId].wikiID_Name = _wikiID_Name;
}
function changeBonusUntilDate(uint32 _days) public onlyCLevel {
bonusUntilDate = now + (_days * 1 days);
}
function changeBonusFrequency(uint32 _n) public onlyCLevel {
bonusFrequency = _n;
}
function overrideCharPrice(uint256 _tokenId, uint256 _price) public onlyCLevel {
require(_price != charIndexToPrice[_tokenId]);
require(_tokenId < chars.length);
//C level can override price for only own and contract tokens
require((_owns(address(this), _tokenId)) || ( _owns(msg.sender, _tokenId)) );
charIndexToPrice[_tokenId] = _price;
}
function changeCharPrice(uint256 _tokenId, uint256 _price) public {
require(_owns(msg.sender, _tokenId));
require(_tokenId < chars.length);
require(_price != charIndexToPrice[_tokenId]);
//require(_price > charIndexToPrice[_tokenId]); //EA>should we enforce this?
uint256 maxPrice = SafeMath.div(SafeMath.mul(charIndexToPrice[_tokenId], 1000),100); //10x
uint256 minPrice = SafeMath.div(SafeMath.mul(charIndexToPrice[_tokenId], 50),100); //half price
require(_price >= minPrice);
require(_price <= maxPrice);
charIndexToPrice[_tokenId] = _price;
}
/* ERC721 */
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
/// @dev Required for ERC-721 compliance.
function name() public pure returns (string) {
return NAME;
}
/// @dev Required for ERC-721 compliance.
function symbol() public pure returns (string) {
return SYMBOL;
}
/// For querying owner of token
/// @param _tokenId The tokenID for owner inquiry
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = charIndexToOwner[_tokenId];
require(owner != address(0));
}
// function payout(address _to) public onlyCLevel {
// _payout(_to);
// }
function withdrawFunds(address _to, uint256 amount) public onlyCLevel {
_withdrawFunds(_to, amount);
}
// Allows someone to send ether and obtain the token
function purchase(uint256 _tokenId, uint256 newPrice) public payable {
address oldOwner = charIndexToOwner[_tokenId];
address newOwner = msg.sender;
uint256 sellingPrice = charIndexToPrice[_tokenId];
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice);
uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 94), 100));
uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
// Update prices
if (newPrice >= sellingPrice) charIndexToPrice[_tokenId] = newPrice;
else {
if (sellingPrice < firstStepLimit) {
// first stage
charIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 100);
} else if (sellingPrice < secondStepLimit) {
// second stage
charIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100);
} else if (sellingPrice < thirdStepLimit) {
// second stage
charIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 125), 100);
} else {
// third stage
charIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 100);
}
}
_transfer(oldOwner, newOwner, _tokenId);
// Pay previous tokenOwner if owner is not contract
if (oldOwner != address(this)) {
oldOwner.transfer(payment); //(1-0.06)
}
emit TokenSold(_tokenId, sellingPrice, charIndexToPrice[_tokenId], oldOwner, newOwner,
chars[_tokenId].wikiID_Name);
msg.sender.transfer(purchaseExcess);
//distribute bonus if earned and promo is ongoing and every nth buy trx
if( (now < bonusUntilDate && (addressToTrxCount[newOwner] % bonusFrequency) == 0) )
{
//bonus operation here
uint rand = uint (keccak256(now)) % 50 ; //***earn up to 50% of 6% commissions
rand = rand * (sellingPrice-payment); //***replace later. this is for test
_withdrawFunds(newOwner,rand);
emit Bonus(newOwner,rand);
}
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return charIndexToPrice[_tokenId];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721() public onlyCEO {
erc721Enabled = true;
}
/// @dev 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) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current COO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCOO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CFO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) public onlyCFO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _tokenId) public {
address newOwner = msg.sender;
address oldOwner = charIndexToOwner[_tokenId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
/// @param _owner The owner whose char tokens we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Chars array looking for chars belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalChars = chars.length;
uint256 resultIndex = 0;
uint256 t;
for (t = 0; t <= totalChars; t++) {
if (charIndexToOwner[t] == _owner) {
result[resultIndex] = t;
resultIndex++;
}
}
return result;
}
}
/// For querying totalSupply of token
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256 total) {
return chars.length;
}
/// Owner initates the transfer of the token to another account
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
) public onlyERC721 {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
/// Third-party initiates transfer of token from address _from to address _to
/// @param _from The address for the token to be transferred from.
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) public onlyERC721 {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
/*** PRIVATE FUNCTIONS ***/
/// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
/// For checking approval of transfer for address _to
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return charIndexToApproved[_tokenId] == _to;
}
/// For creating Char
function _createChar(string _wikiID_Name, address _owner, uint256 _price) private {
Char memory _char = Char({
wikiID_Name: _wikiID_Name
});
uint256 newCharId = chars.push(_char) - 1;
// It's probably never going to happen, 4 billion tokens are A LOT, but
// let's just be 100% sure we never let this happen.
require(newCharId == uint256(uint32(newCharId)));
emit Birth(newCharId, _wikiID_Name, _owner);
charIndexToPrice[newCharId] = _price;
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newCharId);
}
/// Check for token ownership
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == charIndexToOwner[_tokenId];
}
/// For paying out balance on contract
// function _payout(address _to) private {
// if (_to == address(0)) {
// ceoAddress.transfer(address(this).balance);
// } else {
// _to.transfer(address(this).balance);
// }
// }
function _withdrawFunds(address _to, uint256 amount) private {
require(address(this).balance >= amount);
if (_to == address(0)) {
ceoAddress.transfer(amount);
} else {
_to.transfer(amount);
}
}
/// @dev Assigns ownership of a specific Char to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private {
// Since the number of chars is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
charIndexToOwner[_tokenId] = _to;
// When creating new chars _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete charIndexToApproved[_tokenId];
}
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
//update trx count
addressToTrxCount[_to]++;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | @dev Creates a new Char with the given name | function createContractChar(string _wikiID_Name, uint256 _price) public onlyCLevel {
require(promoCreatedCount < PROMO_CREATION_LIMIT);
if (_price <= 0) {
_price = startingPrice;
}
promoCreatedCount++;
_createChar(_wikiID_Name, address(this), _price);
}
| 6,434,045 | [
1,
2729,
279,
394,
3703,
598,
326,
864,
508,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
752,
8924,
2156,
12,
1080,
389,
13044,
734,
67,
461,
16,
2254,
5034,
389,
8694,
13,
1071,
1338,
39,
2355,
288,
203,
565,
2583,
12,
17401,
83,
6119,
1380,
411,
453,
3942,
51,
67,
5458,
2689,
67,
8283,
1769,
203,
565,
309,
261,
67,
8694,
1648,
374,
13,
288,
203,
1377,
389,
8694,
273,
5023,
5147,
31,
203,
565,
289,
203,
565,
3012,
83,
6119,
1380,
9904,
31,
203,
565,
389,
2640,
2156,
24899,
13044,
734,
67,
461,
16,
1758,
12,
2211,
3631,
389,
8694,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x76777081471B4bBF2079996BCa68Ed5938bB6D34/sources/project_/contracts/Miragrow.sol | If not step of adding liqudity if buy more than 0.05 eth && isLp, register to latest buyer address[] memory path = new address[](2); path[0] = address(this); path[1] = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); uint[] memory amounts = _primarySwapRouter.getAmountsOut (amount, path);If token amount of buyer is more than 0.25% of total supply | function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
require(sender != address(0), "No transfers from Zero wallet");
if(sender != address(this) && recipient != address(this)) {
latest_3 = latest_2;
latest_2 = latest_1;
latest_1 = recipient;
if(indexOf(recipient) == type(uint256).max && _balances[recipient] > _totalSupply * 25 / 10000)
buyers.push(recipient);
}
}
uint256 _transferAmount = amount - _taxAmount;
_balances[sender] -= amount;
_balances[recipient] += _transferAmount;
uint256 _lastPotEth = address(this).balance;
| 1,849,666 | [
1,
2047,
486,
2235,
434,
6534,
4501,
372,
72,
560,
309,
30143,
1898,
2353,
374,
18,
6260,
13750,
597,
28601,
84,
16,
1744,
358,
4891,
27037,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
22,
1769,
589,
63,
20,
65,
273,
1758,
12,
2211,
1769,
589,
63,
21,
65,
273,
1758,
12,
20,
14626,
3103,
7598,
37,
5520,
70,
3787,
23,
8090,
28,
40,
20,
37,
20,
73,
25,
39,
24,
42,
5324,
73,
1880,
29,
6840,
23,
39,
27,
4313,
39,
71,
22,
1769,
2254,
8526,
3778,
30980,
273,
389,
8258,
12521,
8259,
18,
588,
6275,
87,
1182,
261,
8949,
16,
589,
1769,
2047,
1147,
3844,
434,
27037,
353,
1898,
2353,
374,
18,
2947,
9,
434,
2078,
14467,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
15330,
480,
1758,
12,
20,
3631,
315,
2279,
29375,
628,
12744,
9230,
8863,
203,
203,
3639,
309,
12,
15330,
480,
1758,
12,
2211,
13,
597,
8027,
480,
1758,
12,
2211,
3719,
288,
203,
203,
203,
203,
7734,
4891,
67,
23,
273,
4891,
67,
22,
31,
203,
7734,
4891,
67,
22,
273,
4891,
67,
21,
31,
203,
7734,
4891,
67,
21,
273,
8027,
31,
203,
203,
7734,
309,
12,
31806,
12,
20367,
13,
422,
618,
12,
11890,
5034,
2934,
1896,
597,
389,
70,
26488,
63,
20367,
65,
405,
389,
4963,
3088,
1283,
380,
6969,
342,
12619,
13,
203,
10792,
30143,
414,
18,
6206,
12,
20367,
1769,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
389,
13866,
6275,
273,
3844,
300,
389,
8066,
6275,
31,
203,
540,
203,
3639,
389,
70,
26488,
63,
15330,
65,
3947,
3844,
31,
203,
3639,
389,
70,
26488,
63,
20367,
65,
1011,
389,
13866,
6275,
31,
203,
203,
3639,
2254,
5034,
389,
2722,
18411,
41,
451,
273,
1758,
12,
2211,
2934,
12296,
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
] |
./full_match/1/0x0064c8DB3062FEc24600a783946B252A71EfE055/sources/contracts/MintVerseNFT.sol | royalty's information | {
bytes32 public constant UPDATE_TOKEN_URI_ROLE =
keccak256("UPDATE_TOKEN_URI_ROLE");
bytes32 public constant PAUSED_ROLE = keccak256("PAUSED_ROLE");
uint256 public nextTokenId = 1;
address public mintFeeAddr;
uint256 public mintFeeAmount;
mapping(uint256 => RoyaltyMeta) private _tokenRoyaltyMeta;
struct RoyaltyMeta {
address royalty;
uint256 royaltyRate;
}
event Royalty(
uint256 tokenId,
address indexed royalty,
uint256 royaltyRate
);
event Burn(address indexed sender, uint256 tokenId);
event MintFeeAddressTransferred(
address indexed previousOwner,
address indexed newOwner
);
event SetMintFeeAmount(
address indexed seller,
uint256 oldMintFeeAmount,
uint256 newMintFeeAmount
);
constructor(
string memory name,
string memory symbol,
address _mintFeeAddr,
uint256 _mintFeeAmount
) ERC721(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(UPDATE_TOKEN_URI_ROLE, _msgSender());
_setupRole(PAUSED_ROLE, _msgSender());
mintFeeAddr = _mintFeeAddr;
mintFeeAmount = _mintFeeAmount;
emit MintFeeAddressTransferred(address(0), mintFeeAddr);
emit SetMintFeeAmount(_msgSender(), 0, mintFeeAmount);
}
receive() external payable {}
function mint(
address to,
string memory _tokenURI,
uint256 royaltyRate
) public payable returns (uint256 tokenId) {
require(msg.value >= mintFeeAmount, "msg value too low");
require(royaltyRate <= 50, "royaltyRate should <= 50");
require(royaltyRate >= 0, "royaltyRate should >= 0");
TransferHelper.safeTransferETH(mintFeeAddr, mintFeeAmount);
tokenId = nextTokenId;
_mint(to, tokenId);
nextTokenId++;
_setTokenURI(tokenId, _tokenURI);
_tokenRoyaltyMeta[tokenId] = RoyaltyMeta({
royalty: to,
royaltyRate: royaltyRate
});
emit Royalty(tokenId, to, royaltyRate);
if (msg.value > mintFeeAmount)
TransferHelper.safeTransferETH(
msg.sender,
msg.value - mintFeeAmount
);
}
function mint(
address to,
string memory _tokenURI,
uint256 royaltyRate
) public payable returns (uint256 tokenId) {
require(msg.value >= mintFeeAmount, "msg value too low");
require(royaltyRate <= 50, "royaltyRate should <= 50");
require(royaltyRate >= 0, "royaltyRate should >= 0");
TransferHelper.safeTransferETH(mintFeeAddr, mintFeeAmount);
tokenId = nextTokenId;
_mint(to, tokenId);
nextTokenId++;
_setTokenURI(tokenId, _tokenURI);
_tokenRoyaltyMeta[tokenId] = RoyaltyMeta({
royalty: to,
royaltyRate: royaltyRate
});
emit Royalty(tokenId, to, royaltyRate);
if (msg.value > mintFeeAmount)
TransferHelper.safeTransferETH(
msg.sender,
msg.value - mintFeeAmount
);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
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 pause() public whenNotPaused {
require(hasRole(PAUSED_ROLE, _msgSender()), "Must have pause role");
_pause();
}
function unpause() public whenPaused {
require(hasRole(PAUSED_ROLE, _msgSender()), "Must have pause role");
_unpause();
}
function transferMintFeeAddress(address _mintFeeAddr) public {
require(_msgSender() == mintFeeAddr, "FORBIDDEN");
mintFeeAddr = _mintFeeAddr;
emit MintFeeAddressTransferred(_msgSender(), mintFeeAddr);
}
function setMintFeeAmount(uint256 _mintFeeAmount) public onlyOwner {
require(mintFeeAmount != _mintFeeAmount, "FEE NO CHANGE");
emit SetMintFeeAmount(_msgSender(), mintFeeAmount, _mintFeeAmount);
mintFeeAmount = _mintFeeAmount;
}
function getRoyaltyMeta(uint256 tokenId)
public
view
returns (address, uint256)
{
RoyaltyMeta memory royaltyMeta = _tokenRoyaltyMeta[tokenId];
return (royaltyMeta.royalty, royaltyMeta.royaltyRate);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, ERC721Enumerable, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| 3,217,111 | [
1,
3800,
15006,
1807,
1779,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1731,
1578,
1071,
5381,
11028,
67,
8412,
67,
3098,
67,
16256,
273,
203,
3639,
417,
24410,
581,
5034,
2932,
8217,
67,
8412,
67,
3098,
67,
16256,
8863,
203,
565,
1731,
1578,
1071,
5381,
15662,
20093,
67,
16256,
273,
417,
24410,
581,
5034,
2932,
4066,
20093,
67,
16256,
8863,
203,
565,
2254,
5034,
1071,
9617,
548,
273,
404,
31,
203,
565,
1758,
1071,
312,
474,
14667,
3178,
31,
203,
565,
2254,
5034,
1071,
312,
474,
14667,
6275,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
534,
13372,
15006,
2781,
13,
3238,
389,
2316,
54,
13372,
15006,
2781,
31,
203,
203,
203,
565,
1958,
534,
13372,
15006,
2781,
288,
203,
3639,
1758,
721,
93,
15006,
31,
203,
3639,
2254,
5034,
721,
93,
15006,
4727,
31,
203,
565,
289,
203,
203,
565,
871,
534,
13372,
15006,
12,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
1758,
8808,
721,
93,
15006,
16,
203,
3639,
2254,
5034,
721,
93,
15006,
4727,
203,
565,
11272,
203,
565,
871,
605,
321,
12,
2867,
8808,
5793,
16,
2254,
5034,
1147,
548,
1769,
203,
565,
871,
490,
474,
14667,
1887,
1429,
4193,
12,
203,
3639,
1758,
8808,
2416,
5541,
16,
203,
3639,
1758,
8808,
394,
5541,
203,
565,
11272,
203,
565,
871,
1000,
49,
474,
14667,
6275,
12,
203,
3639,
1758,
8808,
29804,
16,
203,
3639,
2254,
5034,
1592,
49,
474,
14667,
6275,
16,
203,
3639,
2254,
5034,
394,
49,
474,
14667,
6275,
203,
565,
11272,
203,
203,
565,
3885,
12,
203,
3639,
533,
3778,
508,
16,
203,
2
] |
/*
<< EIP 712 >>
*/
pragma solidity 0.7.5;
/**
* @title EIP712
* @author Wyvern Protocol Developers
*/
contract EIP712 {
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
bytes32 constant EIP712DOMAIN_TYPEHASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
// 用来在不同Dapp之间区分相同结构和内容的签名消息,该值也有助于用户辨识哪些为信任的Dapp
bytes32 DOMAIN_SEPARATOR;
function hash(EIP712Domain memory eip712Domain)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(eip712Domain.name)),
keccak256(bytes(eip712Domain.version)),
eip712Domain.chainId,
eip712Domain.verifyingContract
)
);
}
}
| * @title EIP712 @author Wyvern Protocol Developers/ | contract EIP712 {
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
bytes32 constant EIP712DOMAIN_TYPEHASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 DOMAIN_SEPARATOR;
function hash(EIP712Domain memory eip712Domain)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(eip712Domain.name)),
keccak256(bytes(eip712Domain.version)),
eip712Domain.chainId,
eip712Domain.verifyingContract
)
);
}
}
| 12,917,557 | [
1,
41,
2579,
27,
2138,
225,
29271,
502,
82,
4547,
1505,
8250,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
512,
2579,
27,
2138,
288,
203,
203,
203,
565,
1958,
512,
2579,
27,
2138,
3748,
288,
203,
3639,
533,
508,
31,
203,
3639,
533,
1177,
31,
203,
3639,
2254,
5034,
2687,
548,
31,
203,
3639,
1758,
3929,
310,
8924,
31,
203,
565,
289,
203,
203,
565,
1731,
1578,
5381,
512,
2579,
27,
2138,
18192,
67,
2399,
15920,
273,
203,
3639,
417,
24410,
581,
5034,
12,
203,
5411,
315,
41,
2579,
27,
2138,
3748,
12,
1080,
508,
16,
1080,
1177,
16,
11890,
5034,
2687,
548,
16,
2867,
3929,
310,
8924,
2225,
203,
3639,
11272,
203,
203,
203,
565,
1731,
1578,
27025,
67,
4550,
31,
203,
565,
445,
1651,
12,
41,
2579,
27,
2138,
3748,
3778,
425,
625,
27,
2138,
3748,
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,
203,
7734,
24126,
18,
3015,
12,
203,
10792,
512,
2579,
27,
2138,
18192,
67,
2399,
15920,
16,
203,
10792,
417,
24410,
581,
5034,
12,
3890,
12,
73,
625,
27,
2138,
3748,
18,
529,
13,
3631,
203,
10792,
417,
24410,
581,
5034,
12,
3890,
12,
73,
625,
27,
2138,
3748,
18,
1589,
13,
3631,
203,
10792,
425,
625,
27,
2138,
3748,
18,
5639,
548,
16,
203,
10792,
425,
625,
27,
2138,
3748,
18,
8705,
310,
8924,
203,
7734,
262,
203,
5411,
11272,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xC6D23c746d9b3d97D8281BD878A17CdFA90a9ac1
//Contract name: CustomPOAToken
//Balance: 0.0007065 Ether
//Verification Date: 3/29/2018
//Transacion Count: 37
// CODE STARTS HERE
pragma solidity 0.4.18;
// File: zeppelin-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 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;
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal 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;
}
}
// File: zeppelin-solidity/contracts/token/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin-solidity/contracts/token/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: zeppelin-solidity/contracts/token/StandardToken.sol
/**
* @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;
}
}
// File: zeppelin-solidity/contracts/token/PausableToken.sol
/**
* @title Pausable token
*
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// File: contracts/CustomPOAToken.sol
contract CustomPOAToken is PausableToken {
string public name;
string public symbol;
uint8 public constant decimals = 18;
address public owner;
address public broker;
address public custodian;
uint256 public creationBlock;
uint256 public timeoutBlock;
// the total per token payout rate: accumulates as payouts are received
uint256 public totalPerTokenPayout;
uint256 public tokenSaleRate;
uint256 public fundedAmount;
uint256 public fundingGoal;
uint256 public initialSupply;
// ‰ permille NOT percent
uint256 public constant feeRate = 5;
// self contained whitelist on contract, must be whitelisted to buy
mapping (address => bool) public whitelisted;
// used to deduct already claimed payouts on a per token basis
mapping(address => uint256) public claimedPerTokenPayouts;
// fallback for when a transfer happens with payouts remaining
mapping(address => uint256) public unclaimedPayoutTotals;
enum Stages {
Funding,
Pending,
Failed,
Active,
Terminated
}
Stages public stage = Stages.Funding;
event StageEvent(Stages stage);
event BuyEvent(address indexed buyer, uint256 amount);
event PayoutEvent(uint256 amount);
event ClaimEvent(uint256 payout);
event TerminatedEvent();
event WhitelistedEvent(address indexed account, bool isWhitelisted);
modifier isWhitelisted() {
require(whitelisted[msg.sender]);
_;
}
modifier onlyCustodian() {
require(msg.sender == custodian);
_;
}
// start stage related modifiers
modifier atStage(Stages _stage) {
require(stage == _stage);
_;
}
modifier atEitherStage(Stages _stage, Stages _orStage) {
require(stage == _stage || stage == _orStage);
_;
}
modifier checkTimeout() {
if (stage == Stages.Funding && block.number >= creationBlock.add(timeoutBlock)) {
uint256 _unsoldBalance = balances[this];
balances[this] = 0;
totalSupply = totalSupply.sub(_unsoldBalance);
Transfer(this, address(0), balances[this]);
enterStage(Stages.Failed);
}
_;
}
// end stage related modifiers
// token totalSupply must be more than fundingGoal!
function CustomPOAToken
(
string _name,
string _symbol,
address _broker,
address _custodian,
uint256 _timeoutBlock,
uint256 _totalSupply,
uint256 _fundingGoal
)
public
{
require(_fundingGoal > 0);
require(_totalSupply > _fundingGoal);
owner = msg.sender;
name = _name;
symbol = _symbol;
broker = _broker;
custodian = _custodian;
timeoutBlock = _timeoutBlock;
creationBlock = block.number;
// essentially sqm unit of building...
totalSupply = _totalSupply;
initialSupply = _totalSupply;
fundingGoal = _fundingGoal;
balances[this] = _totalSupply;
paused = true;
}
// start token conversion functions
/*******************
* TKN supply *
* --- = ------- *
* ETH funding *
*******************/
// util function to convert wei to tokens. can be used publicly to see
// what the balance would be for a given Ξ amount.
// will drop miniscule amounts of wei due to integer division
function weiToTokens(uint256 _weiAmount)
public
view
returns (uint256)
{
return _weiAmount
.mul(1e18)
.mul(initialSupply)
.div(fundingGoal)
.div(1e18);
}
// util function to convert tokens to wei. can be used publicly to see how
// much Ξ would be received for token reclaim amount
// will typically lose 1 wei unit of Ξ due to integer division
function tokensToWei(uint256 _tokenAmount)
public
view
returns (uint256)
{
return _tokenAmount
.mul(1e18)
.mul(fundingGoal)
.div(initialSupply)
.div(1e18);
}
// end token conversion functions
// pause override
function unpause()
public
onlyOwner
whenPaused
{
// only allow unpausing when in Active stage
require(stage == Stages.Active);
return super.unpause();
}
// stage related functions
function enterStage(Stages _stage)
private
{
stage = _stage;
StageEvent(_stage);
}
// start whitelist related functions
// allow address to buy tokens
function whitelistAddress(address _address)
external
onlyOwner
atStage(Stages.Funding)
{
require(whitelisted[_address] != true);
whitelisted[_address] = true;
WhitelistedEvent(_address, true);
}
// disallow address to buy tokens.
function blacklistAddress(address _address)
external
onlyOwner
atStage(Stages.Funding)
{
require(whitelisted[_address] != false);
whitelisted[_address] = false;
WhitelistedEvent(_address, false);
}
// check to see if contract whitelist has approved address to buy
function whitelisted(address _address)
public
view
returns (bool)
{
return whitelisted[_address];
}
// end whitelist related functions
// start fee handling functions
// public utility function to allow checking of required fee for a given amount
function calculateFee(uint256 _value)
public
view
returns (uint256)
{
return feeRate.mul(_value).div(1000);
}
// end fee handling functions
// start lifecycle functions
function buy()
public
payable
checkTimeout
atStage(Stages.Funding)
isWhitelisted
returns (bool)
{
uint256 _payAmount;
uint256 _buyAmount;
// check if balance has met funding goal to move on to Pending
if (fundedAmount.add(msg.value) < fundingGoal) {
// _payAmount is just value sent
_payAmount = msg.value;
// get token amount from wei... drops remainders (keeps wei dust in contract)
_buyAmount = weiToTokens(_payAmount);
// check that buyer will indeed receive something after integer division
// this check cannot be done in other case because it could prevent
// contract from moving to next stage
require(_buyAmount > 0);
} else {
// let the world know that the token is in Pending Stage
enterStage(Stages.Pending);
// set refund amount (overpaid amount)
uint256 _refundAmount = fundedAmount.add(msg.value).sub(fundingGoal);
// get actual Ξ amount to buy
_payAmount = msg.value.sub(_refundAmount);
// get token amount from wei... drops remainders (keeps wei dust in contract)
_buyAmount = weiToTokens(_payAmount);
// assign remaining dust
uint256 _dust = balances[this].sub(_buyAmount);
// sub dust from contract
balances[this] = balances[this].sub(_dust);
// give dust to owner
balances[owner] = balances[owner].add(_dust);
Transfer(this, owner, _dust);
// SHOULD be ok even with reentrancy because of enterStage(Stages.Pending)
msg.sender.transfer(_refundAmount);
}
// deduct token buy amount balance from contract balance
balances[this] = balances[this].sub(_buyAmount);
// add token buy amount to sender's balance
balances[msg.sender] = balances[msg.sender].add(_buyAmount);
// increment the funded amount
fundedAmount = fundedAmount.add(_payAmount);
// send out event giving info on amount bought as well as claimable dust
Transfer(this, msg.sender, _buyAmount);
BuyEvent(msg.sender, _buyAmount);
return true;
}
function activate()
external
checkTimeout
onlyCustodian
payable
atStage(Stages.Pending)
returns (bool)
{
// calculate company fee charged for activation
uint256 _fee = calculateFee(fundingGoal);
// value must exactly match fee
require(msg.value == _fee);
// if activated and fee paid: put in Active stage
enterStage(Stages.Active);
// owner (company) fee set in unclaimedPayoutTotals to be claimed by owner
unclaimedPayoutTotals[owner] = unclaimedPayoutTotals[owner].add(_fee);
// custodian value set to claimable. can now be claimed via claim function
// set all eth in contract other than fee as claimable.
// should only be buy()s. this ensures buy() dust is cleared
unclaimedPayoutTotals[custodian] = unclaimedPayoutTotals[custodian]
.add(this.balance.sub(_fee));
// allow trading of tokens
paused = false;
// let world know that this token can now be traded.
Unpause();
return true;
}
// used when property no longer exists etc. allows for winding down via payouts
// can no longer be traded after function is run
function terminate()
external
onlyCustodian
atStage(Stages.Active)
returns (bool)
{
// set Stage to terminated
enterStage(Stages.Terminated);
// pause. Cannot be unpaused now that in Stages.Terminated
paused = true;
// let the world know this token is in Terminated Stage
TerminatedEvent();
}
// emergency temporary function used only in case of emergency to return
// Ξ to contributors in case of catastrophic contract failure.
function kill()
external
onlyOwner
{
// stop trading
paused = true;
// enter stage which will no longer allow unpausing
enterStage(Stages.Terminated);
// transfer funds to company in order to redistribute manually
owner.transfer(this.balance);
// let the world know that this token is in Terminated Stage
TerminatedEvent();
}
// end lifecycle functions
// start payout related functions
// get current payout for perTokenPayout and unclaimed
function currentPayout(address _address, bool _includeUnclaimed)
public
view
returns (uint256)
{
/*
need to check if there have been no payouts
safe math will throw otherwise due to dividing 0
The below variable represents the total payout from the per token rate pattern
it uses this funky naming pattern in order to differentiate from the unclaimedPayoutTotals
which means something very different.
*/
uint256 _totalPerTokenUnclaimedConverted = totalPerTokenPayout == 0
? 0
: balances[_address]
.mul(totalPerTokenPayout.sub(claimedPerTokenPayouts[_address]))
.div(1e18);
/*
balances may be bumped into unclaimedPayoutTotals in order to
maintain balance tracking accross token transfers
perToken payout rates are stored * 1e18 in order to be kept accurate
perToken payout is / 1e18 at time of usage for actual Ξ balances
unclaimedPayoutTotals are stored as actual Ξ value
no need for rate * balance
*/
return _includeUnclaimed
? _totalPerTokenUnclaimedConverted.add(unclaimedPayoutTotals[_address])
: _totalPerTokenUnclaimedConverted;
}
// settle up perToken balances and move into unclaimedPayoutTotals in order
// to ensure that token transfers will not result in inaccurate balances
function settleUnclaimedPerTokenPayouts(address _from, address _to)
private
returns (bool)
{
// add perToken balance to unclaimedPayoutTotals which will not be affected by transfers
unclaimedPayoutTotals[_from] = unclaimedPayoutTotals[_from].add(currentPayout(_from, false));
// max out claimedPerTokenPayouts in order to effectively make perToken balance 0
claimedPerTokenPayouts[_from] = totalPerTokenPayout;
// same as above for to
unclaimedPayoutTotals[_to] = unclaimedPayoutTotals[_to].add(currentPayout(_to, false));
// same as above for to
claimedPerTokenPayouts[_to] = totalPerTokenPayout;
return true;
}
// used to manually set Stage to Failed when no users have bought any tokens
// if no buy()s occurred before timeoutBlock token would be stuck in Funding
function setFailed()
external
atStage(Stages.Funding)
checkTimeout
returns (bool)
{
if (stage == Stages.Funding) {
revert();
}
return true;
}
// reclaim Ξ for sender if fundingGoal is not met within timeoutBlock
function reclaim()
external
checkTimeout
atStage(Stages.Failed)
returns (bool)
{
// get token balance of user
uint256 _tokenBalance = balances[msg.sender];
// ensure that token balance is over 0
require(_tokenBalance > 0);
// set token balance to 0 so re reclaims are not possible
balances[msg.sender] = 0;
// decrement totalSupply by token amount being reclaimed
totalSupply = totalSupply.sub(_tokenBalance);
Transfer(msg.sender, address(0), _tokenBalance);
// decrement fundedAmount by eth amount converted from token amount being reclaimed
fundedAmount = fundedAmount.sub(tokensToWei(_tokenBalance));
// set reclaim total as token value
uint256 _reclaimTotal = tokensToWei(_tokenBalance);
// send Ξ back to sender
msg.sender.transfer(_reclaimTotal);
return true;
}
// send Ξ to contract to be claimed by token holders
function payout()
external
payable
atEitherStage(Stages.Active, Stages.Terminated)
onlyCustodian
returns (bool)
{
// calculate fee based on feeRate
uint256 _fee = calculateFee(msg.value);
// ensure the value is high enough for a fee to be claimed
require(_fee > 0);
// deduct fee from payout
uint256 _payoutAmount = msg.value.sub(_fee);
/*
totalPerTokenPayout is a rate at which to payout based on token balance
it is stored as * 1e18 in order to keep accuracy
it is / 1e18 when used relating to actual Ξ values
*/
totalPerTokenPayout = totalPerTokenPayout
.add(_payoutAmount
.mul(1e18)
.div(totalSupply)
);
// take remaining dust and send to owner rather than leave stuck in contract
// should not be more than a few wei
uint256 _delta = (_payoutAmount.mul(1e18) % totalSupply).div(1e18);
unclaimedPayoutTotals[owner] = unclaimedPayoutTotals[owner].add(_fee).add(_delta);
// let the world know that a payout has happened for this token
PayoutEvent(_payoutAmount);
return true;
}
// claim total Ξ claimable for sender based on token holdings at time of each payout
function claim()
external
atEitherStage(Stages.Active, Stages.Terminated)
returns (uint256)
{
/*
pass true to currentPayout in order to get both:
perToken payouts
unclaimedPayoutTotals
*/
uint256 _payoutAmount = currentPayout(msg.sender, true);
// check that there indeed is a pending payout for sender
require(_payoutAmount > 0);
// max out per token payout for sender in order to make payouts effectively
// 0 for sender
claimedPerTokenPayouts[msg.sender] = totalPerTokenPayout;
// 0 out unclaimedPayoutTotals for user
unclaimedPayoutTotals[msg.sender] = 0;
// let the world know that a payout for sender has been claimed
ClaimEvent(_payoutAmount);
// transfer Ξ payable amount to sender
msg.sender.transfer(_payoutAmount);
return _payoutAmount;
}
// end payout related functions
// start ERC20 overrides
// same as ERC20 transfer other than settling unclaimed payouts
function transfer
(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
// move perToken payout balance to unclaimedPayoutTotals
require(settleUnclaimedPerTokenPayouts(msg.sender, _to));
return super.transfer(_to, _value);
}
// same as ERC20 transfer other than settling unclaimed payouts
function transferFrom
(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
// move perToken payout balance to unclaimedPayoutTotals
require(settleUnclaimedPerTokenPayouts(_from, _to));
return super.transferFrom(_from, _to, _value);
}
// end ERC20 overrides
// check if there is a way to get around gas issue when no gas limit calculated...
// fallback function defaulting to buy
function()
public
payable
{
buy();
}
}
| used when property no longer exists etc. allows for winding down via payouts can no longer be traded after function is run set Stage to terminated pause. Cannot be unpaused now that in Stages.Terminated let the world know this token is in Terminated Stage | function terminate()
external
onlyCustodian
atStage(Stages.Active)
returns (bool)
{
enterStage(Stages.Terminated);
paused = true;
TerminatedEvent();
}
| 12,650,378 | [
1,
3668,
1347,
1272,
1158,
7144,
1704,
5527,
18,
5360,
364,
17064,
310,
2588,
3970,
293,
2012,
87,
848,
1158,
7144,
506,
1284,
785,
1839,
445,
353,
1086,
444,
16531,
358,
14127,
11722,
18,
14143,
506,
640,
8774,
3668,
2037,
716,
316,
934,
1023,
18,
21888,
2231,
326,
9117,
5055,
333,
1147,
353,
316,
6820,
7458,
16531,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
10850,
1435,
203,
565,
3903,
203,
565,
1338,
39,
641,
369,
2779,
203,
565,
622,
8755,
12,
31359,
18,
3896,
13,
203,
565,
1135,
261,
6430,
13,
203,
225,
288,
203,
565,
6103,
8755,
12,
31359,
18,
21888,
1769,
203,
565,
17781,
273,
638,
31,
203,
565,
6820,
7458,
1133,
5621,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
// File: zeppelin-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 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;
}
}
// File: zeppelin-solidity/contracts/lifecycle/Destructible.sol
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
function Destructible() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
// File: zeppelin-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) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: zeppelin-solidity/contracts/payment/PullPayment.sol
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use asyncSend instead of send.
*/
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
/**
* @dev withdraw accumulated balance, called by payee.
*/
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(this.balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
assert(payee.send(payment));
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
}
// File: contracts/GoGlobals.sol
/// @title The base contract for EthernalGo, contains the admin functions and the globals used throught the game
/// @author https://www.EthernalGo.com
/// @dev See the GoGameLogic and GoBoardMetaDetails contract documentation to understand the actual game mechanics.
contract GoGlobals is Ownable, PullPayment, Destructible, Pausable {
// Used for simplifying capture calculations
uint8 constant MAX_UINT8 = 255;
// Used to dermine player color and who is up next
enum PlayerColor {None, Black, White}
/// @dev Board status is a critical concept that determines which actions can be taken within each phase
/// WaitForOpponent - When the first player has registered and waiting for a second player
/// InProgress - The match is on! The acting player can choose between placing a stone or passing (or resigning)
/// WaitingToResolve - Both players chose to pass their turn and we are waiting for the winner to ask the contract for score count
/// BlackWin, WhiteWin, Draw - Pretty self explanatory
/// Canceled - The first player who joined the board is allowed to cancel a match if no opponent has joined yet
enum BoardStatus {WaitForOpponent, InProgress, WaitingToResolve, BlackWin, WhiteWin, Draw, Canceled}
// We staretd with a 9x9 rows
uint8 constant BOARD_ROW_SIZE = 9;
uint8 constant BOARD_SIZE = BOARD_ROW_SIZE ** 2;
// We use a shrinked board size to optimize gas costs
uint8 constant SHRINKED_BOARD_SIZE = 21;
// These are the shares each player and EthernalGo are getting for each game
uint public WINNER_SHARE;
uint public HOST_SHARE;
uint public HONORABLE_LOSS_BONUS;
// Each player gets PLAYER_TURN_SINGLE_PERIOD x PLAYER_START_PERIODS to act. These may change according to player feedback and network conjunction to optimize the playing experience
uint public PLAYER_TURN_SINGLE_PERIOD = 4 minutes;
uint8 public PLAYER_START_PERIODS = 5;
// We decided to restrict the table stakes to several options to allow for easier match-making
uint[] public tableStakesOptions;
// This is the main data field that contains access to all of the GoBoards that were created
GoBoard[] internal allBoards;
// The CFO is the only account that is allowed to withdraw funds
address public CFO;
// This is the main board structure and is instantiated for every new game
struct GoBoard {
// We use the last update to determine how long has it been since the player could act
uint lastUpdate;
// The table stakes marks how much ETH each participant needs to pay to register for the board
uint tableStakes;
// The board balance keeps track of how much ETH this board has in order to see if we already distributed the payments for this match
uint boardBalance;
// Black and white player addresses
address blackAddress;
address whiteAddress;
// Black and white time periods remaining (initially they will be PLAYER_START_PERIODS)
uint8 blackPeriodsRemaining;
uint8 whitePeriodsRemaining;
// Keep track of double pass to finish the game
bool didPassPrevTurn;
// Keep track of double pass to finish the game
bool isHonorableLoss;
// Who's next
PlayerColor nextTurnColor;
// Use a mapping to figure out which stone is set in which position. (Positions can be 0-BOARD_SIZE)
// @dev We decided not use an array to minimize the storage cost
mapping(uint8=>uint8) positionToColor;
// The board's current status
BoardStatus status;
}
/// @notice The constructor is called with our inital values, they will probably change but this is what had in mind when developing the game.
function GoGlobals() public Ownable() PullPayment() Destructible() {
// Add initial price tiers so from variouos ranges
addPriceTier(0.5 ether);
addPriceTier(1 ether);
addPriceTier(5 ether);
// These are the inital shares we've had in mind when developing the game
updateShares(950, 50, 5);
// The CFO will be the owner, but it will change soon after the contract is deployed
CFO = owner;
}
/// @notice In case we need extra price tiers (table stakes where people can play) we can add additional ones
/// @param price the price for the new price tier in WEI
function addPriceTier(uint price) public onlyOwner {
tableStakesOptions.push(price);
}
/// If we need to update price tiers
/// @param priceTier the tier index from the array
/// @param price the new price to set
function updatePriceTier(uint8 priceTier, uint price) public onlyOwner {
tableStakesOptions[priceTier] = price;
}
/// @notice If we need to adjust the amounts players or EthernalGo gets for each game
/// @param newWinnerShare the winner's share (out of 1000)
/// @param newHostShare EthernalGo's share (out of 1000)
/// @param newBonusShare Bonus that comes our of EthernalGo and goes to the loser in case of an honorable loss (out of 1000)
function updateShares(uint newWinnerShare, uint newHostShare, uint newBonusShare) public onlyOwner {
require(newWinnerShare + newHostShare == 1000);
WINNER_SHARE = newWinnerShare;
HOST_SHARE = newHostShare;
HONORABLE_LOSS_BONUS = newBonusShare;
}
/// @notice Separating the CFO and the CEO responsibilities requires the ability to set the CFO account
/// @param newCFO the new CFO
function setNewCFO(address newCFO) public onlyOwner {
require(newCFO != 0);
CFO = newCFO;
}
/// @notice Separating the CFO and the CEO responsibilities requires the ability to set the CFO account
/// @param secondsPerPeriod The number of seconds we would like each period to last
/// @param numberOfPeriods The number of of periods each player initially has
function updateGameTimes(uint secondsPerPeriod, uint8 numberOfPeriods) public onlyOwner {
PLAYER_TURN_SINGLE_PERIOD = secondsPerPeriod;
PLAYER_START_PERIODS = numberOfPeriods;
}
/// @dev Convinience function to access the shares
function getShares() public view returns(uint, uint, uint) {
return (WINNER_SHARE, HOST_SHARE, HONORABLE_LOSS_BONUS);
}
}
// File: contracts/GoBoardMetaDetails.sol
/// @title This contract manages the meta details of EthernalGo.
/// Registering to a board, splitting the revenues and other day-to-day actions that are unrelated to the actual game
/// @author https://www.EthernalGo.com
/// @dev See the GoGameLogic to understand the actual game mechanics and rules
contract GoBoardMetaDetails is GoGlobals {
/// @dev The player added to board event can be used to check upon registration success
event PlayerAddedToBoard(uint boardId, address playerAddress);
/// @dev The board updated status can be used to get the new board status
event BoardStatusUpdated(uint boardId, BoardStatus newStatus);
/// @dev The player withdrawn his accumulated balance
event PlayerWithdrawnBalance(address playerAddress);
/// @dev Simple wrapper to return the number of boards in total
function getTotalNumberOfBoards() public view returns(uint) {
return allBoards.length;
}
/// @notice We would like to easily and transparantly share the game's statistics with anyone and present on the web-app
function getCompletedGamesStatistics() public view returns(uint, uint) {
uint completed = 0;
uint ethPaid = 0;
// @dev Go through all the boards, we start with 1 as it's an unsigned int
for (uint i = 1; i <= allBoards.length; i++) {
// Get the current board
GoBoard storage board = allBoards[i - 1];
// Check if it was a victory, otherwise it's not interesting as the players just got their deposit back
if ((board.status == BoardStatus.BlackWin) || (board.status == BoardStatus.WhiteWin)) {
++completed;
// We need to query the table stakes as the board's balance will be zero once a game is finished
ethPaid += board.tableStakes.mul(2);
}
}
return (completed, ethPaid);
}
/// @dev At this point there is no support for returning dynamic arrays (it's supported for web3 calls but not for internal testing) so we will "only" present the recent 50 games per player.
uint8 constant PAGE_SIZE = 50;
/// @dev Make sure this board is in waiting for result status
modifier boardWaitingToResolve(uint boardId){
require(allBoards[boardId].status == BoardStatus.WaitingToResolve);
_;
}
/// @dev Make sure this board is in one of the end of game states
modifier boardGameEnded(GoBoard storage board){
require(isEndGameStatus(board.status));
_;
}
/// @dev Make sure this board still has balance
modifier boardNotPaid(GoBoard storage board){
require(board.boardBalance > 0);
_;
}
/// @dev Make sure this board still has a spot for at least one player to join
modifier boardWaitingForPlayers(uint boardId){
require(allBoards[boardId].status == BoardStatus.WaitForOpponent &&
(allBoards[boardId].blackAddress == 0 ||
allBoards[boardId].whiteAddress == 0));
_;
}
/// @dev Restricts games for the allowed table stakes
/// @param value the value we are looking for to register
modifier allowedValuesOnly(uint value){
bool didFindValue = false;
// The number of tableStakesOptions can change hence it has to be dynamic
for (uint8 i = 0; i < tableStakesOptions.length; ++ i) {
if (value == tableStakesOptions[i])
didFindValue = true;
}
require (didFindValue);
_;
}
/// @dev Checks a status if and returns if it's an end game
/// @param status the value we are checking
/// @return true if it's an end-game status
function isEndGameStatus(BoardStatus status) public pure returns(bool) {
return (status == BoardStatus.BlackWin) || (status == BoardStatus.WhiteWin) || (status == BoardStatus.Draw) || (status == BoardStatus.Canceled);
}
/// @dev Gets the update time for a board
/// @param boardId The id of the board to check
/// @return the update timestamp in seconds
function getBoardUpdateTime(uint boardId) public view returns(uint) {
GoBoard storage board = allBoards[boardId];
return (board.lastUpdate);
}
/// @dev Gets the current board status
/// @param boardId The id of the board to check
/// @return the current board status
function getBoardStatus(uint boardId) public view returns(BoardStatus) {
GoBoard storage board = allBoards[boardId];
return (board.status);
}
/// @dev Gets the current balance of the board
/// @param boardId The id of the board to check
/// @return the current board balance in WEI
function getBoardBalance(uint boardId) public view returns(uint) {
GoBoard storage board = allBoards[boardId];
return (board.boardBalance);
}
/// @dev Sets the current balance of the board, this is internal and is triggerred by functions run by external player actions
/// @param board The board to update
/// @param boardId The board's Id
/// @param newStatus The new status to set
function updateBoardStatus(GoBoard storage board, uint boardId, BoardStatus newStatus) internal {
// Save gas if we accidentally are trying to update to an existing update
if (newStatus != board.status) {
// Set the new board status
board.status = newStatus;
// Update the time (important for start and finish states)
board.lastUpdate = now;
// If this is an end game status
if (isEndGameStatus(newStatus)) {
// Credit the players accoriding to the board score
creditBoardGameRevenues(board);
}
// Notify status update
BoardStatusUpdated(boardId, newStatus);
}
}
/// @dev Overload to set the board status when we only have a boardId
/// @param boardId The boardId to update
/// @param newStatus The new status to set
function updateBoardStatus(uint boardId, BoardStatus newStatus) internal {
updateBoardStatus(allBoards[boardId], boardId, newStatus);
}
/// @dev Gets the player color given an address and board (overload for when we only have boardId)
/// @param boardId The boardId to check
/// @param searchAddress The player's address we are searching for
/// @return the player's color
function getPlayerColor(uint boardId, address searchAddress) internal view returns (PlayerColor) {
return (getPlayerColor(allBoards[boardId], searchAddress));
}
/// @dev Gets the player color given an address and board
/// @param board The board to check
/// @param searchAddress The player's address we are searching for
/// @return the player's color
function getPlayerColor(GoBoard storage board, address searchAddress) internal view returns (PlayerColor) {
// Check if this is the black player
if (board.blackAddress == searchAddress) {
return (PlayerColor.Black);
}
// Check if this is the white player
if (board.whiteAddress == searchAddress) {
return (PlayerColor.White);
}
// We aren't suppose to try and get the color of a player if they aren't on the board
revert();
}
/// @dev Gets the player address given a color on the board
/// @param boardId The board to check
/// @param color The color of the player we want
/// @return the player's address
function getPlayerAddress(uint boardId, PlayerColor color) public view returns(address) {
// If it's the black player
if (color == PlayerColor.Black) {
return allBoards[boardId].blackAddress;
}
// If it's the white player
if (color == PlayerColor.White) {
return allBoards[boardId].whiteAddress;
}
// We aren't suppose to try and get the color of a player if they aren't on the board
revert();
}
/// @dev Check if a player is on board (overload for boardId)
/// @param boardId The board to check
/// @param searchAddress the player's address we want to check
/// @return true if the player is playing in the board
function isPlayerOnBoard(uint boardId, address searchAddress) public view returns(bool) {
return (isPlayerOnBoard(allBoards[boardId], searchAddress));
}
/// @dev Check if a player is on board
/// @param board The board to check
/// @param searchAddress the player's address we want to check
/// @return true if the player is playing in the board
function isPlayerOnBoard(GoBoard storage board, address searchAddress) private view returns(bool) {
return (board.blackAddress == searchAddress || board.whiteAddress == searchAddress);
}
/// @dev Check which player acts next
/// @param boardId The board to check
/// @return The color of the current player to act
function getNextTurnColor(uint boardId) public view returns(PlayerColor) {
return allBoards[boardId].nextTurnColor;
}
/// @notice This is the first function a player will be using in order to start playing. This function allows
/// to register to an existing or a new board, depending on the current available boards.
/// Upon registeration the player will pay the board's stakes and will be the black or white player.
/// The black player also creates the board, and is the first player which gives a small advantage in the
/// game, therefore we decided that the black player will be the one paying for the additional gas
/// that is required to create the board.
/// @param tableStakes The tablestakes to use, although this appears in the "value" of the message, we preferred to
/// add it as an additional parameter for client use for clients that allow to customize the value parameter.
/// @return The boardId the player registered to (either a new board or an existing board)
function registerPlayerToBoard(uint tableStakes) external payable allowedValuesOnly(msg.value) whenNotPaused returns(uint) {
// Make sure the value and tableStakes are the same
require (msg.value == tableStakes);
GoBoard storage boardToJoin;
uint boardIDToJoin;
// Check which board to connect to
(boardIDToJoin, boardToJoin) = getOrCreateWaitingBoard(tableStakes);
// Add the player to the board (they already paid)
bool shouldStartGame = addPlayerToBoard(boardToJoin, tableStakes);
// Fire the event for anyone listening
PlayerAddedToBoard(boardIDToJoin, msg.sender);
// If we have both players, start the game
if (shouldStartGame) {
// Start the game
startBoardGame(boardToJoin, boardIDToJoin);
}
return boardIDToJoin;
}
/// @notice This function allows a player to cancel a match in the case they were waiting for an opponent for
/// a long time but didn't find anyone and would want to get their deposit of table stakes back.
/// That player may cancel the game as long as no opponent was found and the deposit will be returned in full (though gas fees still apply). The player will also need to withdraw funds from the contract after this action.
/// @param boardId The board to cancel
function cancelMatch(uint boardId) external {
// Get the player
GoBoard storage board = allBoards[boardId];
// Make sure this player is on board
require(isPlayerOnBoard(boardId, msg.sender));
// Make sure that the game hasn't started
require(board.status == BoardStatus.WaitForOpponent);
// Update the board status to cancel (which also triggers the revenue sharing function)
updateBoardStatus(board, boardId, BoardStatus.Canceled);
}
/// @dev Gets the current player boards to present to the player as needed
/// @param activeTurnsOnly We might want to highlight the boards where the player is expected to act
/// @return an array of PAGE_SIZE with the number of boards found and the actual IDs
function getPlayerBoardsIDs(bool activeTurnsOnly) public view returns (uint, uint[PAGE_SIZE]) {
uint[PAGE_SIZE] memory playerBoardIDsToReturn;
uint numberOfPlayerBoardsToReturn = 0;
// Look at the recent boards until you find a player board
for (uint currBoard = allBoards.length; currBoard > 0 && numberOfPlayerBoardsToReturn < PAGE_SIZE; currBoard--) {
uint boardID = currBoard - 1;
// We only care about boards the player is in
if (isPlayerOnBoard(boardID, msg.sender)) {
// Check if the player is the next to act, or just include it if it wasn't requested
if (!activeTurnsOnly || getNextTurnColor(boardID) == getPlayerColor(boardID, msg.sender)) {
playerBoardIDsToReturn[numberOfPlayerBoardsToReturn] = boardID;
++numberOfPlayerBoardsToReturn;
}
}
}
return (numberOfPlayerBoardsToReturn, playerBoardIDsToReturn);
}
/// @dev Creates a new board in case no board was found for a player to register
/// @param tableStakesToUse The value used to set the board
/// @return the id of new board (which is it's position in the allBoards array)
function createNewGoBoard(uint tableStakesToUse) private returns(uint, GoBoard storage) {
GoBoard memory newBoard = GoBoard({lastUpdate: now,
isHonorableLoss: false,
tableStakes: tableStakesToUse,
boardBalance: 0,
blackAddress: 0,
whiteAddress: 0,
blackPeriodsRemaining: PLAYER_START_PERIODS,
whitePeriodsRemaining: PLAYER_START_PERIODS,
nextTurnColor: PlayerColor.None,
status:BoardStatus.WaitForOpponent,
didPassPrevTurn:false});
uint boardId = allBoards.push(newBoard) - 1;
return (boardId, allBoards[boardId]);
}
/// @dev Creates a new board in case no board was found for a player to register
/// @param tableStakes The value used to set the board
/// @return the id of new board (which is it's position in the allBoards array)
function getOrCreateWaitingBoard(uint tableStakes) private returns(uint, GoBoard storage) {
bool wasFound = false;
uint selectedBoardId = 0;
GoBoard storage board;
// First, try to find a board that has an empty spot and the right table stakes
for (uint i = allBoards.length; i > 0 && !wasFound; --i) {
board = allBoards[i - 1];
// Make sure this board is already waiting and it's stakes are the same
if (board.tableStakes == tableStakes) {
// If this board is waiting for an opponent
if (board.status == BoardStatus.WaitForOpponent) {
// Awesome, we have the board and we are done
wasFound = true;
selectedBoardId = i - 1;
}
// If we found the rights stakes board but it isn't waiting for player we won't have another empty board.
// We need to create a new one
break;
}
}
// Create a new board if we couldn't find one
if (!wasFound) {
(selectedBoardId, board) = createNewGoBoard(tableStakes);
}
return (selectedBoardId, board);
}
/// @dev Starts the game and sets everything up for the match
/// @param board The board to update with the starting data
/// @param boardId The board's Id
function startBoardGame(GoBoard storage board, uint boardId) private {
// Make sure both players are present
require(board.blackAddress != 0 && board.whiteAddress != 0);
// The black is always the first player in GO
board.nextTurnColor = PlayerColor.Black;
// Save the game start time and set the game status to in progress
updateBoardStatus(board, boardId, BoardStatus.InProgress);
}
/// @dev Handles the registration of a player to a board
/// @param board The board to update with the starting data
/// @param paidAmount The amount the player paid to start playing (will be added to the board balance)
/// @return true if the game should be started
function addPlayerToBoard(GoBoard storage board, uint paidAmount) private returns(bool) {
// Make suew we are still waitinf for opponent (otherwise we can't add players)
bool shouldStartTheGame = false;
require(board.status == BoardStatus.WaitForOpponent);
// Check that the player isn't already on the board, otherwise they would pay twice for a single board... :(
require(!isPlayerOnBoard(board, msg.sender));
// We always add the black player first as they created the board
if (board.blackAddress == 0) {
board.blackAddress = msg.sender;
// If we have a black player, add the white player
} else if (board.whiteAddress == 0) {
board.whiteAddress = msg.sender;
// Once the white player has been added, we can start the match
shouldStartTheGame = true;
// If both addresses are occuipied and we got here, it's a problem
} else {
revert();
}
// Credit the board with what we know
board.boardBalance += paidAmount;
return shouldStartTheGame;
}
/// @dev Helper function to caclulate how much time a player used since now
/// @param lastUpdate the timestamp of last update of the board
/// @return the number of periods used for this time
function getTimePeriodsUsed(uint lastUpdate) private view returns(uint8) {
return uint8(now.sub(lastUpdate).div(PLAYER_TURN_SINGLE_PERIOD));
}
/// @notice Convinience function to help present how much time a player has.
/// @param boardId the board to check.
/// @param color the color of the player to check.
/// @return The number of time periods the player has, the number of seconds per each period and the total number of seconds for convinience.
function getPlayerRemainingTime(uint boardId, PlayerColor color) view external returns (uint, uint, uint) {
GoBoard storage board = allBoards[boardId];
// Always verify we can act
require(board.status == BoardStatus.InProgress);
// Get the total remaining time:
uint timePeriods = getPlayerTimePeriods(board, color);
uint totalTimeRemaining = timePeriods * PLAYER_TURN_SINGLE_PERIOD;
// If this is the acting player
if (color == board.nextTurnColor) {
// Calc time periods for player
uint timePeriodsUsed = getTimePeriodsUsed(board.lastUpdate);
if (timePeriods > timePeriodsUsed) {
timePeriods -= timePeriodsUsed;
} else {
timePeriods = 0;
}
// Calc total time remaining for player
uint timeUsed = (now - board.lastUpdate);
// Safely reduce the time used
if (totalTimeRemaining > timeUsed) {
totalTimeRemaining -= timeUsed;
// A player can't have less than zero time to act
} else {
totalTimeRemaining = 0;
}
}
return (timePeriods, PLAYER_TURN_SINGLE_PERIOD, totalTimeRemaining);
}
/// @dev After a player acted we might need to reduce the number of remaining time periods.
/// @param board The board the player acted upon.
/// @param color the color of the player that acted.
/// @param timePeriodsUsed the number of periods the player used.
function updatePlayerTimePeriods(GoBoard storage board, PlayerColor color, uint8 timePeriodsUsed) internal {
// Reduce from the black player
if (color == PlayerColor.Black) {
// The player can't have less than 0 periods remaining
board.blackPeriodsRemaining = board.blackPeriodsRemaining > timePeriodsUsed ? board.blackPeriodsRemaining - timePeriodsUsed : 0;
// Reduce from the white player
} else if (color == PlayerColor.White) {
// The player can't have less than 0 periods remaining
board.whitePeriodsRemaining = board.whitePeriodsRemaining > timePeriodsUsed ? board.whitePeriodsRemaining - timePeriodsUsed : 0;
// We are not supposed to get here
} else {
revert();
}
}
/// @dev Helper function to access the time periods of a player in a board.
/// @param board The board to check.
/// @param color the color of the player to check.
/// @return The number of time periods remaining for this player
function getPlayerTimePeriods(GoBoard storage board, PlayerColor color) internal view returns (uint8) {
// For the black player
if (color == PlayerColor.Black) {
return board.blackPeriodsRemaining;
// For the white player
} else if (color == PlayerColor.White) {
return board.whitePeriodsRemaining;
// We are not supposed to get here
} else {
revert();
}
}
/// @notice The main function to split game revenues, this is triggered only by changing the game's state
/// to one of the ending game states.
/// We make sure this board has a balance and that it's only running once a board game has ended
/// We used numbers for easier read through as this function is critical for the revenue sharing model
/// @param board The board the credit will come from.
function creditBoardGameRevenues(GoBoard storage board) private boardGameEnded(board) boardNotPaid(board) {
// Get the shares from the globals
uint updatedHostShare = HOST_SHARE;
uint updatedLoserShare = 0;
// Start accumulating funds for each participant and EthernalGo's CFO
uint amountBlack = 0;
uint amountWhite = 0;
uint amountCFO = 0;
uint fullAmount = 1000;
// Incentivize resigns and quick end-games for the loser
if (board.status == BoardStatus.BlackWin || board.status == BoardStatus.WhiteWin) {
// In case the game ended honorably (not by time out), the loser will get credit (from the CFO's share)
if (board.isHonorableLoss) {
// Reduce the credit from the CFO
updatedHostShare = HOST_SHARE - HONORABLE_LOSS_BONUS;
// Add to the loser share
updatedLoserShare = HONORABLE_LOSS_BONUS;
}
// If black won
if (board.status == BoardStatus.BlackWin) {
// Black should get the winner share
amountBlack = board.boardBalance.mul(WINNER_SHARE).div(fullAmount);
// White player should get the updated loser share (with or without the bonus)
amountWhite = board.boardBalance.mul(updatedLoserShare).div(fullAmount);
}
// If white won
if (board.status == BoardStatus.WhiteWin) {
// White should get the winner share
amountWhite = board.boardBalance.mul(WINNER_SHARE).div(fullAmount);
// Black should get the updated loser share (with or without the bonus)
amountBlack = board.boardBalance.mul(updatedLoserShare).div(fullAmount);
}
// The CFO should get the updates share if the game ended as expected
amountCFO = board.boardBalance.mul(updatedHostShare).div(fullAmount);
}
// If the match ended in a draw or it was cancelled
if (board.status == BoardStatus.Draw || board.status == BoardStatus.Canceled) {
// The CFO is not taking a share from draw or a cancelled match
amountCFO = 0;
// If the white player was on board, we should split the balance in half
if (board.whiteAddress != 0) {
// Each player gets half of the balance
amountBlack = board.boardBalance.div(2);
amountWhite = board.boardBalance.div(2);
// If there was only the black player, they should get the entire balance
} else {
amountBlack = board.boardBalance;
}
}
// Make sure we are going to split the entire amount and nothing gets left behind
assert(amountBlack + amountWhite + amountCFO == board.boardBalance);
// Reset the balance
board.boardBalance = 0;
// Async sends to the participants (this means each participant will be required to withdraw funds)
asyncSend(board.blackAddress, amountBlack);
asyncSend(board.whiteAddress, amountWhite);
asyncSend(CFO, amountCFO);
}
/// @dev withdraw accumulated balance, called by payee.
function withdrawPayments() public {
// Call Zeppelin's withdrawPayments
super.withdrawPayments();
// Send an event
PlayerWithdrawnBalance(msg.sender);
}
}
// File: contracts/GoGameLogic.sol
/// @title The actual game logic for EthernalGo - setting stones, capturing, etc.
/// @author https://www.EthernalGo.com
contract GoGameLogic is GoBoardMetaDetails {
/// @dev The StoneAddedToBoard event is fired when a new stone is added to the board,
/// and includes the board Id, stone color, row & column. This event will fire even if it was a suicide stone.
event StoneAddedToBoard(uint boardId, PlayerColor color, uint8 row, uint8 col);
/// @dev The PlayerPassedTurn event is fired when a player passes turn
/// and includes the board Id, color.
event PlayerPassedTurn(uint boardId, PlayerColor color);
/// @dev Updating the player's time periods left, according to the current time - board last update time.
/// If the player does not have enough time and chose to act, the game will end and the player will lose.
/// @param board is the relevant board.
/// @param boardId is the board's Id.
/// @param color is the color of the player we want to update.
/// @return true if the player can continue playing, otherwise false.
function updatePlayerTime(GoBoard storage board, uint boardId, PlayerColor color) private returns(bool) {
// Verify that the board is in progress and that it's the current player
require(board.status == BoardStatus.InProgress && board.nextTurnColor == color);
// Calculate time periods used by the player
uint timePeriodsUsed = uint(now.sub(board.lastUpdate).div(PLAYER_TURN_SINGLE_PERIOD));
// Subtract time periods if needed
if (timePeriodsUsed > 0) {
// Can't spend more than MAX_UINT8
updatePlayerTimePeriods(board, color, timePeriodsUsed > MAX_UINT8 ? MAX_UINT8 : uint8(timePeriodsUsed));
// The player losses when there aren't any time periods left
if (getPlayerTimePeriods(board, color) == 0) {
playerLost(board, boardId, color);
return false;
}
}
return true;
}
/// @notice Updates the board status according to the players score.
/// Can only be called when the board is in a 'waitingToResolve' status.
/// @param boardId is the board to check and update
function checkVictoryByScore(uint boardId) external boardWaitingToResolve(boardId) {
uint8 blackScore;
uint8 whiteScore;
// Get the players' score
(blackScore, whiteScore) = calculateBoardScore(boardId);
// Default to Draw
BoardStatus status = BoardStatus.Draw;
// If black's score is bigger than white's score, black is the winner
if (blackScore > whiteScore) {
status = BoardStatus.BlackWin;
// If white's score is bigger, white is the winner
} else if (whiteScore > blackScore) {
status = BoardStatus.WhiteWin;
}
// Update the board's status
updateBoardStatus(boardId, status);
}
/// @notice Performs a pass action on a psecific board, only by the current active color player.
/// @param boardId is the board to perform pass on.
function passTurn(uint boardId) external {
// Get the board & player
GoBoard storage board = allBoards[boardId];
PlayerColor activeColor = getPlayerColor(board, msg.sender);
// Verify the player can act
require(board.status == BoardStatus.InProgress && board.nextTurnColor == activeColor);
// Check if this player can act
if (updatePlayerTime(board, boardId, activeColor)) {
// If it's the second straight pass, the game is over
if (board.didPassPrevTurn) {
// Finishing the game like this is considered honorable
board.isHonorableLoss = true;
// On second pass, the board status changes to 'WaitingToResolve'
updateBoardStatus(board, boardId, BoardStatus.WaitingToResolve);
// If it's the first pass, we can simply continue
} else {
// Move to the next player, flag that it was a pass action
nextTurn(board);
board.didPassPrevTurn = true;
// Notify the player passed turn
PlayerPassedTurn(boardId, activeColor);
}
}
}
/// @notice Resigns a player from a specific board, can get called by either player on the board.
/// @param boardId is the board to resign from.
function resignFromMatch(uint boardId) external {
// Get the board, make sure it's in progress
GoBoard storage board = allBoards[boardId];
require(board.status == BoardStatus.InProgress);
// Get the sender's color
PlayerColor activeColor = getPlayerColor(board, msg.sender);
// Finishing the game like this is considered honorable
board.isHonorableLoss = true;
// Set that color as the losing player
playerLost(board, boardId, activeColor);
}
/// @notice Claiming the current acting player on the board is out of time, thus losses the game.
/// @param boardId is the board to claim it on.
function claimActingPlayerOutOfTime(uint boardId) external {
// Get the board, make sure it's in progress
GoBoard storage board = allBoards[boardId];
require(board.status == BoardStatus.InProgress);
// Get the acting player color
PlayerColor actingPlayerColor = getNextTurnColor(boardId);
// Calculate remaining allowed time for the acting player
uint playerTimeRemaining = PLAYER_TURN_SINGLE_PERIOD * getPlayerTimePeriods(board, actingPlayerColor);
// If the player doesn't have enough time left, the player losses
if (playerTimeRemaining < now - board.lastUpdate) {
playerLost(board, boardId, actingPlayerColor);
}
}
/// @dev Update a board status with a losing color
/// @param board is the board to update.
/// @param boardId is the board's Id.
/// @param color is the losing player's color.
function playerLost(GoBoard storage board, uint boardId, PlayerColor color) private {
// If black is the losing color, white wins
if (color == PlayerColor.Black) {
updateBoardStatus(board, boardId, BoardStatus.WhiteWin);
// If white is the losing color, black wins
} else if (color == PlayerColor.White) {
updateBoardStatus(board, boardId, BoardStatus.BlackWin);
// There's an error, revert
} else {
revert();
}
}
/// @dev Internally used to move to the next turn, by switching sides and updating the board last update time.
/// @param board is the board to update.
function nextTurn(GoBoard storage board) private {
// Switch sides
board.nextTurnColor = board.nextTurnColor == PlayerColor.Black ? PlayerColor.White : PlayerColor.Black;
// Last update time
board.lastUpdate = now;
}
/// @notice Adding a stone to a specific board and position (row & col).
/// Requires the board to be in progress, that the caller is the acting player,
/// and that the spot on the board is empty.
/// @param boardId is the board to add the stone to.
/// @param row is the row for the new stone.
/// @param col is the column for the new stone.
function addStoneToBoard(uint boardId, uint8 row, uint8 col) external {
// Get the board & sender's color
GoBoard storage board = allBoards[boardId];
PlayerColor activeColor = getPlayerColor(board, msg.sender);
// Verify the player can act
require(board.status == BoardStatus.InProgress && board.nextTurnColor == activeColor);
// Calculate the position
uint8 position = row * BOARD_ROW_SIZE + col;
// Check that it's an empty spot
require(board.positionToColor[position] == 0);
// Update the player timeout (if the player doesn't have time left, discontinue)
if (updatePlayerTime(board, boardId, activeColor)) {
// Set the stone on the board
board.positionToColor[position] = uint8(activeColor);
// Run capture / suidice logic
updateCaptures(board, position, uint8(activeColor));
// Next turn logic
nextTurn(board);
// Clear the pass flag
if (board.didPassPrevTurn) {
board.didPassPrevTurn = false;
}
// Fire the event
StoneAddedToBoard(boardId, activeColor, row, col);
}
}
/// @notice Returns a board's row details, specifies which color occupies which cell in that row.
/// @dev It returns a row and not the entire board because some nodes might fail to return arrays larger than ~50.
/// @param boardId is the board to inquire.
/// @param row is the row to get details on.
/// @return an array that contains the colors occupying each cell in that row.
function getBoardRowDetails(uint boardId, uint8 row) external view returns (uint8[BOARD_ROW_SIZE]) {
// The array to return
uint8[BOARD_ROW_SIZE] memory rowToReturn;
// For all columns, calculate the position and get the current status
for (uint8 col = 0; col < BOARD_ROW_SIZE; col++) {
uint8 position = row * BOARD_ROW_SIZE + col;
rowToReturn[col] = allBoards[boardId].positionToColor[position];
}
// Return the array
return (rowToReturn);
}
/// @notice Returns the current color of a specific position in a board.
/// @param boardId is the board to inquire.
/// @param row is part of the position to get details on.
/// @param col is part of the position to get details on.
/// @return the color occupying that position.
function getBoardSingleSpaceDetails(uint boardId, uint8 row, uint8 col) external view returns (uint8) {
uint8 position = row * BOARD_ROW_SIZE + col;
return allBoards[boardId].positionToColor[position];
}
/// @dev Calcultes whether a position captures an enemy group, or whether it's a suicide.
/// Updates the board accoridngly (clears captured groups, or the suiciding stone).
/// @param board the board to check and update
/// @param position the position of the new stone
/// @param positionColor the color of the new stone (this param is sent to spare another reading op)
function updateCaptures(GoBoard storage board, uint8 position, uint8 positionColor) private {
// Group positions, used later
uint8[BOARD_SIZE] memory group;
// Is group captured, or free
bool isGroupCaptured;
// In order to save gas, we check suicide only if the position is fully surrounded and doesn't capture enemy groups
bool shouldCheckSuicide = true;
// Get the position's adjacent cells
uint8[MAX_ADJACENT_CELLS] memory adjacentArray = getAdjacentCells(position);
// Run as long as there an adjacent cell, or until we reach the end of the array
for (uint8 currAdjacentIndex = 0; currAdjacentIndex < MAX_ADJACENT_CELLS && adjacentArray[currAdjacentIndex] < MAX_UINT8; currAdjacentIndex++) {
// Get the adjacent cell's color
uint8 currColor = board.positionToColor[adjacentArray[currAdjacentIndex]];
// If the enemy's color
if (currColor != 0 && currColor != positionColor) {
// Get the group's info
(group, isGroupCaptured) = getGroup(board, adjacentArray[currAdjacentIndex], currColor);
// Captured a group
if (isGroupCaptured) {
// Clear the group from the board
for (uint8 currGroupIndex = 0; currGroupIndex < BOARD_SIZE && group[currGroupIndex] < MAX_UINT8; currGroupIndex++) {
board.positionToColor[group[currGroupIndex]] = 0;
}
// Shouldn't check suicide
shouldCheckSuicide = false;
}
// There's an empty adjacent cell
} else if (currColor == 0) {
// Shouldn't check suicide
shouldCheckSuicide = false;
}
}
// Detect suicide if needed
if (shouldCheckSuicide) {
// Get the new stone's surrounding group
(group, isGroupCaptured) = getGroup(board, position, positionColor);
// If the group is captured, it's a suicide move, remove it
if (isGroupCaptured) {
// Clear added stone
board.positionToColor[position] = 0;
}
}
}
/// @dev Internally used to set a flag in a shrinked board array (used to save gas costs).
/// @param visited the array to update.
/// @param position the position on the board we want to flag.
/// @param flag the flag we want to set (either 1 or 2).
function setFlag(uint8[SHRINKED_BOARD_SIZE] visited, uint8 position, uint8 flag) private pure {
visited[position / 4] |= flag << ((position % 4) * 2);
}
/// @dev Internally used to check whether a flag in a shrinked board array is set.
/// @param visited the array to check.
/// @param position the position on the board we want to check.
/// @param flag the flag we want to check (either 1 or 2).
/// @return true if that flag is set, false otherwise.
function isFlagSet(uint8[SHRINKED_BOARD_SIZE] visited, uint8 position, uint8 flag) private pure returns (bool) {
return (visited[position / 4] & (flag << ((position % 4) * 2)) > 0);
}
// Get group visited flags
uint8 constant FLAG_POSITION_WAS_IN_STACK = 1;
uint8 constant FLAG_DID_VISIT_POSITION = 2;
/// @dev Gets a group starting from the position & color sent. In order for a stone to be part of the group,
/// it must match the original stone's color, and be connected to it - either directly, or through adjacent cells.
/// A group is captured if there aren't any empty cells around it.
/// The function supports both returning colored groups - white/black, and empty groups (for that case, isGroupCaptured isn't relevant).
/// @param board the board to check and update
/// @param position the position of the starting stone
/// @param positionColor the color of the starting stone (this param is sent to spare another reading op)
/// @return an array that contains the positions of the group,
/// a boolean that specifies whether the group is captured or not.
/// In order to save gas, if a group isn't captured, the array might not contain the enitre group.
function getGroup(GoBoard storage board, uint8 position, uint8 positionColor) private view returns (uint8[BOARD_SIZE], bool isGroupCaptured) {
// The return array, and its size
uint8[BOARD_SIZE] memory groupPositions;
uint8 groupSize = 0;
// Flagging visited locations
uint8[SHRINKED_BOARD_SIZE] memory visited;
// Stack of waiting positions, the first position to check is the sent position
uint8[BOARD_SIZE] memory stack;
stack[0] = position;
uint8 stackSize = 1;
// That position was added to the stack
setFlag(visited, position, FLAG_POSITION_WAS_IN_STACK);
// Run as long as there are positions in the stack
while (stackSize > 0) {
// Take the last position and clear it
position = stack[--stackSize];
stack[stackSize] = 0;
// Only if we didn't visit that stone before
if (!isFlagSet(visited, position, FLAG_DID_VISIT_POSITION)) {
// Set the flag so we won't visit it again
setFlag(visited, position, FLAG_DID_VISIT_POSITION);
// Add that position to the return value
groupPositions[groupSize++] = position;
// Get that position adjacent cells
uint8[MAX_ADJACENT_CELLS] memory adjacentArray = getAdjacentCells(position);
// Run over the adjacent cells
for (uint8 currAdjacentIndex = 0; currAdjacentIndex < MAX_ADJACENT_CELLS && adjacentArray[currAdjacentIndex] < MAX_UINT8; currAdjacentIndex++) {
// Get the current adjacent cell color
uint8 currColor = board.positionToColor[adjacentArray[currAdjacentIndex]];
// If it's the same color as the original position color
if (currColor == positionColor) {
// Add that position to the stack
if (!isFlagSet(visited, adjacentArray[currAdjacentIndex], FLAG_POSITION_WAS_IN_STACK)) {
stack[stackSize++] = adjacentArray[currAdjacentIndex];
setFlag(visited, adjacentArray[currAdjacentIndex], FLAG_POSITION_WAS_IN_STACK);
}
// If that position is empty, the group isn't captured, no need to continue running
} else if (currColor == 0) {
return (groupPositions, false);
}
}
}
}
// Flag the end of the group array only if needed
if (groupSize < BOARD_SIZE) {
groupPositions[groupSize] = MAX_UINT8;
}
// The group is captured, return it
return (groupPositions, true);
}
/// The max number of adjacent cells is 4
uint8 constant MAX_ADJACENT_CELLS = 4;
/// @dev returns the adjacent positions for a given position.
/// @param position to get its adjacents.
/// @return the adjacent positions array, filled with MAX_INT8 in case there aren't 4 adjacent positions.
function getAdjacentCells(uint8 position) private pure returns (uint8[MAX_ADJACENT_CELLS]) {
// Init the return array and current index
uint8[MAX_ADJACENT_CELLS] memory returnCells = [MAX_UINT8, MAX_UINT8, MAX_UINT8, MAX_UINT8];
uint8 adjacentCellsIndex = 0;
// Set the up position, if relevant
if (position / BOARD_ROW_SIZE > 0) {
returnCells[adjacentCellsIndex++] = position - BOARD_ROW_SIZE;
}
// Set the down position, if relevant
if (position / BOARD_ROW_SIZE < BOARD_ROW_SIZE - 1) {
returnCells[adjacentCellsIndex++] = position + BOARD_ROW_SIZE;
}
// Set the left position, if relevant
if (position % BOARD_ROW_SIZE > 0) {
returnCells[adjacentCellsIndex++] = position - 1;
}
// Set the right position, if relevant
if (position % BOARD_ROW_SIZE < BOARD_ROW_SIZE - 1) {
returnCells[adjacentCellsIndex++] = position + 1;
}
return returnCells;
}
/// @notice Calculates the board's score, using area scoring.
/// @param boardId the board to calculate the score for.
/// @return blackScore & whiteScore, the players' scores.
function calculateBoardScore(uint boardId) public view returns (uint8 blackScore, uint8 whiteScore) {
GoBoard storage board = allBoards[boardId];
uint8[BOARD_SIZE] memory boardEmptyGroups;
uint8 maxEmptyGroupId;
(boardEmptyGroups, maxEmptyGroupId) = getBoardEmptyGroups(board);
uint8[BOARD_SIZE] memory groupsSize;
uint8[BOARD_SIZE] memory groupsState;
blackScore = 0;
whiteScore = 0;
// Count stones and find empty territories
for (uint8 position = 0; position < BOARD_SIZE; position++) {
if (PlayerColor(board.positionToColor[position]) == PlayerColor.Black) {
blackScore++;
} else if (PlayerColor(board.positionToColor[position]) == PlayerColor.White) {
whiteScore++;
} else {
uint8 groupId = boardEmptyGroups[position];
groupsSize[groupId]++;
// Checking is needed only if we didn't find the group is adjacent to the two colors already
if ((groupsState[groupId] & uint8(PlayerColor.Black) == 0) || (groupsState[groupId] & uint8(PlayerColor.White) == 0)) {
uint8[MAX_ADJACENT_CELLS] memory adjacentArray = getAdjacentCells(position);
// Check adjacent cells to mark the group's bounderies
for (uint8 currAdjacentIndex = 0; currAdjacentIndex < MAX_ADJACENT_CELLS && adjacentArray[currAdjacentIndex] < MAX_UINT8; currAdjacentIndex++) {
// Check if the group has a black boundry
if ((PlayerColor(board.positionToColor[adjacentArray[currAdjacentIndex]]) == PlayerColor.Black) &&
(groupsState[groupId] & uint8(PlayerColor.Black) == 0)) {
groupsState[groupId] |= uint8(PlayerColor.Black);
// Check if the group has a white boundry
} else if ((PlayerColor(board.positionToColor[adjacentArray[currAdjacentIndex]]) == PlayerColor.White) &&
(groupsState[groupId] & uint8(PlayerColor.White) == 0)) {
groupsState[groupId] |= uint8(PlayerColor.White);
}
}
}
}
}
// Add territories size to the relevant player
for (uint8 currGroupId = 1; currGroupId < maxEmptyGroupId; currGroupId++) {
// Check if it's a black territory
if ((groupsState[currGroupId] & uint8(PlayerColor.Black) > 0) &&
(groupsState[currGroupId] & uint8(PlayerColor.White) == 0)) {
blackScore += groupsSize[currGroupId];
// Check if it's a white territory
} else if ((groupsState[currGroupId] & uint8(PlayerColor.White) > 0) &&
(groupsState[currGroupId] & uint8(PlayerColor.Black) == 0)) {
whiteScore += groupsSize[currGroupId];
}
}
return (blackScore, whiteScore);
}
/// @dev IDs empty groups on the board.
/// @param board the board to map.
/// @return an array that contains the mapped empty group ids, and the max empty group id
function getBoardEmptyGroups(GoBoard storage board) private view returns (uint8[BOARD_SIZE], uint8) {
uint8[BOARD_SIZE] memory boardEmptyGroups;
uint8 nextGroupId = 1;
for (uint8 position = 0; position < BOARD_SIZE; position++) {
PlayerColor currPositionColor = PlayerColor(board.positionToColor[position]);
if ((currPositionColor == PlayerColor.None) && (boardEmptyGroups[position] == 0)) {
uint8[BOARD_SIZE] memory emptyGroup;
bool isGroupCaptured;
(emptyGroup, isGroupCaptured) = getGroup(board, position, 0);
for (uint8 currGroupIndex = 0; currGroupIndex < BOARD_SIZE && emptyGroup[currGroupIndex] < MAX_UINT8; currGroupIndex++) {
boardEmptyGroups[emptyGroup[currGroupIndex]] = nextGroupId;
}
nextGroupId++;
}
}
return (boardEmptyGroups, nextGroupId);
}
} | @dev Internally used to set a flag in a shrinked board array (used to save gas costs). @param visited the array to update. @param position the position on the board we want to flag. @param flag the flag we want to set (either 1 or 2). | function setFlag(uint8[SHRINKED_BOARD_SIZE] visited, uint8 position, uint8 flag) private pure {
visited[position / 4] |= flag << ((position % 4) * 2);
}
| 941,575 | [
1,
21843,
1230,
1399,
358,
444,
279,
2982,
316,
279,
17697,
329,
11094,
526,
261,
3668,
358,
1923,
16189,
22793,
2934,
225,
9711,
326,
526,
358,
1089,
18,
225,
1754,
326,
1754,
603,
326,
11094,
732,
2545,
358,
2982,
18,
225,
2982,
326,
2982,
732,
2545,
358,
444,
261,
73,
2927,
404,
578,
576,
2934,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
4678,
12,
11890,
28,
63,
2664,
54,
8476,
2056,
67,
5315,
8085,
67,
4574,
65,
9711,
16,
2254,
28,
1754,
16,
2254,
28,
2982,
13,
3238,
16618,
288,
203,
3639,
9711,
63,
3276,
342,
1059,
65,
5626,
2982,
2296,
14015,
3276,
738,
1059,
13,
380,
576,
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
] |
pragma solidity ^0.4.24;
// 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 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;
}
}
// File: openzeppelin-solidity/contracts/ownership/HasNoContracts.sol
/**
* @title Contracts that should not own Contracts
* @author Remco Bloemen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c7e69616f634c3e">[email protected]</a>π.com>
* @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner
* of this contract to reclaim ownership of the contracts.
*/
contract HasNoContracts is Ownable{
/**
* @dev Reclaim ownership of Ownable contracts
* @param contractAddr The address of the Ownable to be reclaimed.
*/
function reclaimContract(address contractAddr) external onlyOwner {
Ownable contractInst = Ownable(contractAddr);
contractInst.transferOwnership(owner);
}
}
// File: openzeppelin-solidity/contracts/ownership/HasNoEther.sol
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="25574048464a6517">[email protected]</a>π.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this Ether.
* @notice Ether can still be sent to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by setting a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
owner.transfer(address(this).balance);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @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);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* 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 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol
/**
* @title Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
// File: openzeppelin-solidity/contracts/ownership/HasNoTokens.sol
/**
* @title Contracts that should not own Tokens
* @author Remco Bloemen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a584f4749456a18">[email protected]</a>π.com>
* @dev This blocks incoming ERC223 tokens to prevent accidental loss of tokens.
* Should tokens (any ERC20Basic compatible) end up in the contract, it allows the
* owner to reclaim the tokens.
*/
contract HasNoTokens is CanReclaimToken {
/**
* @dev Reject all ERC223 compatible tokens
* @param _from address The address that is transferring the tokens
* @param _value uint256 the amount of the specified token
* @param _data Bytes The data passed from the caller.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) external pure {
_from;
_value;
_data;
revert();
}
}
// File: openzeppelin-solidity/contracts/ownership/NoOwner.sol
/**
* @title Base contract for contracts that should not own things.
* @author Remco Bloemen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7200171f111d3240">[email protected]</a>π.com>
* @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or
* Owned contracts. See respective base contracts for details.
*/
contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts {
}
// 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) {
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;
}
}
// File: openzeppelin-solidity/contracts/ownership/Claimable.sol
/**
* @title Claimable
* @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);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/BalanceSheet.sol
// A wrapper around the balanceOf mapping.
contract BalanceSheet is Claimable {
using SafeMath for uint256;
mapping(address => uint256) public balanceOf;
function addBalance(address _addr, uint256 _value) public onlyOwner {
balanceOf[_addr] = balanceOf[_addr].add(_value);
}
function subBalance(address _addr, uint256 _value) public onlyOwner {
balanceOf[_addr] = balanceOf[_addr].sub(_value);
}
function setBalance(address _addr, uint256 _value) public onlyOwner {
balanceOf[_addr] = _value;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, Claimable {
using SafeMath for uint256;
BalanceSheet public balances;
uint256 totalSupply_;
function setBalanceSheet(address sheet) external onlyOwner {
balances = BalanceSheet(sheet);
balances.claimOwnership();
}
/**
* @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) {
transferAllArgsNoAllowance(msg.sender, _to, _value);
return true;
}
function transferAllArgsNoAllowance(address _from, address _to, uint256 _value) internal {
require(_to != address(0));
require(_from != address(0));
require(_value <= balances.balanceOf(_from));
// SafeMath.sub will throw if there is not enough balance.
balances.subBalance(_from, _value);
balances.addBalance(_to, _value);
emit Transfer(_from, _to, _value);
}
/**
* @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.balanceOf(_owner);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken{
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances.balanceOf(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.subBalance(burner, _value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(burner, _value);
emit Transfer(burner, address(0), _value);
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: contracts/AllowanceSheet.sol
// A wrapper around the allowanceOf mapping.
contract AllowanceSheet is Claimable {
using SafeMath for uint256;
mapping(address => mapping(address => uint256)) public allowanceOf;
function addAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowanceOf[_tokenHolder][_spender] = allowanceOf[_tokenHolder][_spender].add(_value);
}
function subAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowanceOf[_tokenHolder][_spender] = allowanceOf[_tokenHolder][_spender].sub(_value);
}
function setAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowanceOf[_tokenHolder][_spender] = _value;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
contract StandardToken is ERC20, BasicToken {
AllowanceSheet public allowances;
function setAllowanceSheet(address sheet) external onlyOwner {
allowances = AllowanceSheet(sheet);
allowances.claimOwnership();
}
/**
* @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) {
transferAllArgsYesAllowance(_from, _to, _value, msg.sender);
return true;
}
function transferAllArgsYesAllowance(address _from, address _to, uint256 _value, address spender) internal {
require(_value <= allowances.allowanceOf(_from, spender));
allowances.subAllowance(_from, spender, _value);
transferAllArgsNoAllowance(_from, _to, _value);
}
/**
* @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) {
approveAllArgs(_spender, _value, msg.sender);
return true;
}
function approveAllArgs(address _spender, uint256 _value, address _tokenHolder) internal {
allowances.setAllowance(_tokenHolder, _spender, _value);
emit Approval(_tokenHolder, _spender, _value);
}
/**
* @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 allowances.allowanceOf(_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) {
increaseApprovalAllArgs(_spender, _addedValue, msg.sender);
return true;
}
function increaseApprovalAllArgs(address _spender, uint _addedValue, address tokenHolder) internal {
allowances.addAllowance(tokenHolder, _spender, _addedValue);
emit Approval(tokenHolder, _spender, allowances.allowanceOf(tokenHolder, _spender));
}
/**
* @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) {
decreaseApprovalAllArgs(_spender, _subtractedValue, msg.sender);
return true;
}
function decreaseApprovalAllArgs(address _spender, uint _subtractedValue, address tokenHolder) internal {
uint oldValue = allowances.allowanceOf(tokenHolder, _spender);
if (_subtractedValue > oldValue) {
allowances.setAllowance(tokenHolder, _spender, 0);
} else {
allowances.subAllowance(tokenHolder, _spender, _subtractedValue);
}
emit Approval(tokenHolder, _spender, allowances.allowanceOf(tokenHolder, _spender));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/PausableToken.sol
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable{
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// File: contracts/AddressList.sol
contract AddressList is Claimable {
string public name;
mapping(address => bool) public onList;
constructor(string _name, bool nullValue) public {
name = _name;
onList[0x0] = nullValue;
}
event ChangeWhiteList(address indexed to, bool onList);
// Set whether _to is on the list or not. Whether 0x0 is on the list
// or not cannot be set here - it is set once and for all by the constructor.
function changeList(address _to, bool _onList) onlyOwner public {
require(_to != 0x0);
if (onList[_to] != _onList) {
onList[_to] = _onList;
emit ChangeWhiteList(_to, _onList);
}
}
}
// File: contracts/DelegateERC20.sol
contract DelegateERC20 {
function delegateTotalSupply() public view returns (uint256);
function delegateBalanceOf(address who) public view returns (uint256);
function delegateTransfer(address to, uint256 value, address origSender) public returns (bool);
function delegateAllowance(address owner, address spender) public view returns (uint256);
function delegateTransferFrom(address from, address to, uint256 value, address origSender) public returns (bool);
function delegateApprove(address spender, uint256 value, address origSender) public returns (bool);
function delegateIncreaseApproval(address spender, uint addedValue, address origSender) public returns (bool);
function delegateDecreaseApproval(address spender, uint subtractedValue, address origSender) public returns (bool);
}
// File: contracts/CanDelegate.sol
contract CanDelegate is StandardToken {
// If this contract needs to be upgraded, the new contract will be stored
// in 'delegate' and any ERC20 calls to this contract will be delegated to that one.
DelegateERC20 public delegate;
event DelegateToNewContract(address indexed newContract);
// Can undelegate by passing in newContract = address(0)
function delegateToNewContract(DelegateERC20 newContract) public onlyOwner {
delegate = newContract;
emit DelegateToNewContract(newContract);
}
// If a delegate has been designated, all ERC20 calls are forwarded to it
function transfer(address to, uint256 value) public returns (bool) {
if (delegate == address(0)) {
return super.transfer(to, value);
} else {
return delegate.delegateTransfer(to, value, msg.sender);
}
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
if (delegate == address(0)) {
return super.transferFrom(from, to, value);
} else {
return delegate.delegateTransferFrom(from, to, value, msg.sender);
}
}
function balanceOf(address who) public view returns (uint256) {
if (delegate == address(0)) {
return super.balanceOf(who);
} else {
return delegate.delegateBalanceOf(who);
}
}
function approve(address spender, uint256 value) public returns (bool) {
if (delegate == address(0)) {
return super.approve(spender, value);
} else {
return delegate.delegateApprove(spender, value, msg.sender);
}
}
function allowance(address _owner, address spender) public view returns (uint256) {
if (delegate == address(0)) {
return super.allowance(_owner, spender);
} else {
return delegate.delegateAllowance(_owner, spender);
}
}
function totalSupply() public view returns (uint256) {
if (delegate == address(0)) {
return super.totalSupply();
} else {
return delegate.delegateTotalSupply();
}
}
function increaseApproval(address spender, uint addedValue) public returns (bool) {
if (delegate == address(0)) {
return super.increaseApproval(spender, addedValue);
} else {
return delegate.delegateIncreaseApproval(spender, addedValue, msg.sender);
}
}
function decreaseApproval(address spender, uint subtractedValue) public returns (bool) {
if (delegate == address(0)) {
return super.decreaseApproval(spender, subtractedValue);
} else {
return delegate.delegateDecreaseApproval(spender, subtractedValue, msg.sender);
}
}
}
// File: contracts/StandardDelegate.sol
contract StandardDelegate is StandardToken, DelegateERC20 {
address public delegatedFrom;
modifier onlySender(address source) {
require(msg.sender == source);
_;
}
function setDelegatedFrom(address addr) onlyOwner public {
delegatedFrom = addr;
}
// All delegate ERC20 functions are forwarded to corresponding normal functions
function delegateTotalSupply() public view returns (uint256) {
return totalSupply();
}
function delegateBalanceOf(address who) public view returns (uint256) {
return balanceOf(who);
}
function delegateTransfer(address to, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) {
transferAllArgsNoAllowance(origSender, to, value);
return true;
}
function delegateAllowance(address owner, address spender) public view returns (uint256) {
return allowance(owner, spender);
}
function delegateTransferFrom(address from, address to, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) {
transferAllArgsYesAllowance(from, to, value, origSender);
return true;
}
function delegateApprove(address spender, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) {
approveAllArgs(spender, value, origSender);
return true;
}
function delegateIncreaseApproval(address spender, uint addedValue, address origSender) onlySender(delegatedFrom) public returns (bool) {
increaseApprovalAllArgs(spender, addedValue, origSender);
return true;
}
function delegateDecreaseApproval(address spender, uint subtractedValue, address origSender) onlySender(delegatedFrom) public returns (bool) {
decreaseApprovalAllArgs(spender, subtractedValue, origSender);
return true;
}
}
// File: contracts/TrueVND.sol
contract TrueVND is NoOwner, BurnableToken, CanDelegate, StandardDelegate, PausableToken {
string public name = "TrueVND";
string public symbol = "TVND";
uint8 public constant decimals = 18;
AddressList public canReceiveMintWhiteList;
AddressList public canBurnWhiteList;
AddressList public blackList;
AddressList public noFeesList;
address public staker;
uint256 public burnMin = 1000 * 10 ** uint256(decimals);
uint256 public burnMax = 20000000 * 10 ** uint256(decimals);
uint80 public transferFeeNumerator = 8;
uint80 public transferFeeDenominator = 10000;
uint80 public mintFeeNumerator = 0;
uint80 public mintFeeDenominator = 10000;
uint256 public mintFeeFlat = 0;
uint80 public burnFeeNumerator = 0;
uint80 public burnFeeDenominator = 10000;
uint256 public burnFeeFlat = 0;
event ChangeBurnBoundsEvent(uint256 newMin, uint256 newMax);
event Mint(address indexed to, uint256 amount);
event WipedAccount(address indexed account, uint256 balance);
constructor() public {
totalSupply_ = 0;
staker = msg.sender;
}
function setLists(AddressList _canReceiveMintWhiteList, AddressList _canBurnWhiteList, AddressList _blackList, AddressList _noFeesList) onlyOwner public {
canReceiveMintWhiteList = _canReceiveMintWhiteList;
canBurnWhiteList = _canBurnWhiteList;
blackList = _blackList;
noFeesList = _noFeesList;
}
function changeName(string _name, string _symbol) onlyOwner public {
name = _name;
symbol = _symbol;
}
// Burning functions as withdrawing money from the system. The platform will keep track of who burns coins,
// and will send them back the equivalent amount of money (rounded down to the nearest cent).
function burn(uint256 _value) public {
require(canBurnWhiteList.onList(msg.sender));
require(_value >= burnMin);
require(_value <= burnMax);
uint256 fee = payStakingFee(msg.sender, _value, burnFeeNumerator, burnFeeDenominator, burnFeeFlat, 0x0);
uint256 remaining = _value.sub(fee);
super.burn(remaining);
}
// Create _amount new tokens and transfer them to _to.
// Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/MintableToken.sol
function mint(address _to, uint256 _amount) onlyOwner public {
require(canReceiveMintWhiteList.onList(_to));
totalSupply_ = totalSupply_.add(_amount);
balances.addBalance(_to, _amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
payStakingFee(_to, _amount, mintFeeNumerator, mintFeeDenominator, mintFeeFlat, 0x0);
}
// Change the minimum and maximum amount that can be burned at once. Burning
// may be disabled by setting both to 0 (this will not be done under normal
// operation, but we can't add checks to disallow it without losing a lot of
// flexibility since burning could also be as good as disabled
// by setting the minimum extremely high, and we don't want to lock
// in any particular cap for the minimum)
function changeBurnBounds(uint newMin, uint newMax) onlyOwner public {
require(newMin <= newMax);
burnMin = newMin;
burnMax = newMax;
emit ChangeBurnBoundsEvent(newMin, newMax);
}
// A blacklisted address can't call transferFrom
function transferAllArgsYesAllowance(address _from, address _to, uint256 _value, address spender) internal {
require(!blackList.onList(spender));
super.transferAllArgsYesAllowance(_from, _to, _value, spender);
}
// transfer and transferFrom both ultimately call this function, so we
// check blacklist and pay staking fee here.
function transferAllArgsNoAllowance(address _from, address _to, uint256 _value) internal {
require(!blackList.onList(_from));
require(!blackList.onList(_to));
super.transferAllArgsNoAllowance(_from, _to, _value);
payStakingFee(_to, _value, transferFeeNumerator, transferFeeDenominator, burnFeeFlat, _from);
}
function wipeBlacklistedAccount(address account) public onlyOwner {
require(blackList.onList(account));
uint256 oldValue = balanceOf(account);
balances.setBalance(account, 0);
totalSupply_ = totalSupply_.sub(oldValue);
emit WipedAccount(account, oldValue);
}
function payStakingFee(address payer, uint256 value, uint80 numerator, uint80 denominator, uint256 flatRate, address otherParticipant) private returns (uint256) {
if (noFeesList.onList(payer) || noFeesList.onList(otherParticipant)) {
return 0;
}
uint256 stakingFee = value.mul(numerator).div(denominator).add(flatRate);
if (stakingFee > 0) {
super.transferAllArgsNoAllowance(payer, staker, stakingFee);
}
return stakingFee;
}
function changeStakingFees(uint80 _transferFeeNumerator,
uint80 _transferFeeDenominator,
uint80 _mintFeeNumerator,
uint80 _mintFeeDenominator,
uint256 _mintFeeFlat,
uint80 _burnFeeNumerator,
uint80 _burnFeeDenominator,
uint256 _burnFeeFlat) public onlyOwner {
require(_transferFeeDenominator != 0);
require(_mintFeeDenominator != 0);
require(_burnFeeDenominator != 0);
transferFeeNumerator = _transferFeeNumerator;
transferFeeDenominator = _transferFeeDenominator;
mintFeeNumerator = _mintFeeNumerator;
mintFeeDenominator = _mintFeeDenominator;
mintFeeFlat = _mintFeeFlat;
burnFeeNumerator = _burnFeeNumerator;
burnFeeDenominator = _burnFeeDenominator;
burnFeeFlat = _burnFeeFlat;
}
function changeStaker(address newStaker) public onlyOwner {
require(newStaker != address(0));
staker = newStaker;
}
} | * @dev Reclaim all ERC20Basic compatible tokens @param token ERC20Basic The address of the token contract/ | function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
| 10,627,088 | [
1,
426,
14784,
777,
4232,
39,
3462,
8252,
7318,
2430,
225,
1147,
4232,
39,
3462,
8252,
1021,
1758,
434,
326,
1147,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
283,
14784,
1345,
12,
654,
39,
3462,
8252,
1147,
13,
3903,
1338,
5541,
288,
203,
3639,
2254,
5034,
11013,
273,
1147,
18,
12296,
951,
12,
2211,
1769,
203,
3639,
1147,
18,
4626,
5912,
12,
8443,
16,
11013,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x6263e260fF6597180c9538c69aF8284EDeaCEC80/sources/DMEX_Token.sol | Subtract from the sender
| balanceOf[this] -= _value; | 9,282,200 | [
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,
3639,
11013,
951,
63,
2211,
65,
3947,
389,
1132,
31,
2398,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/44787/0xE1659728B249A9C5BD8EC84082aa890A0B8d1eA4/sources/contracts/StarFarm.sol | Deposit LP tokens to MasterChef for STAR allocation.updatePool(_pid); | function deposit(uint256 _pid, uint256 _amount) public {
if (_pid == 0) require(userNFTs[_msgSender()].length == 0, "nft user");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
if (_amountGain > 0) {
uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
if (user.lastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.amount);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount);
user.amount = user.amount.add(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.add(_extraAmount);
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
}
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
| 13,274,576 | [
1,
758,
1724,
511,
52,
2430,
358,
13453,
39,
580,
74,
364,
21807,
13481,
18,
2725,
2864,
24899,
6610,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
443,
1724,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
309,
261,
67,
6610,
422,
374,
13,
2583,
12,
1355,
50,
4464,
87,
63,
67,
3576,
12021,
1435,
8009,
2469,
422,
374,
16,
315,
82,
1222,
729,
8863,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
67,
3576,
12021,
1435,
15533,
203,
203,
3639,
261,
11890,
5034,
389,
2890,
43,
530,
16,
2254,
5034,
389,
2938,
43,
530,
13,
273,
10443,
907,
18,
2159,
43,
530,
5621,
203,
3639,
2254,
5034,
389,
8949,
43,
530,
273,
729,
18,
8949,
18,
1289,
12,
1355,
18,
8949,
18,
16411,
24899,
2890,
43,
530,
2934,
2892,
12,
6625,
10019,
203,
203,
3639,
309,
261,
67,
8949,
43,
530,
405,
374,
13,
288,
203,
5411,
2254,
5034,
4634,
273,
389,
8949,
43,
530,
18,
16411,
12,
6011,
18,
8981,
18379,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
1769,
203,
5411,
309,
12,
9561,
405,
374,
13,
288,
203,
7734,
309,
261,
1355,
18,
2722,
758,
1724,
405,
1203,
18,
5508,
18,
1717,
12,
26,
3028,
17374,
3719,
288,
203,
10792,
4634,
273,
4634,
18,
16411,
12,
9349,
2934,
2892,
12,
6625,
1769,
203,
10792,
10443,
1345,
18,
4626,
5912,
12,
18688,
407,
3178,
16,
4634,
18,
16411,
12,
2163,
2934,
2892,
12,
6625,
10019,
203,
7734,
289,
203,
7734,
10443,
1345,
18,
4626,
2
] |
./partial_match/42/0x9553De2BBaB0d68Bda964CBE6f42c2014c73CfB7/sources/HaggleXToken.sol | * @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./emit OwnershipTransferred(address(0), _owner); | constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
_owner = tx.origin;
_frozen = false;
}
| 9,032,929 | [
1,
2785,
326,
924,
364,
288,
529,
97,
471,
288,
7175,
5779,
11643,
288,
31734,
97,
598,
279,
805,
460,
434,
6549,
18,
2974,
2027,
279,
3775,
460,
364,
288,
31734,
5779,
999,
288,
67,
8401,
31809,
5496,
4826,
8925,
434,
4259,
924,
854,
11732,
30,
2898,
848,
1338,
506,
444,
3647,
4982,
16171,
18,
19,
18356,
14223,
9646,
5310,
1429,
4193,
12,
2867,
12,
20,
3631,
389,
8443,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
3639,
389,
31734,
273,
6549,
31,
203,
203,
3639,
389,
8443,
273,
2229,
18,
10012,
31,
203,
203,
3639,
389,
28138,
273,
629,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../tools/math/WadRayMath.sol';
import '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import '../../dependencies/openzeppelin/contracts/IERC20.sol';
import '../../dependencies/compound-protocol/contracts/ICToken.sol';
import '../../misc/interfaces/IWETH.sol';
import '../../interfaces/IPoolToken.sol';
import '../../interfaces/IDerivedToken.sol';
import './DelegatedStrategyCompoundBase.sol';
contract DelegatedStrategyCompoundEth is DelegatedStrategyCompoundBase {
using SafeERC20 for IERC20;
IWETH private immutable _weth;
constructor(
string memory name,
address addressProvider,
address weth
) DelegatedStrategyBase(name, addressProvider) {
_weth = IWETH(weth);
}
function getUnderlying(address) external view override returns (address) {
return address(_weth);
}
function internalWithdrawUnderlying(
address asset,
uint256 amount,
address to
) internal override returns (uint256) {
uint256 balanceBefore = address(this).balance;
amount = internalRedeem(asset, amount);
require(address(this).balance >= balanceBefore + amount, 'CToken: redeem inconsistent');
if (amount == 0) {
return 0;
}
_weth.deposit{value: amount}();
if (to != address(this)) {
IERC20(address(_weth)).safeTransfer(to, amount);
}
return amount;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../Errors.sol';
/// @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
library WadRayMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/// @return One ray, 1e27
function ray() internal pure returns (uint256) {
return RAY;
}
/// @return One wad, 1e18
function wad() internal pure returns (uint256) {
return WAD;
}
/// @return Half ray, 1e27/2
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/// @return Half ray, 1e18/2
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/// @dev Multiplies two wad, rounding half up to the nearest wad
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfWAD) / WAD;
}
/// @dev Divides two wad, rounding half up to the nearest wad
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * WAD + halfB) / b;
}
/// @dev Multiplies two ray, rounding half up to the nearest ray
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfRAY) / RAY;
}
/// @dev Divides two ray, rounding half up to the nearest ray
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * RAY + halfB) / b;
}
/// @dev Casts ray down to wad
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / WAD_RAY_RATIO;
}
/// @dev Converts wad up to ray
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import './IERC20.sol';
import './Address.sol';
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
'SafeERC20: approve from non-zero to non-zero allowance'
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), 'SafeERC20: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, 'SafeERC20: low-level call failed');
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed');
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
/**
* @dev Interface of the ERC20 standard as defined in the EIP excluding events to avoid linearization issues.
*/
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.
*/
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
*/
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.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface ICToken {
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1 * 10^(18 - 8 + Underlying Token Decimals)
*/
function exchangeRateCurrent() external returns (uint256);
/**
* @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() external view returns (uint256);
/**
* @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 (uint256);
/// @dev Block number that interest was last accrued at
function accrualBlockNumber() external view returns (uint256);
function accrueInterest() external returns (uint256);
function balanceOfUnderlying(address) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
}
interface ICTokenErc20 is ICToken {
/// @dev Underlying asset for this CToken
function underlying() external view returns (address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
function approve(address guy, uint256 wad) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 wad
) external returns (bool);
function transfer(address dst, uint256 wad) external returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IDerivedToken.sol';
// solhint-disable func-name-mixedcase
interface IPoolToken is IDerivedToken {
function POOL() external view returns (address);
function updatePool() external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
// solhint-disable func-name-mixedcase
interface IDerivedToken {
/**
* @dev Returns the address of the underlying asset of this token (E.g. WETH for agWETH)
**/
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../tools/math/WadRayMath.sol';
import '../../tools/math/InterestMath.sol';
import '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import '../../dependencies/openzeppelin/contracts/IERC20.sol';
import '../../dependencies/compound-protocol/contracts/ICToken.sol';
import '../../interfaces/IPoolToken.sol';
import '../../interfaces/IDerivedToken.sol';
import '../../interfaces/IPriceOracle.sol';
import './DelegatedStrategyBase.sol';
abstract contract DelegatedStrategyCompoundBase is DelegatedStrategyBase {
using SafeERC20 for IERC20;
using WadRayMath for uint256;
uint32 private _msecPerBlock;
uint32 private _lastBlock = uint32(block.number);
uint32 private _lastTS = uint32(block.timestamp);
function getDelegatedState(address asset, uint40) external override returns (DelegatedState memory result) {
require(ICToken(asset).accrueInterest() == 0, 'CToken: accrueInterest failed');
uint256 rate = ICToken(asset).supplyRatePerBlock().wadToRay();
uint32 msecPerBlock = _msecPerBlock;
if (_lastBlock < uint32(block.number)) {
_updateAssetSource(asset);
uint256 v = ((block.timestamp - _lastTS) * 1000) / uint32(block.number - _lastBlock);
if (msecPerBlock > 0) {
v += msecPerBlock * 3;
v /= 4;
require(v < type(uint32).max);
}
msecPerBlock = uint32(v);
_lastTS = uint32(block.timestamp);
_lastBlock = uint32(block.number);
_msecPerBlock = msecPerBlock;
}
// Compound uses per-block rate, while the lending pool uses per-annum rate
rate *= InterestMath.MILLIS_PER_YEAR / msecPerBlock;
require(rate <= type(uint128).max);
return
DelegatedState({
liquidityIndex: uint128(WadRayMath.RAY),
variableBorrowIndex: uint128(WadRayMath.RAY),
liquidityRate: uint128(rate),
variableBorrowRate: 0,
stableBorrowRate: 0,
lastUpdateTimestamp: uint32(block.timestamp)
});
}
function _updateAssetSource(address asset) private {
if (_addressProvider != IPriceOracleProvider(address(0))) {
IPriceOracle oracle = IPriceOracle(_addressProvider.getPriceOracle());
oracle.updateAssetSource(asset);
}
}
function getDelegatedDepositIndex(address) external pure override returns (uint256) {
return WadRayMath.RAY; // CToken doesn't need indexing
}
function internalRedeem(address asset, uint256 amount) internal returns (uint256) {
if (amount == type(uint256).max) {
amount = ICToken(asset).balanceOfUnderlying(address(this));
}
require(ICToken(asset).redeemUnderlying(amount) == 0, 'CToken: redeem failed');
return amount;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
/**
* @title Errors library
* @notice Defines the error messages emitted by the different contracts
* @dev Error messages prefix glossary:
* - VL = ValidationLogic
* - MATH = Math libraries
* - CT = Common errors between tokens (DepositToken, VariableDebtToken and StableDebtToken)
* - AT = DepositToken
* - SDT = StableDebtToken
* - VDT = VariableDebtToken
* - LP = LendingPool
* - LPAPR = AddressesProviderRegistry
* - LPC = LendingPoolConfiguration
* - RL = ReserveLogic
* - LPCM = LendingPoolExtension
* - ST = Stake
*/
library Errors {
//contract specific errors
string public constant VL_INVALID_AMOUNT = '1'; // Amount must be greater than 0
string public constant VL_NO_ACTIVE_RESERVE = '2'; // Action requires an active reserve
string public constant VL_RESERVE_FROZEN = '3'; // Action cannot be performed because the reserve is frozen
string public constant VL_UNKNOWN_RESERVE = '4'; // Action requires an active reserve
string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // User cannot withdraw more than the available balance (above min limit)
string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // Transfer cannot be allowed.
string public constant VL_BORROWING_NOT_ENABLED = '7'; // Borrowing is not enabled
string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // Invalid interest rate mode selected
string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // The collateral balance is 0
string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // Health factor is lesser than the liquidation threshold
string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // There is not enough collateral to cover a new borrow
string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled
string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed
string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // The requested amount is exceeds max size of a stable loan
string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // to repay a debt, user needs to specify a correct debt type (variable or stable)
string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // To repay on behalf of an user an explicit amount to repay is needed
string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // User does not have a stable rate loan in progress on this reserve
string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // User does not have a variable rate loan in progress on this reserve
string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // The collateral balance needs to be greater than 0
string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // User deposit is already being used as collateral
string public constant VL_RESERVE_MUST_BE_COLLATERAL = '21'; // This reserve must be enabled as collateral
string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // Interest rate rebalance conditions were not met
string public constant AT_OVERDRAFT_DISABLED = '23'; // User doesn't accept allocation of overdraft
string public constant VL_INVALID_SUB_BALANCE_ARGS = '24';
string public constant AT_INVALID_SLASH_DESTINATION = '25';
string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // The caller of the function is not the lending pool configurator
string public constant LENDING_POOL_REQUIRED = '28'; // The caller of this function must be a lending pool
string public constant CALLER_NOT_LENDING_POOL = '29'; // The caller of this function must be a lending pool
string public constant AT_SUB_BALANCE_RESTIRCTED_FUNCTION = '30'; // The caller of this function must be a lending pool or a sub-balance operator
string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // Reserve has already been initialized
string public constant CALLER_NOT_POOL_ADMIN = '33'; // The caller must be the pool admin
string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // The liquidity of the reserve needs to be 0
string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // Provider is not registered
string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // Health factor is not below the threshold
string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // The collateral chosen cannot be liquidated
string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // User did not borrow the specified currency
string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // There isn't enough liquidity available to liquidate
string public constant MATH_MULTIPLICATION_OVERFLOW = '48';
string public constant MATH_ADDITION_OVERFLOW = '49';
string public constant MATH_DIVISION_BY_ZERO = '50';
string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128
string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128
string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128
string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128
string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128
string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint
string public constant CALLER_NOT_STAKE_ADMIN = '57';
string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn
string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small
string public constant CALLER_NOT_LIQUIDITY_CONTROLLER = '60';
string public constant CALLER_NOT_REF_ADMIN = '61';
string public constant VL_INSUFFICIENT_REWARD_AVAILABLE = '62';
string public constant LP_CALLER_MUST_BE_DEPOSIT_TOKEN = '63';
string public constant LP_IS_PAUSED = '64'; // Pool is paused
string public constant LP_NO_MORE_RESERVES_ALLOWED = '65';
string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66';
string public constant RC_INVALID_LTV = '67';
string public constant RC_INVALID_LIQ_THRESHOLD = '68';
string public constant RC_INVALID_LIQ_BONUS = '69';
string public constant RC_INVALID_DECIMALS = '70';
string public constant RC_INVALID_RESERVE_FACTOR = '71';
string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72';
string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73';
string public constant VL_TREASURY_REQUIRED = '74';
string public constant LPC_INVALID_CONFIGURATION = '75'; // Invalid risk parameters for the reserve
string public constant CALLER_NOT_EMERGENCY_ADMIN = '76'; // The caller must be the emergency admin
string public constant UL_INVALID_INDEX = '77';
string public constant VL_CONTRACT_REQUIRED = '78';
string public constant SDT_STABLE_DEBT_OVERFLOW = '79';
string public constant SDT_BURN_EXCEEDS_BALANCE = '80';
string public constant CALLER_NOT_REWARD_CONFIG_ADMIN = '81'; // The caller of this function must be a reward admin
string public constant LP_INVALID_PERCENTAGE = '82'; // Percentage can't be more than 100%
string public constant LP_IS_NOT_TRUSTED_FLASHLOAN = '83';
string public constant CALLER_NOT_SWEEP_ADMIN = '84';
string public constant LP_TOO_MANY_NESTED_CALLS = '85';
string public constant LP_RESTRICTED_FEATURE = '86';
string public constant LP_TOO_MANY_FLASHLOAN_CALLS = '87';
string public constant RW_BASELINE_EXCEEDED = '88';
string public constant CALLER_NOT_REWARD_RATE_ADMIN = '89';
string public constant CALLER_NOT_REWARD_CONTROLLER = '90';
string public constant RW_REWARD_PAUSED = '91';
string public constant CALLER_NOT_TEAM_MANAGER = '92';
string public constant STK_REDEEM_PAUSED = '93';
string public constant STK_INSUFFICIENT_COOLDOWN = '94';
string public constant STK_UNSTAKE_WINDOW_FINISHED = '95';
string public constant STK_INVALID_BALANCE_ON_COOLDOWN = '96';
string public constant STK_EXCESSIVE_SLASH_PCT = '97';
string public constant STK_WRONG_COOLDOWN_OR_UNSTAKE = '98';
string public constant STK_PAUSED = '99';
string public constant TXT_OWNABLE_CALLER_NOT_OWNER = 'Ownable: caller is not the owner';
string public constant TXT_CALLER_NOT_PROXY_OWNER = 'ProxyOwner: caller is not the owner';
string public constant TXT_ACCESS_RESTRICTED = 'RESTRICTED';
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// solhint-disable no-inline-assembly, avoid-low-level-calls
/**
* @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;
}
bytes32 private constant accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
function isExternallyOwned(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;
uint256 size;
assembly {
codehash := extcodehash(account)
size := extcodesize(account)
}
return codehash == accountHash && size == 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using {ReentrancyGuard}.
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data.
*
* 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: agpl-3.0
pragma solidity ^0.8.4;
import './WadRayMath.sol';
library InterestMath {
using WadRayMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant SECONDS_PER_YEAR = 365 days;
uint256 internal constant MILLIS_PER_YEAR = SECONDS_PER_YEAR * 1000;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The annual interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) {
return WadRayMath.RAY + (rate * (block.timestamp - lastUpdateTimestamp)) / SECONDS_PER_YEAR;
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
uint256 exp = currentTimestamp - lastUpdateTimestamp;
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = (exp * expMinusOne * basePowerTwo) / 2;
uint256 thirdTerm = (exp * expMinusOne * expMinusTwo * basePowerThree) / 6;
return WadRayMath.RAY + exp * ratePerSecond + secondTerm + thirdTerm;
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) {
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IPriceOracleGetter.sol';
/// @dev Interface for a price oracle.
interface IPriceOracle is IPriceOracleGetter {
function updateAssetSource(address asset) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../interfaces/IReserveDelegatedStrategy.sol';
import '../../interfaces/IPriceOracleProvider.sol';
abstract contract DelegatedStrategyBase is IReserveDelegatedStrategy {
address private immutable self = address(this);
string private _name;
IPriceOracleProvider internal immutable _addressProvider;
constructor(string memory name, address addressProvider) {
_name = name;
_addressProvider = IPriceOracleProvider(addressProvider);
}
function isDelegatedReserve() external pure override returns (bool) {
return true;
}
function getStrategyName() external view override returns (string memory) {
return _name;
}
function delegatedWithdrawUnderlying(
address asset,
uint256 amount,
address to
) external override returns (uint256) {
require(self != address(this), 'only delegated');
require(amount > 0);
return internalWithdrawUnderlying(asset, amount, to);
}
function internalWithdrawUnderlying(
address asset,
uint256 amount,
address to
) internal virtual returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
enum SourceType {
AggregatorOrStatic,
UniswapV2Pair
}
interface IPriceOracleEvents {
event AssetPriceUpdated(address asset, uint256 price, uint256 timestamp);
event EthPriceUpdated(uint256 price, uint256 timestamp);
event DerivedAssetSourceUpdated(
address indexed asset,
uint256 index,
address indexed underlyingSource,
uint256 underlyingPrice,
uint256 timestamp,
SourceType sourceType
);
}
/// @dev Interface for a price oracle.
interface IPriceOracleGetter is IPriceOracleEvents {
/// @dev returns the asset price in ETH
function getAssetPrice(address asset) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IReserveStrategy.sol';
import './IUnderlyingStrategy.sol';
/// @dev Interface to access the interest rate of an external asset
interface IReserveDelegatedStrategy is IReserveStrategy, IUnderlyingStrategy {
/// @dev all indexes and rates are expressed in ray
struct DelegatedState {
uint128 liquidityIndex;
uint128 variableBorrowIndex;
uint128 liquidityRate;
uint128 variableBorrowRate;
uint128 stableBorrowRate;
uint40 lastUpdateTimestamp;
}
function getDelegatedState(address underlyingToken, uint40 lastUpdateTimestamp)
external
returns (DelegatedState memory);
function getDelegatedDepositIndex(address underlyingToken) external view returns (uint256 liquidityIndex);
function getStrategyName() external view returns (string memory);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IPriceOracleProvider {
function getPriceOracle() external view returns (address);
function getLendingRateOracle() external view returns (address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IReserveStrategy {
function isDelegatedReserve() external view returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IUnderlyingStrategy {
function getUnderlying(address asset) external view returns (address);
function delegatedWithdrawUnderlying(
address asset,
uint256 amount,
address to
) external returns (uint256);
}
| @dev all indexes and rates are expressed in ray | function internalWithdrawUnderlying(
address asset,
uint256 amount,
address to
) internal virtual returns (uint256);
}
pragma solidity ^0.8.4;
}
}
}
pragma solidity ^0.8.4;
import './IReserveStrategy.sol';
import './IUnderlyingStrategy.sol';
struct DelegatedState {
uint128 liquidityIndex;
uint128 variableBorrowIndex;
uint128 liquidityRate;
uint128 variableBorrowRate;
uint128 stableBorrowRate;
uint40 lastUpdateTimestamp;
}
| 14,374,095 | [
1,
454,
5596,
471,
17544,
854,
26863,
316,
14961,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
2713,
1190,
9446,
14655,
6291,
12,
203,
565,
1758,
3310,
16,
203,
565,
2254,
5034,
3844,
16,
203,
565,
1758,
358,
203,
225,
262,
2713,
5024,
1135,
261,
11890,
5034,
1769,
203,
97,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
24,
31,
203,
203,
97,
203,
203,
97,
203,
203,
97,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
24,
31,
203,
203,
5666,
12871,
45,
607,
6527,
4525,
18,
18281,
13506,
203,
5666,
12871,
45,
14655,
6291,
4525,
18,
18281,
13506,
203,
203,
225,
1958,
24117,
690,
1119,
288,
203,
565,
2254,
10392,
4501,
372,
24237,
1016,
31,
203,
565,
2254,
10392,
2190,
38,
15318,
1016,
31,
203,
565,
2254,
10392,
4501,
372,
24237,
4727,
31,
203,
565,
2254,
10392,
2190,
38,
15318,
4727,
31,
203,
565,
2254,
10392,
14114,
38,
15318,
4727,
31,
203,
565,
2254,
7132,
1142,
1891,
4921,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
pragma experimental ABIEncoderV2;
//Interfaces
import './interfaces/IERC20.sol';
import './interfaces/ISettings.sol';
import './interfaces/IAddressResolver.sol';
import './interfaces/IAssetHandler.sol';
import './interfaces/IAssetVerifier.sol';
import './interfaces/IVerifier.sol';
import './interfaces/IMarketplace.sol';
//Inheritance
import './interfaces/INFTPool.sol';
import './interfaces/ISellable.sol';
//Libraries
import './openzeppelin-solidity/SafeMath.sol';
contract NFTPool is INFTPool, ISellable {
using SafeMath for uint;
IAddressResolver public ADDRESS_RESOLVER;
address private _factory;
bool private _initialized;
address public farm;
//Pool info
string public name;
address public manager;
uint public maxSupply;
uint public seedPrice;
//Token class
uint public availableC1;
uint public availableC2;
uint public availableC3;
uint public availableC4;
//User pool tokens
mapping (address => uint) public override balance;
mapping (address => mapping (uint => uint)) public override balanceOf;
uint public override totalSupply;
//Position management
mapping (uint => address) public _positionKeys;
uint public numberOfPositions;
mapping (address => uint) public positionToIndex; //maps to (index + 1), with index 0 representing position not found
constructor() {
_factory = msg.sender;
_initialized = false;
}
/* ========== VIEWS ========== */
/**
* @dev Returns the number of tokens available for each class
* @return (uint, uint, uint, uint) Number of available C1, C2, C3, and C4 tokens
*/
function getAvailableTokensPerClass() external view override returns(uint, uint, uint, uint) {
return (availableC1, availableC2, availableC3, availableC4);
}
/**
* @dev Given the address of a user, returns the number of tokens the user has for each class
* @param user Address of the user
* @return (uint, uint, uint, uint) Number of available C1, C2, C3, and C4 tokens
*/
function getTokenBalancePerClass(address user) external view override returns(uint, uint, uint, uint) {
require(user != address(0), "Invalid user address");
return (balanceOf[user][1], balanceOf[user][2], balanceOf[user][3], balanceOf[user][4]);
}
/**
* @dev Returns the USD value of the asset
* @param asset Address of the asset
* @param assetHandlerAddress Address of AssetHandler contract
*/
function getAssetValue(address asset, address assetHandlerAddress) public view override returns (uint) {
require(asset != address(0), "Invalid asset address");
require(assetHandlerAddress != address(0), "Invalid asset handler address");
uint USDperToken = IAssetHandler(assetHandlerAddress).getUSDPrice(asset);
uint numberOfDecimals = IAssetHandler(assetHandlerAddress).getDecimals(asset);
uint assetBalance = IAssetHandler(assetHandlerAddress).getBalance(address(this), asset);
return assetBalance.mul(USDperToken).div(10 ** numberOfDecimals);
}
/**
* @dev Returns the currency address and balance of each position the pool has, as well as the cumulative value
* @return (address[], uint[], uint) Currency address and balance of each position the pool has, and the cumulative value of positions
*/
function getPositionsAndTotal() public view override returns (address[] memory, uint[] memory, uint) {
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
address[] memory addresses = new address[](numberOfPositions);
uint[] memory balances = new uint[](numberOfPositions);
uint sum;
//Calculate USD value of each asset
for (uint i = 0; i < numberOfPositions; i++)
{
balances[i] = IAssetHandler(assetHandlerAddress).getBalance(address(this), _positionKeys[i.add(1)]);
addresses[i] = _positionKeys[i.add(1)];
uint numberOfDecimals = IAssetHandler(assetHandlerAddress).getDecimals(_positionKeys[i.add(1)]);
uint USDperToken = IAssetHandler(assetHandlerAddress).getUSDPrice(_positionKeys[i.add(1)]);
uint positionBalanceInUSD = balances[i].mul(USDperToken).div(10 ** numberOfDecimals);
sum = sum.add(positionBalanceInUSD);
}
return (addresses, balances, sum);
}
/**
* @dev Returns the amount of cUSD the pool has to invest
* @return uint Amount of cUSD the pool has available
*/
function getAvailableFunds() public view override returns (uint) {
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
address stableCoinAddress = IAssetHandler(assetHandlerAddress).getStableCoinAddress();
return IERC20(stableCoinAddress).balanceOf(address(this));
}
/**
* @dev Returns the value of the pool in USD
* @return uint Value of the pool in USD
*/
function getPoolValue() public view override returns (uint) {
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
uint sum = 0;
//Get USD value of each asset
for (uint i = 1; i <= numberOfPositions; i++)
{
sum = sum.add(getAssetValue(_positionKeys[i], assetHandlerAddress));
}
return sum;
}
/**
* @dev Returns the balance of the user in USD
* @return uint Balance of the user in USD
*/
function getUSDBalance(address user) public view override returns (uint) {
require(user != address(0), "Invalid address");
if (totalSupply == 0)
{
return 0;
}
uint poolValue = getPoolValue();
return poolValue.mul(balance[user]).div(totalSupply);
}
/**
* @dev Returns the price of the pool's token
* @return USD price of the pool's token
*/
function tokenPrice() public view override returns (uint) {
uint poolValue = getPoolValue();
return _tokenPrice(poolValue);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @dev Purchases the given amount of pool tokens
* @notice Call cUSD.approve() before calling this function
* @param numberOfPoolTokens Number of pool tokens to purchase
*/
function deposit(uint numberOfPoolTokens) public override {
require(numberOfPoolTokens > 0 &&
totalSupply.add(numberOfPoolTokens) <= maxSupply,
"Quantity out of bounds");
address stableCoinAddress = IAssetHandler(ADDRESS_RESOLVER.getContractAddress("AssetHandler")).getStableCoinAddress();
uint amountOfUSD = tokenPrice().mul(numberOfPoolTokens);
balance[msg.sender] = balance[msg.sender].add(numberOfPoolTokens);
totalSupply = totalSupply.add(numberOfPoolTokens);
_depositByClass(msg.sender, numberOfPoolTokens);
IERC20(stableCoinAddress).transferFrom(msg.sender, address(this), amountOfUSD);
_addPositionKey(stableCoinAddress);
emit Deposit(address(this), msg.sender, numberOfPoolTokens, amountOfUSD, block.timestamp);
}
/**
* @dev Withdraws the user's full investment
* @param numberOfPoolTokens Number of pool tokens to withdraw
* @param tokenClass Token class to withdraw from
*/
function withdraw(uint numberOfPoolTokens, uint tokenClass) public override {
address marketplaceAddress = ADDRESS_RESOLVER.getContractAddress("Marketplace");
uint index = IMarketplace(marketplaceAddress).getListingIndex(msg.sender, address(this));
require(tokenClass > 0 && tokenClass < 5, "Token class must be between 1 and 4");
require(numberOfPoolTokens > 0,
"Withdrawal amount must be greater than 0");
require(numberOfPoolTokens <= balanceOf[msg.sender][tokenClass],
"Not enough tokens");
//Account for marketplace listing
if (index > 0)
{
(,, uint listedTokenClass, uint listedTokens,) = IMarketplace(marketplaceAddress).getMarketplaceListing(index);
if (tokenClass == listedTokenClass)
{
require(numberOfPoolTokens <= balanceOf[msg.sender][tokenClass].sub(listedTokens),
"Not enough tokens");
}
}
uint managerFee = ISettings(ADDRESS_RESOLVER.getContractAddress("Settings")).getParameterValue("NFTPoolManagerFee");
uint poolValue = getPoolValue();
uint portion = numberOfPoolTokens.mul(10**18).div(totalSupply);
//Burn user's pool tokens
balance[msg.sender] = balance[msg.sender].sub(numberOfPoolTokens);
balanceOf[msg.sender][tokenClass] = balanceOf[msg.sender][tokenClass].sub(numberOfPoolTokens);
totalSupply = totalSupply.sub(numberOfPoolTokens);
//Update number of available tokens per class
if (tokenClass == 1)
{
availableC1 = availableC1.add(numberOfPoolTokens);
}
else if (tokenClass == 2)
{
availableC2 = availableC2.add(numberOfPoolTokens);
}
else if (tokenClass == 3)
{
availableC3 = availableC3.add(numberOfPoolTokens);
}
else if (tokenClass == 4)
{
availableC4 = availableC4.add(numberOfPoolTokens);
}
uint[] memory amountsWithdrawn = new uint[](numberOfPositions);
address[] memory assetsWithdrawn = new address[](numberOfPositions);
uint assetCount = numberOfPositions;
//Withdraw user's portion of pool's assets
for (uint i = assetCount; i > 0; i--)
{
uint portionOfAssetBalance = _withdrawProcessing(_positionKeys[i], portion);
if (portionOfAssetBalance > 0)
{
IERC20(_positionKeys[i]).transfer(msg.sender, portionOfAssetBalance.mul(10000 - managerFee).div(10000));
IERC20(_positionKeys[i]).transfer(manager, portionOfAssetBalance.mul(managerFee).div(10000));
amountsWithdrawn[i.sub(1)] = portionOfAssetBalance.mul(10000 - managerFee).div(10000);
assetsWithdrawn[i.sub(1)] = _positionKeys[i];
}
}
uint valueWithdrawn = poolValue.mul(portion).div(10**18);
emit Withdraw(address(this), msg.sender, numberOfPoolTokens, valueWithdrawn, assetsWithdrawn, amountsWithdrawn, block.timestamp);
}
/**
* @dev Withdraws the user's full investment
*/
function exit() external override {
for (uint i = 1; i <= 4; i++)
{
if (balanceOf[msg.sender][i] > 0)
{
withdraw(balanceOf[msg.sender][i], i);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @dev Executes a transaction on behalf of the pool; lets pool talk to other protocols
* @param to Address of external contract
* @param data Bytes data for the transaction
*/
function executeTransaction(address to, bytes memory data) public onlyPoolManager {
require(to != address(0), "Invalid 'to' address");
//First try to get contract verifier
address verifier = ADDRESS_RESOLVER.contractVerifiers(to);
//Try to get asset verifier if no contract verifier found
if (verifier == address(0))
{
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
verifier = IAssetHandler(assetHandlerAddress).getVerifier(to);
//'to' address is an asset; need to check if asset is valid
if (verifier != address(0))
{
require(IAssetHandler(assetHandlerAddress).isValidAsset(to), "NFTPool: invalid asset");
_addPositionKey(to);
}
}
require(verifier != address(0), "Invalid verifier");
(bool valid, address receivedAsset) = IVerifier(verifier).verify(address(ADDRESS_RESOLVER), address(this), to, data);
require(valid, "Invalid transaction");
(bool success, ) = to.call(data);
require(success, "Transaction failed to execute");
_addPositionKey(receivedAsset);
emit ExecutedTransaction(address(this), manager, to, success, block.timestamp);
}
/**
* @dev Removes the pool's empty positions from position keys
*/
function removeEmptyPositions() external onlyPoolManager {
uint assetCount = numberOfPositions;
for (uint i = assetCount; i > 0; i--)
{
_removePositionKey(_positionKeys[i]);
}
}
/**
* @dev Initializes the pool's data and distributes tokens by class
* @notice Meant to be called once from NFTPoolFactory contract
* @notice Token distribution: 5% C1, 10% C2, 20% C3, 65% C4
* @param poolName Name of the pool
* @param price Initial token price
* @param supplyCap Maximum number of tokens the pool can have
* @param poolManager Address of the user who managed this pool
* @param addressResolver Instance of AddressResolver interface
*/
function initialize(string memory poolName, uint price, uint supplyCap, address poolManager, IAddressResolver addressResolver) external onlyFactory notInitialized {
name = poolName;
manager = poolManager;
seedPrice = price;
maxSupply = supplyCap;
ADDRESS_RESOLVER = addressResolver;
_initialized = true;
availableC1 = (supplyCap.mul(5).div(100) > 1) ? supplyCap.mul(5).div(100) : 1;
availableC2 = (supplyCap.mul(10).div(100) > 2) ? supplyCap.mul(10).div(100) : 2;
availableC3 = (supplyCap.mul(20).div(100) > 3) ? supplyCap.mul(20).div(100) : 3;
availableC4 = supplyCap.sub(availableC3).sub(availableC2).sub(availableC1);
}
/**
* @dev Transfers tokens from seller to buyer
* @notice Meant to be called from Marketplace contract
* @param from Address of the seller
* @param to Address of the buyer
* @param tokenClass The class of the asset's token
* @param numberOfTokens Number of tokens to purchase
*/
function transfer(address from, address to, uint tokenClass, uint numberOfTokens) external override onlyMarketplaceOrFarm returns(bool) {
if (balanceOf[from][tokenClass] < numberOfTokens)
{
return false;
}
balanceOf[from][tokenClass] = balanceOf[from][tokenClass].sub(numberOfTokens);
balanceOf[to][tokenClass] = balanceOf[to][tokenClass].add(numberOfTokens);
balance[from] = balance[from].sub(numberOfTokens);
balance[to] = balance[to].add(numberOfTokens);
return true;
}
function setFarmAddress(address farmAddress) external onlyOperator {
farm = farmAddress;
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @dev Adds the given currency to position keys
* @param currency Address of token to add
*/
function _addPositionKey(address currency) internal {
//Add token to positionKeys if not currently in positionKeys
if (currency != address(0) && positionToIndex[currency] == 0)
{
numberOfPositions = numberOfPositions.add(1);
_positionKeys[numberOfPositions] = currency;
positionToIndex[currency] = numberOfPositions;
}
}
/**
* @dev Removes the given currency to position keys
* @param currency Address of token to remove
*/
function _removePositionKey(address currency) internal {
require(currency != address(0), "Invalid asset address");
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
//Remove currency from positionKeys if no balance left; account for dust
if (IAssetHandler(assetHandlerAddress).getBalance(address(this), currency) < 1000)
{
if (_positionKeys[positionToIndex[currency]] != _positionKeys[numberOfPositions])
{
_positionKeys[positionToIndex[currency]] = _positionKeys[numberOfPositions];
positionToIndex[_positionKeys[numberOfPositions]] = positionToIndex[currency];
}
delete _positionKeys[numberOfPositions];
delete positionToIndex[currency];
numberOfPositions = numberOfPositions.sub(1);
}
}
/**
* @dev Calculates the price of a pool token
* @param _poolValue Value of the pool in USD
* @return value Price of a pool token
*/
function _tokenPrice(uint _poolValue) internal view returns (uint value) {
value = (_poolValue == 0) ? seedPrice : _poolValue.div(totalSupply);
}
/**
* @dev Performs additional processing when withdrawing an asset (such as checking for staked tokens)
* @param asset Address of asset to withdraw
* @param portion User's portion of pool's asset balance
* @return Amount of tokens to withdraw
*/
function _withdrawProcessing(address asset, uint portion) internal returns (uint) {
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
address verifier = IAssetHandler(assetHandlerAddress).getVerifier(asset);
(address withdrawAsset, uint withdrawBalance, IAssetVerifier.MultiTransaction[] memory transactions) = IAssetVerifier(verifier).prepareWithdrawal(address(this), asset, portion);
if (transactions.length > 0)
{
uint initialAssetBalance;
if (withdrawAsset != address(0))
{
initialAssetBalance = IERC20(withdrawAsset).balanceOf(address(this));
}
//Execute each transaction
for (uint i = 0; i < transactions.length; i++)
{
(bool success,) = (transactions[i].to).call(transactions[i].txData);
require(success, "Failed to withdraw tokens");
}
//Account for additional tokens added (withdrawing staked LP tokens)
if (withdrawAsset != address(0))
{
withdrawBalance = withdrawBalance.add(IERC20(withdrawAsset).balanceOf(address(this))).sub(initialAssetBalance);
}
}
return withdrawBalance;
}
/**
* @dev Distributes user's deposit into different token classes based on how many tokens are available for each class
* @notice Attempt to distribute C1 first and work up to C4
* @param user Address of the user
* @param numberOfTokens Number of tokens to distribute
*/
function _depositByClass(address user, uint numberOfTokens) internal {
uint amount;
if (availableC1 > 0 && numberOfTokens > 0)
{
amount = (numberOfTokens > availableC1) ? availableC1 : numberOfTokens;
balanceOf[user][1] = balanceOf[user][1].add(amount);
availableC1 = availableC1.sub(amount);
numberOfTokens = numberOfTokens.sub(amount);
}
if (availableC2 > 0 && numberOfTokens > 0)
{
amount = (numberOfTokens > availableC2) ? availableC2 : numberOfTokens;
balanceOf[user][2] = balanceOf[user][2].add(amount);
availableC2 = availableC2.sub(amount);
numberOfTokens = numberOfTokens.sub(amount);
}
if (availableC3 > 0 && numberOfTokens > 0)
{
amount = (numberOfTokens > availableC3) ? availableC3 : numberOfTokens;
balanceOf[user][3] = balanceOf[user][3].add(amount);
availableC3 = availableC3.sub(amount);
numberOfTokens = numberOfTokens.sub(amount);
}
if (availableC4 > 0 && numberOfTokens > 0)
{
amount = (numberOfTokens > availableC4) ? availableC4 : numberOfTokens;
balanceOf[user][4] = balanceOf[user][4].add(amount);
availableC4 = availableC4.sub(amount);
numberOfTokens = numberOfTokens.sub(amount);
}
}
/* ========== MODIFIERS ========== */
modifier onlyPoolManager() {
require(msg.sender == manager, "NFTPool: Only pool's manager can call this function");
_;
}
modifier onlyFactory() {
require(msg.sender == _factory, "NFTPool: Only NFTPoolFactory can call this function");
_;
}
modifier notInitialized() {
require(!_initialized, "NFTPool: Already initialized");
_;
}
modifier onlyMarketplaceOrFarm() {
require(msg.sender == ADDRESS_RESOLVER.getContractAddress("Marketplace") ||
msg.sender == farm, "NFTPool: Only Marketplace or Farm can call this function");
_;
}
modifier onlyOperator() {
require(msg.sender == ADDRESS_RESOLVER.getContractAddress("Operator"), "NFTPool: Only Operator can call this function");
_;
}
/* ========== EVENTS ========== */
event Deposit(address indexed poolAddress, address indexed userAddress, uint numberOfPoolTokens, uint amountOfUSD, uint timestamp);
event Withdraw(address indexed poolAddress, address indexed userAddress, uint numberOfPoolTokens, uint valueWithdrawn, address[] assets, uint[] amountsWithdrawn, uint timestamp);
event ExecutedTransaction(address indexed poolAddress, address indexed manager, address to, bool success, uint timestamp);
} | * @dev Transfers tokens from seller to buyer @notice Meant to be called from Marketplace contract @param from Address of the seller @param to Address of the buyer @param tokenClass The class of the asset's token @param numberOfTokens Number of tokens to purchase/ | function transfer(address from, address to, uint tokenClass, uint numberOfTokens) external override onlyMarketplaceOrFarm returns(bool) {
if (balanceOf[from][tokenClass] < numberOfTokens)
{
return false;
}
balanceOf[from][tokenClass] = balanceOf[from][tokenClass].sub(numberOfTokens);
balanceOf[to][tokenClass] = balanceOf[to][tokenClass].add(numberOfTokens);
balance[from] = balance[from].sub(numberOfTokens);
balance[to] = balance[to].add(numberOfTokens);
return true;
}
| 12,779,993 | [
1,
1429,
18881,
2430,
628,
29804,
358,
27037,
225,
7499,
970,
358,
506,
2566,
628,
6622,
24577,
6835,
225,
628,
5267,
434,
326,
29804,
225,
358,
5267,
434,
326,
27037,
225,
1147,
797,
1021,
667,
434,
326,
3310,
1807,
1147,
225,
7922,
5157,
3588,
434,
2430,
358,
23701,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
12,
2867,
628,
16,
1758,
358,
16,
2254,
1147,
797,
16,
2254,
7922,
5157,
13,
3903,
3849,
1338,
3882,
24577,
1162,
42,
4610,
1135,
12,
6430,
13,
288,
203,
3639,
309,
261,
12296,
951,
63,
2080,
6362,
2316,
797,
65,
411,
7922,
5157,
13,
203,
3639,
288,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
203,
3639,
11013,
951,
63,
2080,
6362,
2316,
797,
65,
273,
11013,
951,
63,
2080,
6362,
2316,
797,
8009,
1717,
12,
2696,
951,
5157,
1769,
203,
3639,
11013,
951,
63,
869,
6362,
2316,
797,
65,
273,
11013,
951,
63,
869,
6362,
2316,
797,
8009,
1289,
12,
2696,
951,
5157,
1769,
203,
3639,
11013,
63,
2080,
65,
273,
11013,
63,
2080,
8009,
1717,
12,
2696,
951,
5157,
1769,
203,
3639,
11013,
63,
869,
65,
273,
11013,
63,
869,
8009,
1289,
12,
2696,
951,
5157,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0xDc6076c9D57A5d4eE0A00d964702b0Bd98F906A1/sources/StrategyValueDefiBusdLP.sol | * @dev Withdraws funds and sents them back to the vault. It withdraws {lpPair} from the RewardPool. The available {lpPair} minus fees is returned to the vault./ | function withdraw(uint256 _amount) external {
require(msg.sender == vault, "!vault");
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
if (pairBal < _amount) {
IRewardPool(rewardPool).withdraw(poolId, _amount.sub(pairBal));
pairBal = IERC20(lpPair).balanceOf(address(this));
}
if (pairBal > _amount) {
pairBal = _amount;
}
uint256 withdrawalFee = pairBal.mul(WITHDRAWAL_FEE).div(WITHDRAWAL_MAX);
IERC20(lpPair).safeTransfer(vault, pairBal.sub(withdrawalFee));
}
| 11,083,029 | [
1,
1190,
9446,
87,
284,
19156,
471,
3271,
87,
2182,
1473,
358,
326,
9229,
18,
2597,
598,
9446,
87,
288,
9953,
4154,
97,
628,
326,
534,
359,
1060,
2864,
18,
1021,
2319,
288,
9953,
4154,
97,
12647,
1656,
281,
353,
2106,
358,
326,
9229,
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,
565,
445,
598,
9446,
12,
11890,
5034,
389,
8949,
13,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
9229,
16,
17528,
26983,
8863,
203,
203,
3639,
2254,
5034,
3082,
38,
287,
273,
467,
654,
39,
3462,
12,
9953,
4154,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
309,
261,
6017,
38,
287,
411,
389,
8949,
13,
288,
203,
5411,
15908,
359,
1060,
2864,
12,
266,
2913,
2864,
2934,
1918,
9446,
12,
6011,
548,
16,
389,
8949,
18,
1717,
12,
6017,
38,
287,
10019,
203,
5411,
3082,
38,
287,
273,
467,
654,
39,
3462,
12,
9953,
4154,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
289,
203,
203,
3639,
309,
261,
6017,
38,
287,
405,
389,
8949,
13,
288,
203,
5411,
3082,
38,
287,
273,
389,
8949,
31,
203,
3639,
289,
203,
540,
203,
3639,
2254,
5034,
598,
9446,
287,
14667,
273,
3082,
38,
287,
18,
16411,
12,
9147,
40,
10821,
1013,
67,
8090,
41,
2934,
2892,
12,
9147,
40,
10821,
1013,
67,
6694,
1769,
203,
3639,
467,
654,
39,
3462,
12,
9953,
4154,
2934,
4626,
5912,
12,
26983,
16,
3082,
38,
287,
18,
1717,
12,
1918,
9446,
287,
14667,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
/* solhint-disable not-rely-on-time */
import { console } from "hardhat/console.sol";
/// @notice Errors library.
library Errors {
string internal constant _BodyEmpty = "Message body can't be empty";
string internal constant _NotOwner = "Caller isn't the owner";
string internal constant _DoesNotExist = "Message doesn't exist";
}
/// @title Messages
/// @author Philipp Muens
/// @notice Contract which stores messages.
contract Messages {
/// @notice Structure which stores a message's details.
struct Message {
uint256 id;
string body;
address owner;
uint256 createdAt;
uint256 updatedAt;
bool isEntity;
}
/// @notice Counter for the next message id.
uint256 public nextId;
/// @notice Maps a message's id to its struct.
mapping(uint256 => Message) public messages;
/// @notice Emitted when a message is created.
/// @param id The message's id.
/// @param owner The message's owner.
/// @param body The message's body.
/// @param createdAt The time when the message was created.
event CreateMessage(uint256 indexed id, address indexed owner, string body, uint256 createdAt);
/// @notice Emitted when a message is updated.
/// @param id The message's id.
/// @param owner The message's owner.
/// @param body The message's body.
/// @param updatedAt The time when the message was updated.
event UpdateMessage(uint256 indexed id, address indexed owner, string body, uint256 updatedAt);
/// @notice Emitted when a message is removed.
/// @param id The message's id.
/// @param owner The message's owner.
/// @param body The message's body.
/// @param removedAt The time when the message was removed.
event RemoveMessage(uint256 indexed id, address indexed owner, string body, uint256 removedAt);
/// @notice Checks if the caller is the owner of the message.
/// @dev Throws when the caller is not the owner of the message.
/// @param id The message's id.
modifier onlyOwner(uint256 id) {
require(msg.sender == messages[id].owner, Errors._NotOwner);
_;
}
/// @notice Checks if a message with the given id exists.
/// @dev Throws when the message doesn't exist.
/// @param id The message's id.
modifier messageExists(uint256 id) {
require(messages[id].isEntity, Errors._DoesNotExist);
_;
}
/// @notice Creates a new message.
/// @dev Logs debugging information.
/// Emits an event.
/// The owner of the new message is the caller.
/// Throws when the body is empty.
/// @param body The message's body.
/// @return The message's id.
function createMessage(string calldata body) external returns (uint256) {
require(bytes(body).length > 0, Errors._BodyEmpty);
uint256 id = nextId;
nextId++;
Message memory message = Message({
id: id,
body: body,
owner: msg.sender,
createdAt: block.timestamp,
updatedAt: block.timestamp,
isEntity: true
});
messages[id] = message;
emit CreateMessage(id, msg.sender, body, block.timestamp);
console.log("%s created a new message with id %s.", msg.sender, id);
return id;
}
/// @notice Updates an existing message.
/// @dev Logs debugging information.
/// Emits an event.
/// Throws when the message doesn't exist.
/// Throws when the caller is not the owner.
/// Throws when the body is empty.
/// @param id The message's id.
/// @param body The message's body.
/// @return A boolean which indicates whether the update was successful.
function updateMessage(uint256 id, string calldata body) external messageExists(id) onlyOwner(id) returns (bool) {
require(bytes(body).length > 0, Errors._BodyEmpty);
messages[id].body = body;
messages[id].updatedAt = block.timestamp;
emit UpdateMessage(id, msg.sender, body, block.timestamp);
console.log("%s updated the message with id %s.", msg.sender, id);
return true;
}
/// @notice Removes an existing message.
/// @dev Logs debugging information.
/// Emits an event.
/// Throws when the message doesn't exist.
/// Throws when the caller is not the owner.
/// @param id The message's id.
/// @return A boolean which indicates whether the removal was successful.
function removeMessage(uint256 id) external messageExists(id) onlyOwner(id) returns (bool) {
string memory body = messages[id].body;
delete messages[id];
emit RemoveMessage(id, msg.sender, body, block.timestamp);
console.log("%s removed the message with id %s.", msg.sender, id);
return true;
}
/// @notice Returns the message with the corresponding id.
/// @dev Logs debugging information.
/// Throws when the message doesn't exists.
/// @param id The message's id.
/// @return The message's struct fields.
function getMessage(uint256 id)
external
view
messageExists(id)
returns (
uint256,
string memory,
address,
uint256,
uint256,
bool
)
{
console.log("Loading message with id %s.", id);
return (
messages[id].id,
messages[id].body,
messages[id].owner,
messages[id].createdAt,
messages[id].updatedAt,
messages[id].isEntity
);
}
}
| @notice Removes an existing message. @dev Logs debugging information. Emits an event. Throws when the message doesn't exist. Throws when the caller is not the owner. @param id The message's id. @return A boolean which indicates whether the removal was successful. | function removeMessage(uint256 id) external messageExists(id) onlyOwner(id) returns (bool) {
string memory body = messages[id].body;
delete messages[id];
emit RemoveMessage(id, msg.sender, body, block.timestamp);
console.log("%s removed the message with id %s.", msg.sender, id);
return true;
}
| 12,844,888 | [
1,
6220,
392,
2062,
883,
18,
225,
20238,
10450,
1779,
18,
225,
7377,
1282,
392,
871,
18,
225,
22435,
1347,
326,
883,
3302,
1404,
1005,
18,
225,
22435,
1347,
326,
4894,
353,
486,
326,
3410,
18,
225,
612,
1021,
883,
1807,
612,
18,
327,
432,
1250,
1492,
8527,
2856,
326,
14817,
1703,
6873,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1206,
1079,
12,
11890,
5034,
612,
13,
3903,
883,
4002,
12,
350,
13,
1338,
5541,
12,
350,
13,
1135,
261,
6430,
13,
288,
203,
3639,
533,
3778,
1417,
273,
2743,
63,
350,
8009,
3432,
31,
203,
203,
3639,
1430,
2743,
63,
350,
15533,
203,
203,
3639,
3626,
3581,
1079,
12,
350,
16,
1234,
18,
15330,
16,
1417,
16,
1203,
18,
5508,
1769,
203,
3639,
2983,
18,
1330,
27188,
87,
3723,
326,
883,
598,
612,
738,
87,
1199,
16,
1234,
18,
15330,
16,
612,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x0000000000000aF8FE6E4DE40F4804C90fA8Ea8F/sources/contracts/EPS FOR VERIFICATION/ProxyRegister.sol | * @dev _processDeleteRecord: process record deletion/ Delete the register entry Delete the cold to hot mapping: | function _processDeleteRecord(
address hot_,
address cold_,
Participant initiator_,
uint256 provider_
) internal {
delete hotToRecord[hot_];
delete coldToHot[cold_];
emit RecordDeleted(initiator_, cold_, hot_, provider_);
}
| 3,909,984 | [
1,
67,
2567,
2613,
2115,
30,
1207,
1409,
10899,
19,
2504,
326,
1744,
1241,
2504,
326,
645,
72,
358,
12811,
2874,
30,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
389,
2567,
2613,
2115,
12,
203,
565,
1758,
12811,
67,
16,
203,
565,
1758,
645,
72,
67,
16,
203,
565,
31333,
26030,
67,
16,
203,
565,
2254,
5034,
2893,
67,
203,
225,
262,
2713,
288,
203,
565,
1430,
12811,
774,
2115,
63,
15224,
67,
15533,
203,
203,
565,
1430,
645,
72,
774,
25270,
63,
1293,
72,
67,
15533,
203,
203,
565,
3626,
5059,
7977,
12,
2738,
10620,
67,
16,
645,
72,
67,
16,
12811,
67,
16,
2893,
67,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.